Introduction to Redis Transactions

Introduction to Transactions

Welcome back! In the previous lesson, we explored the concept of batch command execution. You learned how to efficiently bundle your commands using pipelines to enhance performance. Now, let’s delve into the world of Redis Transactions — a powerful feature that ensures your commands are executed in a precise and reliable manner. This lesson will seamlessly extend what you've learned by introducing you to transactional operations in Redis. Transactions in Redis are an essential tool for executing a series of commands that act as a single atomic unit. By the end of this lesson, you will be able to:

  • Understand the fundamentals of Redis transactions.
  • Write transaction commands using Predis with MULTI and EXEC commands.
  • Write transaction code with closures.
  • Ensure reliable and consistent execution of multiple commands.

In Redis, the MULTI command in Redis starts a transaction, queuing multiple commands for atomic execution. Following MULTI, all commands that follow are enqueued rather than executed. Once all planned commands are listed, the transaction concludes with EXEC, which runs all queued commands together. MULTI and EXEC should always be used together and always in the presented sequence.

Errors in Redis Transactions and Atomicity

It is important to note that, unlike transactions in SQL, Redis transactions do not offer the option of rolling back changes if errors happen. Redis differentiates between command syntax errors and runtime errors inside a transaction:

  • Syntax Errors: If a command has incorrect syntax inside MULTI - EXEC will fail, and the transaction will not be executed at all.
  • Runtime Errors: If a command encounters an issue during execution (e.g., incrementing a string instead of a number), Redis will execute the remaining commands, but the failed command will return an error.

This means that when we enqueue 5 commands, and a runtime error occurs after the 3rd one, the first 3 commands still execute. On the other hand, if we have a syntax error in one of our 5 commands, the transaction will be aborted with an error stating that there was a problem in syntax.

Knowing these limitations is paramount when building systems and setting expectations.

The main benefit of transactions in Redis is the atomicity of the execution. Redis ensures that all commands queued in a transaction are executed in sequence without interference of any other commands. This means that no other client can execute any other command until the transaction is completed.

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