What is Transaction in Redis: Simple Explanation and Example
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.
MULTI INCR counter1 INCR counter2 EXEC
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
MULTIandEXEC. - Commands are queued and executed sequentially without interruption.
- Redis transactions do not rollback on errors; all commands run once
EXECis called. - Useful for simple atomic batches but not for complex rollback scenarios.