DeployU
Interviews / Databases / What are transactions and how do you use them in Redis?

What are transactions and how do you use them in Redis?

conceptual Transactions Interactive Quiz Code Examples

The Scenario

You are a backend engineer at a fintech company. You are writing a new service that needs to transfer money from one account to another.

The transfer consists of two separate operations: a DECRBY to the sender’s account to debit the money, and a INCRBY to the receiver’s account to credit the money.

You need to make sure that both operations are executed successfully, or that neither of them are.

The Challenge

Explain what transactions are in Redis and how you would use them to solve this problem. What are the key commands that you would use to create a transaction?

Wrong Approach

A junior engineer might try to solve this problem by just executing the two commands one after the other. This would be a very risky solution, because if the second command fails, the money will be debited from the sender's account but not credited to the receiver's account.

Right Approach

A senior engineer would know that a transaction is the perfect tool for this job. They would be able to explain what a transaction is and how to use it to make sure that both commands are executed successfully, or that neither of them are.

Step 1: Understand What Transactions Are

A transaction is a sequence of one or more commands that are executed as a single atomic unit.

Step 2: The Key Commands

CommandDescription
MULTIStarts a new transaction.
EXECExecutes all the commands in the transaction.
DISCARDDiscards all the commands in the transaction.
WATCHWatches one or more keys to detect changes to them.

Step 3: Use a Transaction

Here’s how we can use a transaction to transfer money from one account to another:

WATCH account:1 account:2
balance1 = GET account:1
balance2 = GET account:2
if balance1 >= 100:
    MULTI
    DECRBY account:1 100
    INCRBY account:2 100
    EXEC
else:
    UNWATCH

In this example, we use the WATCH command to watch the two accounts for changes. We then get the balances of the two accounts and check if the sender has enough money. If they do, we start a new transaction and execute the two commands. If they do not, we unwatch the keys.

If another client modifies one of the watched keys before the EXEC command is executed, the transaction will be aborted.

Practice Question

You are in the middle of a transaction and you want to undo all the commands that you have queued so far. Which of the following would you use?