Redis & Caching (50 Qs)•Part 2: Core Architecture & Implementation (Mid-Level)
What is the difference between Redis Transactions (MULTI/EXEC) and Lua Scripts?
senior LevelCode ExampleState ManagementSystem DesignDatabases & SQL
In Simple Words:
- MULTI / EXEC / WATCH:
MULTIqueues commands;EXECruns them sequentially.WATCHprovides optimistic locking (aborts if a key was modified beforeEXEC).- Limitation: Cannot use conditional results from one command inside the next command in the same transaction!
- Lua Scripting (
EVAL):- Executes complex conditional logic atomically inside the Redis engine.
- Guaranteed atomicity: no other script or command can run until the Lua script completes.
lua
-- Atomic check-and-decrement Lua script:
local current = redis.call('get', KEYS[1])
if current and tonumber(current) >= tonumber(ARGV[1]) then
return redis.call('decrby', KEYS[1], ARGV[1])
else
return -1
end