← Back to Backend, page 2

backend-0035 · Hard senior

How do you build a distributed lock with Redis, and why are ownership checks, lock expiry and fencing tokens needed for correctness?

A Redis lock uses SET key token NX PX ttl: it sets the key only if absent, with an expiry (a lease) so a crashed owner cannot block everybody. Release must check that the token still belongs to you (a Lua compare-and-delete). But a lease can expire while the owner is paused (garbage collection, slow network), so two clients may both think they hold the lock. For correctness, protect the shared resource with a fencing token: an increasing number issued with each lock grant, which the resource checks and uses to reject writes from older holders.

Full answer

Basic lock

  • Acquire: SET lock:resource <random token> NX PX 30000. OK means you own it.
  • Release: run a Lua script that deletes the key only if its value equals your token. A plain DEL can remove a lock that was granted to someone else after yours expired.
  • Always use an expiry. Keep it longer than the work, and extend (renew) while working if needed.

Why it is not enough

  • Leases are time based. If a process pauses longer than the TTL (long GC pause, CPU starvation, a slow call), the lock expires, another client gets it, and the first process wakes up still believing it is the owner. Both write.
  • A single Redis node can fail over before the key replicates, which grants the lock twice. Redlock (several independent nodes) reduces but does not remove the timing problem.

Fencing tokens

  • The lock service gives each grant a number that only increases. The client sends it with every write. The resource (database, storage) remembers the highest token seen and rejects lower ones. So a delayed old holder cannot overwrite newer data. This needs the resource to cooperate.

Prefer alternatives when you can

  • A database row lock or unique constraint, a compare-and-set (optimistic) update, a single consumer per queue partition, or idempotent operations. Use a distributed lock for efficiency (avoid duplicate work) rather than for correctness unless you use fencing.
javascript
const Redis = require('ioredis');
const redis = new Redis(process.env.REDIS_URL);
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

const RELEASE = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
async function acquire(owner, ttlMs) {
  const token = await redis.incr('bk35:tokens');                             // increasing number, used as the fencing token
  const ok = await redis.set('bk35:lock', owner, 'PX', ttlMs, 'NX');
  return ok ? { owner, token } : null;
}

// A storage that checks fencing tokens, and one that does not.
const storage = { value: null, highest: 0 };
const writeUnfenced = (v) => { storage.value = v; return true; };
const writeFenced = (v, token) => { if (token < storage.highest) return false; storage.highest = token; storage.value = v; return true; };

(async () => {
  await redis.del('bk35:lock', 'bk35:tokens');

  const A = await acquire('A', 100);                       // A gets the lock with a 100 ms lease...
  await sleep(150);                                        // ...then stalls (a long pause) past the lease
  const B = await acquire('B', 1000);                      // the lock expired, so B gets it
  console.log('A token:', A.token, '| B token:', B.token, '| B is the owner now:', (await redis.get('bk35:lock')) === 'B');

  writeFenced('written by B', B.token);
  console.log('A wakes up and writes, unfenced storage:', writeUnfenced('written by A (stale)'), '->', storage.value);
  storage.value = 'written by B'; storage.highest = B.token;
  console.log('A wakes up and writes, fenced storage  :', writeFenced('written by A (stale)', A.token), '->', storage.value);

  // Releasing a lock that is not yours.
  console.log('A releases with a plain DEL            :', await redis.del('bk35:lock'), '(B\'s lock is gone, though B still works)');
  await redis.set('bk35:lock', 'B', 'PX', 1000, 'NX');
  console.log('A releases with the token check        :', await redis.eval(RELEASE, 1, 'bk35:lock', 'A'), '| B still holds it:', (await redis.get('bk35:lock')) === 'B');

  await redis.del('bk35:lock', 'bk35:tokens');
  redis.disconnect();
})();

A stall is simulated with a sleep longer than the lease. It runs on one local Redis node, so failover problems and Redlock are described in the text and were not tested. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): A token: 1 | B token: 2 | B is the owner now: true A wakes up and writes, unfenced storage: true -> written by A (stale) A wakes up and writes, fenced storage : false -> written by B A releases with a plain DEL : 1 (B's lock is gone, though B still works) A releases with the token check : 0 | B still holds it: true

Key points

  • SET NX PX gives a lease; the expiry prevents permanent blocking.
  • Release only when the stored token is yours (Lua).
  • A paused owner can lose the lock without knowing.
  • Fencing tokens let the resource reject stale writers.
  • Prefer database constraints or compare-and-set when possible.

Common mistakes

  • Releasing with DEL and no token check.
  • No expiry on the lock.
  • Assuming a lock guarantees mutual exclusion even when a process pauses.
  • Using a distributed lock where a database constraint would do.
  • Renewing leases from the same thread that may be blocked.

Follow-ups

  • What is Redlock and what are the criticisms of it?
  • How would a database implement the fencing check?
  • When is an advisory lock in PostgreSQL a better choice?

Tips

  • Cover acquire, release, expiry in order.
  • Explain the pause problem.
  • Say 'fencing tokens'.