Introduction to Redis Transactions

Welcome back! In the previous lesson, we explored Redis Pipelines, which optimize command execution by batching multiple commands. Today, we’ll focus on Redis Transactions, a powerful feature that queues a group of commands for execution in a single, sequential operation.

By the end of this lesson, you’ll understand how to implement transactions in Redis using Java and Jedis.

How Redis Transactions Work

Redis Transactions allow you to queue multiple commands and then execute them sequentially once you commit (using EXEC). This is often described as an atomic operation, but it’s important to note:

  • Atomic Execution: Commands within a transaction are sent to Redis as a block.
  • (Partial) All or Nothing: If a command fails at queue time (e.g., invalid command), the entire transaction is discarded. However, if a command fails at runtime (e.g., type error), Redis will still execute the other commands.
  • Isolation: Transactions prevent other clients from executing commands on the keys being modified until the transaction completes.
  • Queuing of Commands: Commands are queued after a transaction is initiated with MULTI and only execute on EXEC.

In short, Redis discards the entire transaction if a command cannot be queued correctly, but does not roll back commands if a runtime error occurs after the transaction is committed.

Implementing Transactions in Java with Jedis

Here’s how to implement a basic transaction using Jedis in Java:

// Start a transaction and queue commands
Transaction transaction = jedis.multi();

// Add commands to the transaction
transaction.set("key1", "value1");
transaction.incr("counter");

// Commit the transaction and retrieve results
List<Object> results = transaction.exec();

// Print the transaction results
System.out.println("Transaction results: " + results);

In this example:

  • Start the Transaction: The multi() method begins the queuing process.
  • Queue Commands: set and incr are added to the queue.
  • Commit the Transaction: exec() sends all queued commands to the Redis server, which executes them in order.
  • Retrieve Results: The server’s responses are returned in a List<Object>.

A typical output might look like this:

Transaction results: [OK, 1]
  • OK for the SET command.
  • 1 for the INCR command.
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal