Redis & Caching (50 Qs)•Part 3: Advanced Internals, Scale & Production Patterns (Senior / Lead)
Atomic Operations: Redis Transactions (`MULTI`/`EXEC`) vs Lua Scripts (`EVAL`).
senior LevelCode ExampleState ManagementDatabases & SQL
In Simple Words:
MULTI/EXEC: Queues commands and runs them sequentially. Does not support rollback if a command produces a runtime error, and cannot use the result of Command 1 inside Command 2 within the same transaction.- Lua Scripts (
EVAL): Executed atomically in the Redis main thread. Can read state, execute conditional logic, and update keys without any other command interleaving!
lua
-- Atomic Rate Limiting Lua Script
local current = redis.call('INCR', KEYS[1])
if current == 1 then
redis.call('EXPIRE', KEYS[1], ARGV[1])
end
return current