Easy Tutorial
❮ Strings Incr Lists Lpop ❯

Redis Transactions

Redis transactions allow the execution of multiple commands in a single step, with the following three important guarantees:

A transaction goes through the following three phases from start to execution:


Example

Below is an example of a transaction. It starts with MULTI, queues multiple commands into the transaction, and finally triggers the transaction with the EXEC command to execute all commands in the transaction:

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 individual Redis commands is atomic, but Redis does not add any mechanisms to maintain atomicity in transactions, so the execution of Redis transactions 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 command does not cause a rollback of previously executed commands, nor does it prevent subsequent commands from executing.

>

This is the official explanation from the Redis docs:

It's important to note that even when a command fails, all 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 the command set b bbb fails, 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:

Number Command and Description
1 DISCARD <br>Discard the transaction and abort the execution of all commands within the transaction block.
2 EXEC <br>Execute all commands within the transaction block.
3 MULTI <br>Mark the beginning of a transaction block.
4 UNWATCH <br>Unwatch all keys monitored by the WATCH command.
5 WATCH key [key ...] <br>Monitor one (or multiple) keys. If the key(s) are modified by another command before the transaction is executed, the transaction will be interrupted.
❮ Strings Incr Lists Lpop ❯