Back to results for “Rate Limiting with Redis”
Redis › Strings & Bitmaps in Redis

How do you atomically increment and decrement a numeric value stored as a Redis string?

Beginner

Answer

You use INCR to atomically increase a numeric string value by one, DECR to atomically decrease it by one, or INCRBY and DECRBY to change it by a specific custom amount, all guaranteed to be safe even if many clients are trying to update the same counter simultaneously.
SET page_views 0
INCR page_views
INCRBY page_views 5
Real-world example A website safely tracks its total page view count using INCR, ensuring the counter remains accurate even when many visitors are loading pages at the exact same moment.

Common follow-ups: What happens if you try to INCR a string that does not hold a valid integer?;Is there an equivalent command for incrementing a floating point number?