Distributed Locking (Redlock)

Difficulty: Advanced

Question

How do you implement a distributed lock with Redis? What is Redlock, and what are its limitations?

Answer

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.

Why each part matters

  • Random token: without it, client A whose lock expired could DEL the lock that client B now holds.
  • Expiry: prevents a crashed client from holding the lock forever. Pick a TTL longer than the critical section, or extend it periodically (a watchdog, as Redisson does).
  • Atomic set: the old SETNX then EXPIRE pattern is two commands; a crash between them leaves a lock with no TTL. SET ... NX PX does both atomically.
  • Atomic release: GET then DEL from the client is racy; the Lua script runs both on the server.

How Redlock works

  1. Record the current time.
  2. Try SET key token NX PX ttl on each of N independent primaries with a short per-node timeout.
  3. The lock is acquired if at least N/2+1 nodes granted it and the elapsed time is less than the TTL. The remaining validity is TTL minus elapsed time minus a clock drift margin.
  4. If acquisition fails, release on all nodes.

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.

The Kleppmann critique and fencing tokens

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).

When to use what

Use caseRecommendation
Avoid duplicate work (cron on one pod, cache rebuild)Single-instance SET NX PX is fine
Occasional double execution is harmful but recoverableRedlock 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.

Acquire and safely release a lock. The token ensures a client can only release the lock it actually holds.
  1. Worker A → Redis: SET lock:job tokA NX PX 30000
  2. Redis → Worker A: OK (lock acquired)
  3. Worker B → Redis: SET lock:job tokB NX PX 30000
  4. Redis → Worker B: nil (already locked)
  5. Worker A → Redis: EVAL delete if value is tokA
  6. Redis → Worker A: 1 (released)

Code examples

Single-instance lock with safe release (Node.js, node-redis v4+)

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.

Key points

  • Acquire: SET key token NX PX ttl, one atomic command.
  • Release: Lua compare-and-delete using the random token.
  • Redlock needs a majority of N independent primaries, not replicas.
  • Lease locks can be violated by GC pauses or clock issues; use fencing tokens for correctness.
  • For money movement, prefer DB constraints and idempotency keys over Redis locks.

Common follow-up questions

  • What happens if the critical section takes longer than the lock TTL?
  • Why is SETNX followed by EXPIRE unsafe?
  • What is a fencing token and who enforces it?
  • How does a single primary with a replica break lock safety during failover?

Interview tips

  • Write the exact SET NX PX command and the Lua release; interviewers check these details.
  • Mention the Kleppmann vs antirez debate briefly and conclude with fencing tokens.
  • Distinguish efficiency locks (avoid duplicate work) from correctness locks (must never overlap).

Concepts covered

SET NX PX, Lock Token, Redlock, Fencing Token, Lua Compare-and-Delete

More Redis & Caching questions