Atomic operations and why INCR is not GET plus SET
Read-modify-write from the client loses updates; the same work inside one command cannot.
Open this lesson in the learning hubKey points
- Redis executes one command at a time, so a single command sees a consistent state and cannot interleave.
INCRparses the string as a 64-bit signed integer and fails with an error above 9223372036854775807.INCRon a missing key treats it as0, so counters need no initialisation step.- The same idea covers
HINCRBY,ZINCRBY,INCRBYFLOAT,GETDELandLPUSH- one round trip, one atomic effect. - A fixed window rate limiter is
INCRplusEXPIREon 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.