MULTI
Marks the start of a transaction block in which commands will be queued for atomic execution.
Syntax
MULTI
Details
- Available since: 1.0.0
- Time complexity: O(1).
- ACL categories:
@transaction,@write
The MULTI command is used to start a transaction block in Redis. Once MULTI is called, all subsequent commands are queued and will be executed atomically when the EXEC command is issued. This means that either all the commands in the transaction will be executed or none will, ensuring atomicity and consistency.
Examples
Starting a Transaction
To start a transaction block:
MULTI
After issuing MULTI, all subsequent commands are queued and will be executed as a single unit.
Queuing Commands
After starting the transaction with MULTI, you can queue multiple commands:
MULTI
SET key1 "value1"
SET key2 "value2"
The SET commands are queued and will be executed together when EXEC is called.
Executing the Transaction
To execute the queued commands:
EXEC
The EXEC command will run all the queued commands atomically. If any command in the transaction fails, the rest of the commands are still executed, but the result will reflect the success or failure of each command.
Example Workflow
-
Start a transaction:
MULTI -
Queue commands:
SET key1 "value1"
SET key2 "value2" -
Execute the transaction:
EXEC
The EXEC command will execute both SET commands and apply the changes.
Edge Cases
- If
MULTIis issued while already in a transaction (i.e., whileMULTIhas been called butEXEChas not been issued yet), it will simply queue the next commands. - If commands are issued before
MULTIis called, they will be executed immediately and will not be part of the transaction.
RESP2/RESP3 Reply
- Simple string reply:
OK
Example reply for MULTI:
"OK"
This indicates that the transaction block has been successfully started and subsequent commands will be queued.
Notes
- Use
DISCARDto abort a transaction and discard all queued commands if needed. - The
MULTIcommand must be followed by one or more commands and thenEXECto complete the transaction. - For pattern-based subscriptions, use
PSUBSCRIBEandPUNSUBSCRIBEin conjunction withMULTIandEXECfor transaction management.