Redis Transactions
A single Redis command is always atomic. A transaction extends that guarantee to a group of commands: they run one after another with no other client's commands in between. Redis transactions use four commands: MULTI, EXEC, DISCARD and WATCH.
MULTI and EXEC
MULTI starts a transaction. Every following command is not executed but queued, and Redis answers QUEUED. EXEC then runs the whole queue at once and returns an array with one reply per command.
SET account:ada 100
SET account:linus 20
MULTI
DECRBY account:ada 30
INCRBY account:linus 30
EXEC
MGET account:ada account:linusredis> SET account:ada 100
OK
redis> SET account:linus 20
OK
redis> MULTI
OK
redis> DECRBY account:ada 30
QUEUED
redis> INCRBY account:linus 30
QUEUED
redis> EXEC
1) (integer) 70
2) (integer) 50
redis> MGET account:ada account:linus
1) "70"
2) "50"
No other client can observe the moment where Ada's account was already debited but Linus's was not yet credited. Either both commands run, or (if the connection drops before EXEC) neither does.
DISCARD
DISCARD throws the queue away and leaves transaction mode:
SET stock 5
MULTI
DECR stock
DECR stock
DISCARD
GET stockredis> SET stock 5
OK
redis> MULTI
OK
redis> DECR stock
QUEUED
redis> DECR stock
QUEUED
redis> DISCARD
OK
redis> GET stock
"5"
Errors inside a transaction
There are two kinds of errors, and Redis handles them very differently.
1. Errors while queuing (unknown command, wrong number of arguments): Redis remembers the problem and refuses the whole transaction at EXEC:
SET counter 1
MULTI
INCR counter
INCRBY counter
EXEC
GET counterredis> SET counter 1
OK
redis> MULTI
OK
redis> INCR counter
QUEUED
redis> INCRBY counter
(error) ERR wrong number of arguments for 'incrby' command
redis> EXEC
(error) EXECABORT Transaction discarded because of previous errors.
redis> GET counter
"1"
2. Errors while executing (for example a command against the wrong type): the failing command returns an error, but the others still run. Redis does not roll back:
SET name Ada
SET visits 10
MULTI
INCR visits
INCR name
INCR visits
EXEC
GET visitsredis> SET name Ada
OK
redis> SET visits 10
OK
redis> MULTI
OK
redis> INCR visits
QUEUED
redis> INCR name
QUEUED
redis> INCR visits
QUEUED
redis> EXEC
1) (integer) 11
2) (error) ERR value is not an integer or out of range
3) (integer) 12
redis> GET visits
"12"
The second command failed, yet visits was incremented twice. Redis skips rollback on purpose: such errors are programming mistakes (wrong type, wrong key) that should be caught during development, and leaving out rollback keeps transactions simple and fast.
Note: If you come from SQL, this is the biggest difference: a Redis transaction guarantees isolation (nothing interleaves) but not rollback.
Optimistic locking with WATCH
Commands inside MULTI cannot read values and decide what to do next: you only get the results after EXEC. To implement "read a value, compute, write back" safely, Redis offers optimistic locking:
WATCH keymarks keys to observe.- Read the values you need (normal commands, not queued).
MULTI, queue the writes,EXEC.- If any watched key was modified between
WATCHandEXEC,EXECdoes nothing and returns(nil). Your program then retries from step 1.
In this first example nothing interferes, so the transaction succeeds:
SET seats:flight42 3
WATCH seats:flight42
GET seats:flight42
MULTI
DECR seats:flight42
RPUSH bookings:flight42 ada
EXEC
GET seats:flight42redis> SET seats:flight42 3
OK
redis> WATCH seats:flight42
OK
redis> GET seats:flight42
"3"
redis> MULTI
OK
redis> DECR seats:flight42
QUEUED
redis> RPUSH bookings:flight42 ada
QUEUED
redis> EXEC
1) (integer) 2
2) (integer) 1
redis> GET seats:flight42
"2"
Now we simulate a second client that changes the key after our WATCH. In real life that SET would come from another connection; any modification counts, even one from the same connection:
SET seats:flight42 3
WATCH seats:flight42
GET seats:flight42
SET seats:flight42 0
MULTI
DECR seats:flight42
RPUSH bookings:flight42 ada
EXEC
GET seats:flight42
LLEN bookings:flight42redis> SET seats:flight42 3
OK
redis> WATCH seats:flight42
OK
redis> GET seats:flight42
"3"
redis> SET seats:flight42 0
OK
redis> MULTI
OK
redis> DECR seats:flight42
QUEUED
redis> RPUSH bookings:flight42 ada
QUEUED
redis> EXEC
(nil)
redis> GET seats:flight42
"0"
redis> LLEN bookings:flight42
(integer) 0
EXEC returned (nil): the transaction was aborted, so we did not oversell a flight that had just sold out. After EXEC (successful or not) all keys are unwatched automatically; UNWATCH does it by hand.
The retry loop in application code
Client libraries wrap WATCH in a helper. In redis-py it looks like this:
import redis
r = redis.Redis(decode_responses=True)
def book_seat(flight, user):
key = f"seats:{flight}"
with r.pipeline() as pipe:
while True:
try:
pipe.watch(key) # 1. watch
seats = int(pipe.get(key) or 0) # 2. read (runs immediately)
if seats <= 0:
pipe.unwatch()
return False
pipe.multi() # 3. queue the writes
pipe.decr(key)
pipe.rpush(f"bookings:{flight}", user)
pipe.execute() # EXEC
return True
except redis.WatchError: # 4. someone changed the key: retry
continueWhen to use what
| Need | Tool |
|---|---|
| One atomic change | a single command (INCR, LMOVE, SET NX ...) |
| Several writes that must not interleave | MULTI / EXEC |
| Read, decide, then write | WATCH + MULTI / EXEC, or a Lua script |
| Complex logic with many reads and writes | a Lua script (next lesson): simpler and no retries |
Test yourself
What does Redis reply to a command sent after MULTI?
- Its normal result
- QUEUED
- OK
- (nil)
Inside a transaction, the second of three commands fails at run time with WRONGTYPE. What happens?
- All three are rolled back
- Only the first runs
- The first and third run; the second returns an error
- EXEC returns (nil)
What does EXEC return when a WATCHed key was modified after WATCH?
- An error
- (nil), and no queued command runs
- The results of the commands
- QUEUED