Distributed Locks and Fencing Tokens

Making sure only one process at a time does something across many machines, and staying safe when that guarantee breaks.

What is it?

On one machine, a mutex guarantees that only one thread enters a critical section. Across machines you want the same thing: only one worker processes a given job, only one node runs the nightly billing run, only one process writes a given file.

That's much harder in a distributed system, because:

- The lock holder can die while holding the lock. So locks must expire, usually as leases with a time limit. - The lock holder can pause without dying: a long GC pause, a VM migration, a swapped-out process. Its lease expires, someone else gets the lock, then the first process wakes up and carries on, believing it still holds the lock. - Clocks and networks lie. Messages are delayed and clocks drift, so "my lease has 2 seconds left" may be false.

So a distributed lock is best treated as an efficiency tool (avoid doing work twice) unless the resource being protected also checks a fencing token: a number that increases every time the lock is granted, so the resource can reject writes from a holder whose lease has already been superseded.

Explain like I'm 10

A lease is a meeting-room booking that expires after an hour. If you fall asleep in the room, the booking ends and someone else is given the room. Fencing is the receptionist stamping each booking with an increasing number, and the room's door only opening for the highest number it has seen: when you wake up holding booking #33, the door already saw #34 and stays shut.

Examples

Single-node Redis lease lock

// Acquire: set only if absent (NX), with an expiry (PX) so a dead
// holder doesn't block everyone forever. The random value identifies us.
const ownerToken = crypto.randomUUID();
const acquired = await redis.set("lock:invoice-run", ownerToken, {
  NX: true,
  PX: 30_000,
});
if (!acquired) return; // someone else holds it

try {
  await runInvoiceBatch();
} finally {
  // Release only if we still own it. Check-and-delete must be atomic,
  // otherwise we might delete a lock that expired and was re-acquired.
  await redis.eval(
    "if redis.call('get', KEYS[1]) == ARGV[1] then " +
      "return redis.call('del', KEYS[1]) else return 0 end",
    { keys: ["lock:invoice-run"], arguments: [ownerToken] },
  );
}

Fine for avoiding duplicate work. It's not safe for correctness: if runInvoiceBatch takes longer than 30 s (or the process pauses), a second worker can get the lock while the first is still running.

Fencing tokens at the storage layer

// The lock service returns a monotonically increasing token with each grant
// (e.g. ZooKeeper zxid / znode version, etcd revision).
const { token } = await lockService.acquire("report-file");

await storage.write("report.csv", data, { fencingToken: token });

// Inside the storage service:
let highestTokenSeen = 0;

function write(path: string, data: Buffer, fencingToken: number): void {
  if (fencingToken < highestTokenSeen) {
    throw new AppError("STALE_LOCK", "Write rejected: lock was superseded");
  }
  highestTokenSeen = fencingToken;
  persist(path, data);
}

A paused client with token 33 is rejected once a newer holder has written with token 34, no matter what the client believes about its lease. (In a real store, highestTokenSeen is persisted per resource and checked atomically with the write.)

How it works

Lease-based locks. The lock service grants a lock with a TTL. The holder must finish, or renew, before the TTL runs out. If it crashes, the lease expires and the lock frees itself. The danger is the holder that's alive but late: a stop-the-world GC pause or a slow network can stretch past the TTL without the holder knowing.

Redis locks. A single Redis instance with SET key value NX PX ttl and an atomic compare-and-delete release is a reasonable lock for efficiency. Its weaknesses: if that Redis fails over to a replica that hadn't received the key (replication is asynchronous), two clients can hold the lock.

Redlock (proposed by Redis's author) acquires the lock on a majority of N independent Redis masters (typically 5) within a time budget, and treats the remaining validity as TTL minus the time spent acquiring. Martin Kleppmann's 2016 critique, "How to do distributed locking", argued that:

- It depends on timing assumptions (bounded network delay, bounded process pauses, clocks that don't jump), which real systems violate. - It produces no fencing token, so a paused client can still corrupt the resource after its lease expired. - So it's heavier than needed for efficiency, and not safe enough for correctness.

Redis's author published a rebuttal; the debate is a good illustration that the hard part is the resource's protection, not lock acquisition.

Fencing tokens. Every successful acquisition returns a number strictly greater than any previous one. The client passes it with every operation on the protected resource, and the resource rejects any token lower than the highest it has seen. Safety no longer depends on timing; it only requires the resource to be able to check the token (a conditional write, a version column, a compare-and-set).

ZooKeeper locks. Clients create an ephemeral sequential znode under a lock path (e.g. /locks/job-0000000042). Ephemeral nodes vanish when the client's session ends, so crashes release the lock. The client with the lowest sequence number holds the lock; each other client watches only the node immediately before its own, avoiding a thundering herd when the lock is released. The zxid or the sequence number can act as a fencing token. ZooKeeper's session timeout still means a paused client can lose its lock without noticing, which is why fencing matters.

etcd locks. Clients attach keys to a lease that they keep alive. The etcd concurrency API creates a key per contender and grants the lock to the one with the lowest creation revision. Every key carries a revision (create_revision, mod_revision) that increases cluster-wide and works as a fencing token. Because etcd and ZooKeeper run on consensus, their lock state survives node failures without split grants, unlike asynchronously replicated Redis.

Why leases alone are unsafe

 Client 1   ──acquire(lease 30s)──►┐
            write ✓                │ lock service
            [ GC pause 40s ......] │
                                   │ lease expires
 Client 2   ──acquire ────────────►│ granted
            write ✓
 Client 1   (wakes) write ✓  ← corrupts data: thinks it still holds the lock

With fencing tokens

 Client 1   acquire → token 33,  write(33) ✓
            [ GC pause ]
 Client 2   acquire → token 34,  write(34) ✓   storage: highest = 34
 Client 1   write(33) ✗ rejected (33 < 34)

Why does it exist?

Leader-only jobs, exclusive access to external resources and "process each thing once" all need mutual exclusion across machines. Naive locks either deadlock when holders die or let two holders overlap when holders pause. Leases solve the first problem; fencing tokens solve the second by moving the final safety check to the resource itself.

When to use it

- Efficiency locks (avoid duplicate work, where an occasional double run is harmless): a single Redis instance with TTL is fine. - Correctness locks (double execution corrupts data or moves money): use a consensus-backed service (etcd, ZooKeeper, Consul) and have the protected resource enforce fencing tokens. - Leader election for singleton workers (schedulers, compaction jobs), usually via the same lease mechanism.

When not to use it

- If the database can enforce the invariant itself, prefer that: unique constraints, conditional updates (UPDATE ... WHERE version = ?), SELECT ... FOR UPDATE, or idempotency keys. - When work can be partitioned so each item has exactly one owner (Kafka partitions, consistent hashing), you often don't need a lock at all. - Don't use Redlock for correctness-critical mutual exclusion; it has neither consensus-backed state nor fencing. - Avoid locks on hot paths with high contention: they serialize work and add round trips.

Common mistakes

  • Releasing a lock with a plain DEL, which can delete a lock that already expired and was acquired by someone else. Release must check ownership atomically.

  • Assuming a lease means mutual exclusion. Process pauses and clock jumps let two holders overlap, so correctness needs fencing at the resource.

  • Setting no TTL, so a crashed holder blocks everyone forever, or a TTL shorter than the work's realistic worst case without renewal.

  • Renewing a lease from a background timer without checking it succeeded, then carrying on after the renewal silently failed.

  • Using a lock where an idempotent or conditional write would have enforced the same rule more simply and safely.

Practice exercises

  1. Easy:

    Explain why a distributed lock needs an expiry, and what goes wrong if the expiry is too short or too long.

  2. Medium:

    Write the release logic for a Redis lock so that a client can never delete a lock it doesn't own. Explain why the check and delete must be atomic.

  3. Hard:

    A cron-like scheduler runs on 3 nodes and must send each customer's monthly invoice exactly once. Design it with etcd: leader election, fencing, and what the invoicing database must check. Describe what happens if the leader pauses for 60 seconds mid-run.

Interview questions

Why is a distributed lock harder than a local mutex?

The holder can crash or pause without the others knowing, messages and clocks are unreliable, and the lock service itself can fail. You need expiry to survive crashes, which then allows overlapping holders when a holder is merely slow.

What is a lease?

A lock granted for a limited time. The holder must finish or renew before it expires; if the holder crashes, the lock becomes available again automatically.

How do you safely release a Redis lock?

Store a unique random value when acquiring, and release with an atomic script that deletes the key only if its value still matches. A plain DEL could remove a lock now owned by someone else.

Why isn't a single Redis instance with replication safe for correctness locks?

Replication is asynchronous. If the primary fails after granting a lock but before replicating it, the promoted replica doesn't know about it and can grant the same lock to another client.

What is Redlock and what's the main criticism?

Acquiring a lock on a majority of independent Redis masters within a time budget. Kleppmann argued its safety depends on bounded pauses, network delays and clock drift, and it issues no fencing token, so a paused client can still act after its lock expired.

What is a fencing token?

A strictly increasing number issued with each lock grant. The client sends it with every operation, and the protected resource rejects tokens lower than the highest it has seen, so a stale lock holder can't do damage.

How do you implement a lock in ZooKeeper?

Create an ephemeral sequential znode under a lock path. The lowest sequence number holds the lock; each other client watches only its predecessor. The ephemeral node disappears when the session dies, releasing the lock.

What can serve as a fencing token in etcd?

The key's revision numbers (e.g. create_revision or mod_revision), which increase monotonically across the cluster, so a newer lock holder always has a larger revision.

When should you avoid a distributed lock entirely?

When the storage can enforce the rule (unique constraints, conditional writes, compare-and-set, idempotency keys) or when you can partition work so each item has a single owner. Both avoid the timing hazards of locks.

Your external resource (e.g. a third-party API) can't check fencing tokens. How do you stay safe?

You can't get strict mutual exclusion from the lock alone. Make the operation idempotent with a deterministic idempotency key, check the lease's remaining time before each side effect and abort if it's short, keep critical sections short, and reconcile afterwards to detect and fix duplicates.