Reading — step 1 of 3
Atomic Counters
~1 min readString Commands
INCR & DECR — Atomic Counters
Redis can treat string values as integers and atomically increment or decrement them.
Commands
| Command | Description |
|---|---|
INCR key | Increment by 1 |
DECR key | Decrement by 1 |
INCRBY key amount | Increment by amount |
DECRBY key amount | Decrement by amount |
Behavior
- If the key doesn't exist, treat it as
0before operating - Returns the new value as RESP integer:
:<value>\r\n - If the stored value isn't a valid integer:
-ERR value is not an integer or out of range\r\n
Why This Matters
Atomic counters are used everywhere: page views, rate limiting, leaderboard scores, inventory counts. The atomicity guarantee means no race conditions — critical in concurrent systems.
Implementation
Parse the stored string to an integer, perform the operation, store back as string. The key insight: Redis stores everything as strings internally but interprets them as integers when needed.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…