Difficulty: Advanced
How do you implement a distributed lock with Redis? What is Redlock, and what are its limitations?
The standard single-instance lock is SET lock:resource <random-token> NX PX 30000: NX makes the set succeed only if the key does not exist, so exactly one client wins, and PX adds an expiry so the lock is released even if the holder crashes. To unlock, the client deletes the key only if it still holds its own token, using a Lua script so the check and delete are atomic. Redlock extends this to N independent Redis primaries (usually 5) and treats the lock as acquired only if a majority grant it within the validity time.
DEL the lock that client B now holds.SETNX then EXPIRE pattern is two commands; a crash between them leaves a lock with no TTL. SET ... NX PX does both atomically.GET then DEL from the client is racy; the Lua script runs both on the server.SET key token NX PX ttl on each of N independent primaries with a short per-node timeout.Redlock protects against a single Redis node failing. A single primary with a replica does not, because replication is async: the primary can grant a lock, crash before replicating, and the promoted replica grants it again.
Martin Kleppmann argued that no lease-based lock is safe for correctness on its own: a long GC pause or network delay can make a client continue working after its lock expired, while another client also holds it. Redlock additionally depends on bounded clock drift. The fix is a fencing token: a monotonically increasing number issued with each lock, which the storage layer checks and rejects if it is older than one it has already seen. Redis locks do not provide fencing tokens out of the box (you can use INCR to generate one, but the downstream system must enforce it).
| Use case | Recommendation |
|---|---|
| Avoid duplicate work (cron on one pod, cache rebuild) | Single-instance SET NX PX is fine |
| Occasional double execution is harmful but recoverable | Redlock or single lock plus idempotency |
| Correctness critical (debiting a wallet) | DB transaction, row lock or idempotency key; or a consensus system (etcd, ZooKeeper) with fencing |
For payments, a Razorpay-style idempotency key with a unique DB constraint is safer than any Redis lock.
import { randomUUID } from 'node:crypto';
const RELEASE = `
if redis.call('GET', KEYS[1]) == ARGV[1] then
return redis.call('DEL', KEYS[1])
end
return 0`;
export async function withLock(resource, ttlMs, fn) {
const key = `lock:${resource}`;
const token = randomUUID();
const ok = await redis.set(key, token, { NX: true, PX: ttlMs });
if (ok !== 'OK') throw new Error('Lock busy');
try {
return await fn();
} finally {
// Only delete if we still own it
await redis.eval(RELEASE, { keys: [key], arguments: [token] });
}
}
await withLock('settlement:2026-10-12', 60_000, runDailySettlement);
SET NX PX acquires atomically with a TTL, and the Lua script makes check-and-delete atomic so an expired holder cannot remove someone else's lock.
SET NX PX, Lock Token, Redlock, Fencing Token, Lua Compare-and-Delete