Skip to main content

A Lock Is Not Enough: Fencing Tokens and the Zombie Writer

· 12 min read
Clustron Team
Distributed Systems Engineering

A distributed lock makes a promise that sounds airtight: acquire it, and you are the only process in the fleet allowed into the critical section. Build a leader, a single writer, an exclusive owner of some resource on top of that promise, and the design looks correct — one holder at a time, enforced globally. And for the common cases it is correct. The trouble is a case that is neither common nor rare enough to ignore, and it slips through a gap the lock cannot see: the gap between the instant your code confirms it holds the lock and the instant it actually performs the write.

Picture a holder that acquires a lease-based lock — the kind that expires on its own so a crashed owner cannot wedge the resource forever. It takes the lock with a ten-second lease, begins its work, and then, mid-operation, it stops. Not crashes — stops. A stop-the-world garbage collection, a scheduler that de-prioritizes it on an overcommitted host, a VM paused for live migration, a syscall that blocks for fifteen seconds. The lease, meanwhile, keeps ticking in real time and lapses. The lock service, seeing the lease expire, correctly lets a second process acquire the lock — there is now a new, legitimate owner. Then the first process wakes up exactly where it left off, with a write half-formed in its hands and no idea any time has passed, and it completes that write. Two processes have now written to the same resource, each certain it was the sole owner.

The lock was never wrong. The new owner was elected correctly, and the old one genuinely did hold the lock when it checked. What failed is subtler: holding a lock is a fact only at the moment you verify it, and a long enough pause can strip the lock away between that verification and the write it was meant to guard. No tuning of the lease fixes this, and the fix has to live somewhere the lock cannot reach — at the resource being written.

The pause you cannot design away​

It is tempting to treat this as a tuning problem: make the lease long enough that no pause outlasts it. But the pauses that cause this are not bounded by anything you control. A stop-the-world GC can run for seconds under memory pressure; a host that is oversubscribed can starve a process of CPU for longer; a network blip between the holder and the lock service can delay a lease renewal past its deadline while the holder keeps running locally, oblivious. There is no pause length you can rule out, which means there is no lease short enough to be safe. And lengthening the lease only trades one failure for another: a thirty-second lease makes the bad window rarer, but it also means that when a holder actually crashes, the resource stays locked for thirty seconds before anyone else can take over. You cannot win the safety–liveness trade by adjusting a timer.

This is the distinction that matters. A lease solves liveness — it guarantees that a dead holder's grip eventually releases, so the system makes progress. What it does not solve is safety in the face of a holder that is merely paused: alive, lease expired, and about to act on a belief that is no longer true. The paused process is more dangerous than the crashed one precisely because it comes back. A crash is clean; the writer is gone. A pause is a zombie — it returns, confident, and completes work the system already handed to someone else.

The fencing token: a number the resource checks​

The fix is to stop trusting the holder's belief and start checking a fact at the resource. Every time the lock is granted, the lock service also hands out a fencing token: a number that strictly increases with each acquisition and is never reused. The first grant gets token 33, the next gets 34, the next 35 — monotonic, fleet-wide, never going backward. The holder must carry its token on every write to the protected resource. The resource, in turn, remembers the highest token it has ever accepted and refuses any write that arrives carrying a lower one.

Now replay the zombie with tokens attached. Holder A acquires token 33 and pauses. Its lease lapses, and holder B acquires token 34 and writes; the resource records 34 as the highest it has seen. A wakes and completes its write, stamped with token 33. The resource compares: 33 is less than 34, so this is a writer that has already been superseded, and it rejects the write. A is fenced off — not by the lock, which it unknowingly lost, but by the resource, which has moved on and can prove it.

// On acquire, the lock service returns a strictly increasing token.
token = lock.Acquire("resource:" + id, lease: 10s) // e.g. 34

// Every mutation to the protected resource carries that token.
storage.Write(id, payload, fence: token)

// Resource-side — the check that actually makes it safe:
onWrite(id, payload, fence):
if (fence < highestSeen[id]) // a stale, superseded holder
return reject("fenced: " + fence + " < " + highestSeen[id])
highestSeen[id] = fence // advance the watermark
commit(payload)

The crucial detail is where the check lives. It is at the resource — the single point every write must pass through — and nowhere else. A fencing token that the holder checks against its own state is worthless, because the holder's state is exactly the thing that went stale during the pause. Only the resource has a vantage point that the paused writer cannot have corrupted, because the resource saw the newer token arrive while the old holder was asleep.

Without fencing: both writers reach the resourceholder Apaused, then wakesholder Bnew ownerwritewritestorageaccepts both — corrupted ✗With fencing: the resource rejects the stale tokenholder Atoken 33 · pausedholder Btoken 34 · new ownerwrite(33)write(34)storage · highest = 3433 < 34 → reject ✗the watermark only moves forward

Where the token has to come from​

A fencing token is only as good as its monotonicity, and that monotonicity has a demanding requirement: it must hold across the whole fleet and survive the failure of the lock service itself. Two holders must never be handed the same number, and — the part that quietly breaks naive implementations — a number must never go backward after the component issuing tokens restarts. An in-memory counter that resets to zero on restart will happily re-issue token 5 to a new holder while the resource has already accepted token 40, and the new, legitimate owner gets fenced off by its own stale-looking token.

So the token's source has to be durable and ordered through failover. In practice it comes from one of two places: the lock's own generation or epoch number, incremented on every grant and persisted with the lock, or a separate atomic counter colocated with the lock and advanced once per acquisition. With a lease-based lock and an atomic increment — acquire the lease, bump a counter keyed to the resource, carry that value as the fence — you get exactly the property you need, provided the counter is replicated and owner-authoritative so it keeps climbing even after the node that owned it fails over to a replica. That last clause is the whole game: the one scenario a fencing token exists to survive, a holder being replaced, is also the scenario most likely to coincide with the token source itself being reassigned, so the counter must not forget its high-water mark when its owner changes.

The resource has to play along​

There is an uncomfortable condition buried in all of this: fencing only works if the protected resource enforces the check, and plenty of resources simply cannot. A dumb blob store that accepts any PUT has no concept of a token, so there is nothing to compare 33 against — the stale write lands and the scheme is decorative. You have three honest options. If the resource supports a conditional write — compare-and-set against a version — use the fencing token as that expected version, and let the resource's existing CAS do the rejecting. If it does not, put a thin gateway in front of it that holds the highestSeen watermark and enforces the comparison before forwarding. Or write to a resource that already versions every value, where the fence rides on the version check you were going to do anyway. A store whose writes natively carry a version you can condition on turns fencing from a bolted-on side-channel into a property of the normal write path — which is the cheapest place for it to live.

The principle underneath all three is the same, and it is worth stating plainly because it is the thing people get backward: the authority over who is allowed to write must sit with the thing being written, not with the thing doing the writing. A writer cannot be trusted to know whether it is still the writer, because the entire failure mode is a writer that is wrong about exactly that.

Wrap-up​

A distributed lock answers the question "who should write?" and it answers it correctly. What it cannot answer is "is the process writing right now still the one who should?" — because between the check and the write lies a pause the lock knows nothing about, and across that pause the role can quietly change hands. Lease-based locking bounds a crash, which is the clean failure. Fencing tokens bound a pause, which is the dangerous one, because the zombie comes back alive and sure of itself. Hand out a monotonic token on every acquire, carry it on every write, and make the resource reject anything below its high-water mark, and you replace a belief that can rot — "I hold the lock" — with a fact checked at the only moment that matters — "this write carries the highest token the resource has ever seen." The lock elects the writer. The fence is what enforces the election after the writer stops paying attention.