How to Use MULTI Command in Redis for Transactions
In Redis, use the
MULTI command to start a transaction block where multiple commands are queued. Then use EXEC to execute all queued commands atomically, or DISCARD to cancel them.Syntax
The MULTI command starts a transaction block. After MULTI, you queue commands that will run together. Use EXEC to run all queued commands atomically or DISCARD to cancel the transaction.
MULTI: Begin transactionCOMMAND: Any Redis command queuedEXEC: Execute all queued commandsDISCARD: Cancel the transaction
redis
MULTI COMMAND COMMAND EXEC
Example
This example shows how to use MULTI to queue commands and then execute them atomically with EXEC. All commands run together or none run if discarded.
redis
127.0.0.1:6379> MULTI OK 127.0.0.1:6379> SET key1 "Hello" QUEUED 127.0.0.1:6379> INCR counter QUEUED 127.0.0.1:6379> EXEC 1) OK 2) (integer) 1 127.0.0.1:6379> GET key1 "Hello" 127.0.0.1:6379> GET counter "1"
Output
OK
QUEUED
QUEUED
1) OK
2) (integer) 1
"Hello"
"1"
Common Pitfalls
Common mistakes when using MULTI include:
- Forgetting to call
EXEC, so commands stay queued but never run. - Running commands that cause errors inside the transaction; Redis queues them but errors appear only after
EXEC. - Using commands that depend on previous commands' results inside the transaction, which is not allowed because commands are queued, not executed immediately.
redis
127.0.0.1:6379> MULTI OK 127.0.0.1:6379> INCR counter QUEUED 127.0.0.1:6379> GET key1 QUEUED 127.0.0.1:6379> DISCARD OK 127.0.0.1:6379> GET counter "1"
Output
OK
QUEUED
QUEUED
OK
"1"
Quick Reference
| Command | Description |
|---|---|
| MULTI | Start a transaction block |
| EXEC | Execute all queued commands atomically |
| DISCARD | Cancel the transaction and clear queued commands |
| WATCH | Optional: Monitor keys for changes before EXEC |
Key Takeaways
Use MULTI to start queuing commands for a transaction in Redis.
Call EXEC to run all queued commands atomically or DISCARD to cancel.
Commands inside MULTI are queued, not executed immediately.
Avoid depending on intermediate results inside a MULTI block.
Always ensure EXEC or DISCARD is called to end the transaction.