Redis Distributed Locks (Redlock caveats)
Implement or sketch code for Redis Distributed Locks (Redlock caveats). Explain the logic, complexity, and pros/cons of this approach.
Answers use simple, clear English.
Quick interview answer
Logic: SET key token NX EX ttl acquires lock; release with Lua comparing token. Redlock multi-master debated — prefer DB advisory locks or etcd for strict correctness.
Detailed answer
Logic: SET key token NX EX ttl acquires lock; release with Lua comparing token. Redlock multi-master debated — prefer DB advisory locks or etcd for strict correctness. Complexity notes included in code section when present. Pros: Simple; fast; works for many coordination tasks. Cons: Clock skew / long GC can cause double execution; not CP like etcd. Core: SET key token NX EX ttl acquires lock; release with Lua comparing token. Redlock multi-master debated — prefer DB advisory locks or etcd for strict correctness. Real-time example: Cron job on N pods: only one runs nightly billing via Redis lock with 5min TTL + heartbeat extend. Pros: Simple; fast; works for many coordination tasks. Cons: Clock skew / long GC can cause double execution; not CP like etcd. Common mistakes: DEL without token check; no TTL (dead lock holder); lock too short for work. Best practices: Unique token + Lua release; fencing tokens for storage writes. Audience level: Tech Lead.
Full explanation
SET key token NX EX ttl acquires lock; release with Lua comparing token. Redlock multi-master debated — prefer DB advisory locks or etcd for strict correctness.
Real example & use case
Cron job on N pods: only one runs nightly billing via Redis lock with 5min TTL + heartbeat extend.
Pros & cons
Pros: Simple; fast; works for many coordination tasks. Cons: Clock skew / long GC can cause double execution; not CP like etcd.
Code example
const token = crypto.randomUUID();
const ok = await redis.set('lock:billing', token, { NX: true, EX: 300 });
if (!ok) return;
try { await runBilling(); }
finally {
const lua = 'if redis.call("get",KEYS[1])==ARGV[1] then return redis.call("del",KEYS[1]) end';
await redis.eval(lua, 1, 'lock:billing', token);
}Practice code · javascript (view only · no execution)
const token = crypto.randomUUID();
const ok = await redis.set('lock:billing', token, { NX: true, EX: 300 });
if (!ok) return;
try { await runBilling(); }
finally {
const lua = 'if redis.call("get",KEYS[1])==ARGV[1] then return redis.call("del",KEYS[1]) end';
await redis.eval(lua, 1, 'lock:billing', token);
}Common mistakes
DEL without token check; no TTL (dead lock holder); lock too short for work.
Best practices
Unique token + Lua release; fencing tokens for storage writes.
Follow-up questions
- How would you test Redis Distributed Locks (Redlock caveats)?
- What metrics prove Redis Distributed Locks (Redlock caveats) is healthy in prod?
- How does Redis Distributed Locks (Redlock caveats) change at 10× traffic?