Transactions
What is a Redis transaction?
Section titled “What is a Redis transaction?”A Redis transaction is a sequence of commands that are queued and then executed as a single, uninterrupted block. No other client’s commands can interleave between the queued commands once EXEC is called.
You open a transaction with MULTI, issue commands (they are queued, not executed immediately), then fire them all with EXEC. To abandon the queue, use DISCARD.
127.0.0.1:6379> MULTIOK127.0.0.1:6379> SET balance 100QUEUED127.0.0.1:6379> DECRBY balance 30QUEUED127.0.0.1:6379> GET balanceQUEUED127.0.0.1:6379> EXEC1) OK2) (integer) 703) "70"Notice: while inside MULTI, every command returns QUEUED instead of its result. The actual results come back as a list when EXEC fires.
MULTI
SET balance 100
DECRBY balance 30
GET balance
EXECDISCARD — abandoning a transaction
Section titled “DISCARD — abandoning a transaction”If you change your mind before calling EXEC, use DISCARD to flush the queue and exit the transaction block.
127.0.0.1:6379> MULTIOK127.0.0.1:6379> SET temp "draft"QUEUED127.0.0.1:6379> DISCARDOK127.0.0.1:6379> EXISTS temp(integer) 0MULTI
SET temp "draft"
DISCARD
EXISTS tempNo rollback — errors in Redis transactions
Section titled “No rollback — errors in Redis transactions”Redis transactions do not roll back on command errors. There are two categories of error:
- Syntax/type errors at queue time (e.g., wrong number of arguments) — these cancel the entire transaction.
- Runtime errors during EXEC (e.g., calling
INCRon a string value) — Redis continues executing the remaining commands and only that specific command fails.
127.0.0.1:6379> SET mystr "hello"OK127.0.0.1:6379> MULTIOK127.0.0.1:6379> SET k1 "a"QUEUED127.0.0.1:6379> INCR mystrQUEUED127.0.0.1:6379> SET k2 "b"QUEUED127.0.0.1:6379> EXEC1) OK2) (error) ERR value is not an integer or out of range3) OKk1 and k2 were set successfully even though INCR mystr failed. Redis does not roll back the successful commands.
Optimistic locking with WATCH
Section titled “Optimistic locking with WATCH”WATCH lets you implement a check-and-set (CAS) pattern: watch one or more keys before starting a transaction. If any watched key is modified by another client before EXEC fires, the entire transaction is aborted and EXEC returns (nil) instead of a list of results. Your code can then retry.
127.0.0.1:6379> SET stock 5OK127.0.0.1:6379> WATCH stockOK127.0.0.1:6379> MULTIOK127.0.0.1:6379> DECRBY stock 1QUEUED127.0.0.1:6379> EXEC1) (integer) 4If another client changed stock between WATCH and EXEC, the EXEC call would return (nil) and you would retry the whole sequence from WATCH.
UNWATCH cancels all watches without aborting the connection.
SET stock 5
WATCH stock
MULTI
DECRBY stock 1
EXEC
GET stock