Transactions & Atomicity

Difficulty: Intermediate

Question

How do transactions work in Redis? Explain MULTI, EXEC, DISCARD and WATCH, and what happens when a command inside a transaction fails.

Answer

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.

The four commands

  • 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.

What happens on errors

Error typeExampleResult
Queue-time errorWrong number of arguments, unknown commandEXEC is rejected with EXECABORT; nothing runs
Runtime errorINCR on a key holding a List (WRONGTYPE)That command returns an error, all others still execute
Watched key changedAnother client SET the keyEXEC 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.

Optimistic locking with WATCH

The classic check-and-set loop:

  1. WATCH wallet:42
  2. GET wallet:42 and compute the new balance in the app.
  3. MULTI, SET wallet:42 <new>, EXEC.
  4. If 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.

Transactions vs Lua scripts vs pipelines

  • A pipeline only batches network round trips; other clients' commands can interleave.
  • MULTI/EXEC gives isolation but you cannot use the result of one command to decide the next inside the transaction.
  • A Lua script (EVAL) or Function (FCALL) is also atomic and can branch on intermediate values, which is why it often replaces WATCH loops.
  • Client libraries usually send MULTI ... EXEC as one pipelined batch, so you get both.

Gotchas

  • In Redis Cluster all keys in a transaction must hash to the same slot; use hash tags like {user:42}:wallet.
  • Blocking commands such as BLPOP inside MULTI do not block; they behave like their non-blocking versions.
  • "Atomic" here does not mean durable. Without AOF always, a crash right after EXEC can still lose the writes.
Optimistic locking with WATCH. If another client touches the watched key before EXEC, the whole transaction is cancelled.
  1. Client A → Redis: WATCH stock:sku1
  2. Client A → Redis: GET stock:sku1 returns 5
  3. Client B → Redis: DECR stock:sku1 (now 4)
  4. Client A → Redis: MULTI, SET stock:sku1 4, EXEC
  5. Redis → Client A: nil: watched key changed, retry

Code examples

MULTI/EXEC and a runtime error in redis-cli

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.

WATCH-based check-and-set in Python (redis-py)

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.

Key points

  • MULTI queues, EXEC runs atomically, DISCARD cancels, WATCH adds optimistic locking.
  • No rollback: runtime errors fail only that command.
  • Syntax errors at queue time make EXEC fail with EXECABORT.
  • EXEC returns nil if any watched key changed; the client must retry.
  • Lua scripts or Functions are the better tool when logic depends on intermediate results.

Common follow-up questions

  • Why doesn't Redis support rollback?
  • How is MULTI/EXEC different from pipelining?
  • When would you use a Lua script instead of WATCH?
  • How do transactions behave in Redis Cluster?

Interview tips

  • Say clearly that Redis transactions give isolation but not rollback; that is what interviewers are fishing for.
  • Walk through the WATCH retry loop with a stock or wallet example.
  • Compare with SQL transactions briefly: no rollback, no isolation levels, single-threaded execution.

Concepts covered

MULTI, EXEC, DISCARD, WATCH, Optimistic Locking

More Redis & Caching questions