You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Redis transactions allow you to execute a group of commands atomically — either all commands in the group run, or none of them run. This prevents interleaving of commands from concurrent clients and is essential for maintaining data consistency.
Wrap commands in a transaction block using MULTI (begin) and EXEC (commit):
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379> SET balance:alice 500
QUEUED
127.0.0.1:6379> SET balance:bob 300
QUEUED
127.0.0.1:6379> DECRBY balance:alice 100
QUEUED
127.0.0.1:6379> INCRBY balance:bob 100
QUEUED
127.0.0.1:6379> EXEC
1) OK
2) OK
3) (integer) 400
4) (integer) 400
Between MULTI and EXEC, commands return QUEUED instead of executing. EXEC runs all queued commands sequentially and returns an array of results.
Cancel a queued transaction:
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379> SET temp_key "value"
QUEUED
127.0.0.1:6379> DISCARD
OK
All queued commands are discarded and the transaction is aborted.
WATCH monitors one or more keys. If any watched key is modified by another client before EXEC is called, the transaction is aborted and EXEC returns nil:
# Client A
127.0.0.1:6379> WATCH balance:alice
OK
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379> DECRBY balance:alice 50
QUEUED
127.0.0.1:6379> EXEC
# Returns nil if balance:alice was changed by another client
# Returns results array if no modification occurred
This is called optimistic locking. The application code detects the nil return, re-reads the current value, and retries the transaction.
There are two types of errors:
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379> SET counter 10
QUEUED
127.0.0.1:6379> LPUSH counter "bad" # type mismatch, will error at exec time
QUEUED
127.0.0.1:6379> INCR counter
QUEUED
127.0.0.1:6379> EXEC
1) OK
2) (error) WRONGTYPE ...
3) (integer) 11 # still executed!
Redis transactions are atomic in the sense that no other client can interleave commands between MULTI and EXEC. However, Redis does not support rollback on runtime errors — if one command fails mid-transaction, previous commands are not undone. Design your transactions carefully to avoid partial updates.
Transactions in Redis are ideal for operations like transferring balances, conditional updates with WATCH, and batching writes that must not be interleaved.
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.