Redis Transactions
A Redis transaction can execute multiple commands at once, and comes with the following three important guarantees:
- Batch operations are queued into the cache before the EXEC command is sent.
- Upon receiving the EXEC command, the transaction is executed; if any command in the transaction fails, the remaining commands are still executed.
- During transaction execution, command requests submitted by other clients are not inserted into the transaction's command sequence.
A transaction goes through the following three stages from start to execution:
- Begin the transaction.
- Queue the commands.
- Execute the transaction.
Example
Here is an example of a transaction; it first starts MULTI a transaction, then queues multiple commands into the transaction, and finally triggers EXEC the transaction via the command, executing all commands in the transaction together:
redis 127.0.0.1:6379> MULTI
OK
redis 127.0.0.1:6379> SET book-name "Mastering C++ in 21 days"
QUEUED
redis 127.0.0.1:6379> GET book-name
QUEUED
redis 127.0.0.1:6379> SADD tag "C++" "Programming" "Mastering Series"
QUEUED
redis 127.0.0.1:6379> SMEMBERS tag
QUEUED
redis 127.0.0.1:6379> EXEC
1) OK
2) "Mastering C++ in 21 days"
3) (integer) 3
4) 1) "Mastering Series"
2) "C++"
3) "Programming"
The execution of a single Redis command is atomic, but Redis does not add any mechanism to maintain atomicity on transactions, so the execution of a Redis transaction is not atomic.
A transaction can be understood as a packaged batch execution script, but the batch instructions are not atomic operations; the failure of an intermediate instruction does not cause the rollback of previously executed instructions, nor does it cause subsequent instructions to be skipped.
This is the official documentation note from redis docs on transactions:
It's important to note that even when a command fails, all the other commands in the queue are processed – Redis will not stop the processing of commands.
For example:
redis 127.0.0.1:7000> multi
OK
redis 127.0.0.1:7000> set a aaa
QUEUED
redis 127.0.0.1:7000> set b bbb
QUEUED
redis 127.0.0.1:7000> set c ccc
QUEUED
redis 127.0.0.1:7000> exec
1) OK
2) OK
3) OK
If it fails at "set b bbb", the already successful "set a" will not be rolled back, and "set c" will continue to execute.
Redis Transaction Commands
The table below lists the redis transaction related commands:
| No. | Command and Description |
|---|---|
| 1 | DISCARD |
| Discard the transaction, abandoning all commands in the transaction block. | |
| 2 | EXEC |
| Execute all commands in the transaction block. | |
| 3 | MULTI |
| Mark the start of a transaction block. | |
| 4 | UNWATCH |
| Cancel the WATCH command's monitoring of all keys. | |
| 5 | WATCH key [key ...] |
| Watch one (or more) key; if this (or these) key is modified by another command before the transaction executes, the transaction will be aborted. |