How to Use EXEC Command in Redis Transactions
In Redis,
EXEC is used to execute all commands queued after a MULTI command atomically as a transaction. It runs all queued commands in order and returns their results together.Syntax
The EXEC command is used after MULTI to execute all queued commands in a transaction. The basic flow is:
MULTI: Start the transaction and queue commands.- Queue commands: Commands are queued but not executed immediately.
EXEC: Executes all queued commands atomically.
redis
MULTI <command1> <command2> ... EXEC
Example
This example shows how to increment two keys atomically using MULTI and EXEC. Both increments happen together or not at all.
redis
127.0.0.1:6379> MULTI OK 127.0.0.1:6379> INCR counter1 QUEUED 127.0.0.1:6379> INCR counter2 QUEUED 127.0.0.1:6379> EXEC 1) (integer) 1 2) (integer) 1
Output
1) (integer) 1
2) (integer) 1
Common Pitfalls
Common mistakes when using EXEC include:
- Forgetting to call
MULTIbefore queuing commands, soEXEChas nothing to run. - Not checking for errors in queued commands;
EXECruns all commands regardless of individual errors. - Using
WATCHwithout proper handling can causeEXECto return null if keys were modified.
redis
127.0.0.1:6379> INCR counter1 (integer) 1 127.0.0.1:6379> EXEC (error) ERR EXEC without MULTI -- Correct way -- 127.0.0.1:6379> MULTI OK 127.0.0.1:6379> INCR counter1 QUEUED 127.0.0.1:6379> EXEC 1) (integer) 2
Output
(error) ERR EXEC without MULTI
1) (integer) 2
Quick Reference
| Command | Description |
|---|---|
| MULTI | Start a transaction and queue commands |
| EXEC | Execute all queued commands atomically |
| DISCARD | Cancel the transaction and clear queued commands |
| WATCH | Monitor keys for changes to conditionally abort EXEC |
Key Takeaways
Use MULTI to start queuing commands before EXEC runs them atomically.
EXEC executes all queued commands in order and returns their results together.
If EXEC is called without MULTI, Redis returns an error.
WATCH can be used to monitor keys and abort EXEC if keys change.
Always check EXEC's return to handle transaction success or failure.