0
0
RedisConceptBeginner · 3 min read

What is Transaction in Redis: Simple Explanation and Example

A transaction in Redis is a way to execute a group of commands in a single, atomic operation using MULTI and EXEC. This ensures all commands run sequentially without interruption, but Redis transactions do not support rollback on errors.
⚙️

How It Works

Think of a Redis transaction like placing multiple orders at a fast-food counter all at once. You tell the cashier all your orders first, then they prepare and deliver everything together without mixing with other customers' orders. In Redis, you start a transaction with MULTI, queue your commands, and then run EXEC to execute them all in order.

During this process, Redis queues the commands but does not run them immediately. When you send EXEC, Redis runs all queued commands one by one without interruption from other clients. However, if one command fails, Redis still runs the rest; it does not undo previous commands. This is different from traditional database transactions that support rollback.

💻

Example

This example shows how to use a Redis transaction to increment two counters atomically.

redis
MULTI
INCR counter1
INCR counter2
EXEC
Output
[1, 1]
🎯

When to Use

Use Redis transactions when you need to run multiple commands together without interference from other clients. For example, updating related counters, setting multiple keys, or performing batch operations where order matters.

However, since Redis transactions do not support rollback, avoid using them when you need full atomicity with error recovery. For complex workflows, consider Lua scripting in Redis for better control.

Key Points

  • Redis transactions group commands between MULTI and EXEC.
  • Commands are queued and executed sequentially without interruption.
  • Redis transactions do not rollback on errors; all commands run once EXEC is called.
  • Useful for simple atomic batches but not for complex rollback scenarios.

Key Takeaways

Redis transactions run multiple commands atomically using MULTI and EXEC.
Commands are queued and executed in order without interruption from other clients.
Redis transactions do not support rollback if a command fails.
Use transactions for simple grouped operations, not for complex error handling.
Lua scripting offers more control for atomic operations with error management.