Back to results for “Rate Limiting with Redis”
Redis › Hashes in Redis

How do you atomically increment a numeric field within a Redis hash?

Intermediate

Answer

You use the HINCRBY command, specifying the hash key, the field name, and the amount to increase it by, which atomically updates that specific field's numeric value, making it safe to use even when multiple clients are trying to update the same counter field simultaneously.
HINCRBY user:100 loginCount 1
HINCRBY product:55 stock -1
Real-world example An e-commerce platform atomically decreases a product's stock count field within its hash using HINCRBY whenever an order is placed, safely handling many simultaneous purchases without risking an incorrect stock count.

Common follow-ups: What happens if you try to increment a field that does not currently hold a numeric value?;Is there an equivalent command for incrementing by a floating point amount?