Difficulty: Intermediate
How do transactions work in Redis? Explain MULTI, EXEC, DISCARD and WATCH, and what happens when a command inside a transaction fails.
A Redis transaction starts with MULTI, queues every following command (each reply is QUEUED), and runs them all in one go with EXEC. Because Redis executes commands on a single thread, no other client's command can run in the middle of an EXEC, so the block is isolated and atomic in the sense of all-or-nothing execution. There is no rollback: if one queued command fails at runtime, the others still run.
MULTI: switch the connection into queuing mode.EXEC: execute the queue and return an array with one reply per command.DISCARD: throw away the queue and leave transaction mode.WATCH key [key ...]: before MULTI, mark keys for optimistic locking. If any watched key is modified by anyone before EXEC, EXEC returns a null reply and nothing runs. UNWATCH clears watches, and EXEC/DISCARD clear them automatically.| Error type | Example | Result |
|---|---|---|
| Queue-time error | Wrong number of arguments, unknown command | EXEC is rejected with EXECABORT; nothing runs |
| Runtime error | INCR on a key holding a List (WRONGTYPE) | That command returns an error, all others still execute |
| Watched key changed | Another client SET the key | EXEC returns nil; client should retry |
Redis skips rollback on purpose: runtime errors are programming bugs (wrong type) that should be caught in development, and supporting rollback would complicate the engine and slow it down.
The classic check-and-set loop:
WATCH wallet:42GET wallet:42 and compute the new balance in the app.MULTI, SET wallet:42 <new>, EXEC.EXEC returns nil, someone else changed the balance; go back to step 1.This works well under low contention. Under heavy contention many clients keep retrying, and a Lua script or Redis Function that does the read and write on the server is usually better.
MULTI/EXEC gives isolation but you cannot use the result of one command to decide the next inside the transaction.EVAL) or Function (FCALL) is also atomic and can branch on intermediate values, which is why it often replaces WATCH loops.MULTI ... EXEC as one pipelined batch, so you get both.{user:42}:wallet.BLPOP inside MULTI do not block; they behave like their non-blocking versions.always, a crash right after EXEC can still lose the writes.SET balance 500
LPUSH mylist a
MULTI
DECRBY balance 100
INCR mylist # wrong type, but only fails at EXEC time
INCRBY balance 10
EXEC
The failing INCR does not roll back the other two commands, which shows why Redis transactions are isolated but not rollback-capable.
import redis
r = redis.Redis()
def reserve_stock(sku: str, qty: int) -> bool:
key = f"stock:{sku}"
with r.pipeline() as pipe:
while True:
try:
pipe.watch(key) # optimistic lock
available = int(pipe.get(key) or 0)
if available < qty:
pipe.unwatch()
return False
pipe.multi() # start queuing
pipe.decrby(key, qty)
pipe.execute() # raises if key changed
return True
except redis.WatchError:
continue # someone else won, retry
redis-py raises WatchError when EXEC returns nil, so the loop retries until it either succeeds or finds insufficient stock.
MULTI, EXEC, DISCARD, WATCH, Optimistic Locking