Transactions in Redis
Let’s look at how transactions work in Redis.
We'll cover the following
A transaction is a sequence of commands that are executed atomically and in order. We can create transactions in Redis as well.
Let’s see how we can start a transaction in Redis.
MULTI
command
To start a new transaction, the user should execute the MULTI
command. This command tells the Redis server that a transaction has been started.
EXEC
command
When a transaction is started, the Redis client queues all commands sent by the user. When the user executes the EXEC
command, the client sends the commands to the server. All commands are executed in the order that they were provided.
DISCARD
command
If a user wants to end the transaction without executing the commands, the DISCARD
command can be used. This will inform the Redis server that the transaction has ended.
Let’s see how these commands work. Afterwards, we will learn at a few other things about Redis transactions.
In the example below, a transaction is created and after adding a few commands, it executed. When a transaction is executed, the result of each query is returned.
Similarly, we can discard a transaction as shown below:
When a transaction is running in Redis, no other client can run a query. Suppose a transaction has 70 commands. When
EXEC
is run, these 70 commands will run in the same order as they were queued. No other client will be able to run any command until these 70 commands are completed.
You can try creating a transaction in the terminal below.
Get hands-on with 1200+ tech skills courses.