Atomicity
The four ways to avoid a race.
Redis runs one command at a time, so a single command is safe. The danger is two commands with a gap.
The read-then-write race
Twenty clients each read a counter, add one, and write it back:
redis-cli GET counterAtomic single commands
The fix is to stop reading first. Each of these is one command:
INCR hits
INCR hits
LPUSH q a
LMOVE q done LEFT RIGHT
ZINCRBY board 5 adaA lock
When no single command fits, SET with NX and EX claims a lock and gives it a lifetime
in one step:
SET lock 1 NX EX 30
SET lock 1 NX EX 30
TTL lockOK means you hold it, (nil) means someone else does. The EX is not optional:
SETNX lock 1
TTL lockReleasing it safely
DEL lock is wrong: your lease may have expired. Store a token and delete only if it
matches:
redis-cli SET lock token123 EX 30
redis-cli EVAL "if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) else return 0 end" 1 lock wrongtoken
redis-cli EXISTS lockMULTI and EXEC
MULTI queues commands and EXEC runs them with nothing interleaved:
MULTI
INCR a
INCR a
EXEC
GET aWhat MULTI is not
Not a transaction in the SQL sense. A runtime failure does not stop the others, and nothing rolls back:
SET name ada
MULTI
INCR name
SET ok yes
EXEC
GET okA command Redis cannot even parse is different — the whole block is refused:
MULTI
NOSUCHCOMMAND x
SET ok yes
EXEC
EXISTS okYou also cannot branch. A GET inside the block returns its value only in the EXEC
reply, too late to use:
SET n 5
MULTI
GET n
INCR n
EXECWATCH
WATCH closes that gap: EXEC runs only if the key has not changed. Nothing touched it
here:
SET n 5
WATCH n
MULTI
INCR n
EXECIf another client writes to a watched key, EXEC abandons everything:
redis-cliEVAL
A Lua script runs as one command, so everything inside it is atomic:
EVAL "return redis.call('INCR', KEYS[1])" 1 counter
GET counterChoosing between them
| Use when | Cost | |
|---|---|---|
| One atomic command | there is one that fits | none — always try this first |
SET NX EX |
you need a lock around other work | must handle expiry and release |
MULTI/EXEC |
several writes must land together | no branching, no rollback |
WATCH |
you must read before deciding | a retry loop |
EVAL |
the logic needs branching | Lua, and it blocks the server |