Skip to content
Redis CLI

MULTI / EXEC / WATCH (Transactions)

Queue commands atomically and use optimistic locking with WATCH.

By EZ4Code Team
transactionmultiexecwatch

Code

# Atomic queue: MULTI opens, commands queue, EXEC runs them all
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379(TX)> SET counter 10
QUEUED
127.0.0.1:6379(TX)> INCR counter
QUEUED
127.0.0.1:6379(TX)> GET counter
QUEUED
127.0.0.1:6379(TX)> EXEC
1) OK
2) (integer) 11
3) "11"

# Optimistic locking with WATCH
# If the watched key changes before EXEC, the transaction aborts (nil)
127.0.0.1:6379> SET stock 5
127.0.0.1:6379> WATCH stock
OK
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379(TX)> DECR stock
QUEUED
127.0.0.1:6379(TX)> EXEC
1) (integer) 4

# Abort manually
127.0.0.1:6379> DISCARD

# Pipeline (no atomicity, but fewer round trips) — common in clients, not the CLI
# Use --pipe file for bulk inserts instead.

Explanation

MULTI starts a transaction: subsequent commands are QUEUED (not executed); EXEC runs them in order, atomically, with no other client interleaving. DISCARD cancels. WATCH key1 [key2...] is optimistic locking: if any watched key changes before EXEC, the whole transaction aborts (returns nil) — the client should retry. WATCH/MULTI/EXEC is the classic pattern for read-modify-write (e.g. decrement-if-positive). Note: Redis has no rollback on command errors — a queued command that fails at runtime (e.g. type mismatch) doesn't abort the rest. For pure throughput without atomicity, use pipelining or --pipe.

More Redis CLI Snippets