MULTI / EXEC / WATCH (Transactions)
Queue commands atomically and use optimistic locking with WATCH.
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
Connecting: URLs, TLS, AUTH & Select
Connect to standalone, TLS, authenticated, or non-default DB indexes.
Interactive Mode, HELP & Inspecting
Navigate the REPL, discover commands, and introspect the server.
Pub/Sub: SUBSCRIBE, PUBLISH & PSUBSCRIBE
Fan-out messaging with channels and pattern subscriptions.
MONITOR, SLOWLOG & Latency Debugging
Watch every command in real time and find slow queries.
EVAL, Lua & Function Stats (Server-side Scripting)
Run atomic server-side Lua scripts; load and call functions.
RDB / AOF Persistence & Backup
Trigger snapshots, manage AOF rewrite, and capture a safe backup.