Redis Database – Part 07 – Transactions

In the last blog I discussed how we can apply filters to our data. In this blog I will discuss how we deal with transactions.


If you come from a relational database background you will be very familiar with transactions. When a transaction starts, data is modified immediately and because RDBMS’s support full ACID properties, changes are isolated until either the transaction is committed or rolled back. In Redis transactions are handled somewhat differently.

A transaction is started with the MULTI command and committed with the EXEC command. For example;

   SET a 1
   SET b 2

What is not so obvious is the fact that none of the commands are executed until the EXEC command is run. Not even commands that read the keys. Redis is also single threaded when it comes to executing user queries. That means when EXEC is run, there is no possibility of another user reading or writing to any of the keys that are used within the transaction. This is one of the reasons Redis is so fast because it does not need to execute code for handling consistency and isolation when dealing with transactions. Take a look at the following commands.

   SET a 1
   SET b 2

You can probably guess what is happening here however; DISCARD is not rollback. Redis has no concept of rollback transactions because when DISCARD is run, nothing had actually executed that needs rolling back. This means that when EXEC is run, all the commands will run. If a command fails during execution, the database will be left in an inconsistent state however; there is not much that can cause it to fail. Let’s introduce a syntax error.

Notice that we had a syntax error before EXEC and when we called EXEC it aborted. This prevents design time errors.

Optimistic Locking

The commands above constitute pessimistic locking. Redis has a WATCH command that is classified as optimistic locking. The idea is that you watch one or more keys in order to make sure that keys do not change before you finish carrying out some actions before the MULTI statement is executed. If any one of those watched keys are changed by another user, the transaction will be discarded. UNWATCH is used to stop watching on all keys.

There is more information found here.

In the next blog I will discuss scalability and high availability.