Transactions & Scripting
Redis ensures data integrity through two primary methods: native transactions and Lua scripting.
1. Redis Transactions
Transactions in Redis allow a group of commands to execute as a single, atomic operation.
Key Commands:
MULTI: Marks the start of a transaction block.EXEC: Executes all commands issued after MULTI.DISCARD: Flushes all commands in a transaction.WATCH: Provides optimistic locking (Check-and-Set).
WATCH mykey
# If mykey changes between WATCH and EXEC, the transaction fails
MULTI
SET mykey "new_value"
INCR counter
EXEC[!WARNING] Redis transactions are not like RDBMS transactions. If one command fails (e.g., syntax error), other commands may still execute if they are valid. There is no automatic rollback.
2. Lua Scripting
For complex operations that require absolute atomicity and logic (if/else, loops) inside the database, Redis supports Lua scripts via the EVAL command.
Why use Lua?
- Atomicity: The entire script runs as a single operation. No other command can run while a script is executing.
- Performance: Reduces network round-trips by sending logic to the data.
Example Script:
-- Increment a value only if it exists
local current = redis.call('GET', KEYS[1])
if current then
return redis.call('INCR', KEYS[1])
else
return nil
endExecuting Lua:
EVAL "return redis.call('SET', KEYS[1], ARGV[1])" 1 mykey "myvalue"3. Comparison
| Feature | Transactions (MULTI/EXEC) | Lua Scripting (EVAL) |
|---|---|---|
| Atomicity | Atomic at execution | Atomic throughout |
| Logic | No (Just a queue) | Yes (Full programming logic) |
| Complexity | Simple | More advanced |
| Use Case | Batching simple commands | Complex conditional updates |