Atomic operations and why INCR is not GET plus SET

Redis Course · lesson 7 of 19 · 5 min read

Read-modify-write from the client loses updates; the same work inside one command cannot.

Open this lesson in the learning hub

Key points

  • Redis executes one command at a time, so a single command sees a consistent state and cannot interleave.
  • INCR parses the string as a 64-bit signed integer and fails with an error above 9223372036854775807.
  • INCR on a missing key treats it as 0, so counters need no initialisation step.
  • The same idea covers HINCRBY, ZINCRBY, INCRBYFLOAT, GETDEL and LPUSH - one round trip, one atomic effect.
  • A fixed window rate limiter is INCR plus EXPIRE on first use, keyed by user and time bucket.
  • Pipelining batches commands to save round trips but gives no atomicity - other clients can still run in between.

Example

# fixed window rate limit: 100 requests per minute per user
INCR   rate:user:1000:202608031431
EXPIRE rate:user:1000:202608031431 60 NX   # NX: only if no TTL yet (7.0+)
# if the INCR reply is > 100, reject with 429

# atomic counters on other types
HINCRBY cart:sess:abc item:991 1
ZINCRBY leaderboard 25 ada

If the new value depends on the old one, do the whole thing in one command - never GET, compute, SET.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Redis Course course, and every lesson in it is listed on the Redis Course contents page.