Skip to content
INCR & DECR — Atomic Counters
step 1/3

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

CommandDescription
INCR keyIncrement by 1
DECR keyDecrement by 1
INCRBY key amountIncrement by amount
DECRBY key amountDecrement by amount

Behavior

  • If the key doesn't exist, treat it as 0 before 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…