Redis & Caching (50 Qs)•Part 3: Advanced Internals, Scale & Production Patterns (Senior / Lead)
What is the Redlock Algorithm and how does Distributed Locking work?
senior LevelCode ExampleSystem Design
In Simple Words:
Single-instance Redis locks (SET key uuid NX PX 30000) fail if the master crashes before replicating the lock to the replica (split-brain lock acquisition):
- Redlock (Martin Kleppmann / Salvatore Sanfilippo):
- Acquire lock across $N$ independent Redis master nodes (e.g. 5 nodes).
- Use the same key and random UUID value with a short timeout.
- Lock is considered acquired if the client obtains locks from a majority ($\lfloor N/2 \rfloor + 1 = 3$) nodes within the validity time.
- Release lock across all nodes using a Lua script verifying the UUID token.
lua
-- Safe Lock Release Lua Script:
if redis.call("get", KEYS[1]) == ARGV[1] then
return redis.call("del", KEYS[1])
else
return 0
end