Table of contents
1.
Introduction
2.
Transaction
3.
MULTI/EXEC command
4.
Errors inside a transaction
5.
DISCARD command
6.
WATCH/UNWATCH command
7.
Frequently Asked Questions
7.1.
Does Redis support ACID transactions?
7.2.
Does Redis support the rollback of transactions?
7.3.
Why is Redis not ACID?
7.4.
What are Redis transactional commands?
7.5.
How do MULTI and EXEC function?
8.
Conclusion
Last Updated: Mar 27, 2024

Transactions in Redis

Introduction

To manipulate numerous structures simultaneously, we may need to make multiple calls to Redis. There are a few commands for copying or moving items between keys, but none for moving items between types efficiently. Redis Transactions enable the execution of multiple commands in a single step; they are centered around the commands WATCH, MULTI, EXEC, UNWATCH, and DISCARD. In this blog, we will discuss transactions in Redis and we will also discuss Redis transaction commands in detail with suitable examples.

Transaction

Transactions provide mainly two promises:

  • A transaction's commands are serialized and performed one after the other. During the execution of a Redis Transaction, a request received by another client will never be fulfilled; this ensures that the commands are executed as a single, independent action.
  • A Redis transaction is atomic, meaning it either takes place all at once or doesn't occur at all. There is no middle way, which means that partial transactions are not allowed. If the Redis server crashes or is killed in another method by the system administrator, just a portion of the actions may be registered. Redis will identify this state and quit with an error when restarted.

MULTI/EXEC command

A primary transaction in Redis utilizing MULTI and EXEC intends to allow one client to execute several instructions A, B, C, etc., without being interrupted by other clients.

The MULTI command is used to create a Redis Transaction. OK is the command's default response. The user can now issue several commands at this point. Redis will queue these commands instead of executing them. Once EXEC is called, all commands are performed.

Calling DISCARD will flush the transaction queue and exit the transaction.

Example:

The first example illustrates what happens when we perform MULTI and EXEC commands without instruction.

The above example illustrates what happens when we perform MULTI and EXEC commands without instruction.

As shown in the example above, EXEC produces an array of responses. Elements represent the response to single command in the transaction in the same order these commands were issued.

Errors inside a transaction

There are two types of command errors that might occur during a transaction:

  • A command may fail to be queued, resulting in an error before EXEC is invoked. In particular, the command could be syntactically incorrect, or there could be a critical condition, such as an out-of-memory situation.
  • After executing EXEC, a command may fail, for example, if we acted on a key with the incorrect value (like calling a list operation against a string value).

The server will identify an error during the accumulation of commands starting with Redis 2.6.5. It will then refuse to complete the transaction, resulting in an EXEC error, and the transaction gets discarded.

Note: Even if a command fails, all subsequent commands in the queue are executed - Redis does not halt command execution.

DISCARD command

DISCARD is a command that can be used to cancel a transaction. No commands are executed in this scenario, and the connection's state restores to normal.

Example:

WATCH/UNWATCH command

WATCH is used to provide Redis transactions a check-and-set (CAS) behavior.

It's a command that makes the EXEC conditional: we're telling Redis to execute the transaction only if none of the WATCHed keys have been changed. This includes changes performed by the client, such as write commands and changes made by Redis itself, such as expiration or eviction. The transaction aborts if at least one watched key gets modified before the EXEC command, and EXEC delivers a Null response to indicate that the transaction failed.

WATCH is a command that can be used several times. Said, all WATCH calls will have the effect of watching for changes from when the call is made until EXEC is called. You can also use a single WATCH call to send any number of keys.

Regardless of whether the transaction was aborted or not, when EXEC called, all keys were UNWATCHED. Everything is also UNWATCHED when a client connection is closed.

It's also possible to flush all the watched keys with the UNWATCH command (without arguments). UNWATCH is sometimes handy when we optimistically lock a few keys because we may need to run a transaction to alter those keys, but we don't want to proceed after reading the current content of the keys. When this happens, we immediately use UNWATCH to use the connection for new transactions.

Example:

Consider the case where we need to atomically increment the value of a key by 1 (assuming Redis lacks INCR).

Val = GET mykey
Val = Val + 1
SET mykey $Val

There will be a race condition if multiple clients try to increment the key simultaneously. Clients A and B, for example, will read the old value of 10, Both clients will increment the value to 11, and then the value of the key will be SET. As a result, instead of 12, the final value will be 11.

WATCH mykey
Val = GET mykey
Val = Val + 1
MULTI
SET mykey $Val
EXEC

If there are race conditions in the above code and another client updates the result of Val between our calls to WATCH and EXEC, the transaction will fail.

Frequently Asked Questions

Does Redis support ACID transactions?

Transactions in Redis are not entirely ACID compliant ( Atomicity, Consistency, Isolation, and Durability). If ACID transactions are required, Redis is not the best choice. In those cases, employ an RDBMS or another database system.

Does Redis support the rollback of transactions?

Redis does not offer transaction rollbacks because doing so would detract significantly from Redis' simplicity and performance.

Why is Redis not ACID?

Redis is lacking the D in ACID, which means that a correctly performed command is not guaranteed to persist to disk because Redis only flushes its data to disk at configurable intervals (if persistence is enabled). As a result, if your server fails, the changes made since the last flush are lost.

What are Redis transactional commands?

Redis Transactions enable the execution of multiple commands in a single step; the transaction commands are WATCH, MULTI, EXEC, UNWATCH, and DISCARD.

How do MULTI and EXEC function?

We use the MULTI command to create a Redis Transaction. OK is the command's default response. The user can now issue several commands at this point. Redis will queue these commands instead of executing them. Once we call EXEC, all commands are performed.

Conclusion

In this article, we have discussed transactions in Redis. We have discussed each command of the Redis transaction in depth.

After learning what transaction is in Redis and how to use it, are you curious to explore more articles on the topic related to DBMS? We have you covered. Check out MongoDBDatabasesOperational Databases, Non-relational databases, and Top-100 SQL Problems.

Refer to guided paths on Coding Ninjas Studio to upskill yourself in Data Structure and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more. If you want to test your competency in coding, you may check out the mock test series and participate in a contest hosted by Coding Ninjas Studio! But suppose you have just started the learning process and looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problemsinterview experiences, and interview bundle for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy learning!

Live masterclass