Skip to content
Redis CLI

MULTI / EXEC / WATCH (Transactions)

Queue commands atomically and use optimistic locking with WATCH.

#transaction#multi#exec#watch

Code

redis-cli
# 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.