The shape
A process often needs something to itself: a lock on a row, a lease on a file, or leadership of a cluster. A lease is a lock with a time limit. It expires on its own unless the holder keeps renewing it. Whatever holds the lock right now is the holder. It takes the lock, does its work, and hands it back. That is the normal path, and most designs draw only that path.
The problem is that a lease can expire without the holder finding out. Four ways that happens:
- The process freezes for a garbage collection pause.
- The virtual machine it runs on is paused so it can be moved to another host.
- The container hits its CPU quota, and the kernel throttles it until it barely runs.
- The network stops delivering its packets, while the process keeps running and notices nothing.
In every one of these, the holder is either not running or not reachable, but the clock keeps going. The lease expires, and the lock is given to another process. Then the first process comes back. It is still sure it holds the lock, and it writes.
A process can keep believing it holds a lock long after it has lost it. You cannot prevent this. To prevent it, the process would have to notice the expiry while it is not running, and a process cannot do that. A longer lease does not help either. It only means a longer pause is needed to break it, and a pause has no upper limit.
So this pattern does not try to stop a second holder from existing. Instead, it makes the old holder's writes harmless.
The mechanism
The mechanism has three parts, and designs most often leave out the third.
- Every lock comes with a number. The number goes up by one each time the lock is handed out. The first holder gets 1, the next gets 2, and the number never goes back down. This number is called a fencing token. When the lock is leadership of a cluster, it is usually called an epoch.
- Every write the holder sends carries that number. The number travels inside the request. It is not a variable that the process checks for itself before writing.
- The thing being written to remembers the highest number it has seen, and refuses anything lower. This is usually a database, but it can be any store or service.
That third step is the whole pattern. The old holder wakes up and sends a write that carries the number 4. The database has already accepted a write that carried 5, so it refuses this one. Being told no is how the old holder finds out it is not the holder any more. It has no other way to find out, because everything else it knows is from before the pause.
The same idea, under four names
This idea is not new, and nobody invented it for your system. Mature distributed systems already use it, so you can name them instead of deriving the whole argument from scratch.
| system | the number | who compares it |
|---|---|---|
| Raft | term | followers, on every append |
| Kafka | leader epoch | followers, when deciding where to truncate |
| Chubby | the sequencer's lock generation number | the file server being written to |
| GFS | chunk version number | chunkservers |
Kafka's history shows how hard this is to get right. Kafka used to decide how far a follower should cut back its log by looking at the high watermark. That is the point in the log up to which every in-sync replica has copied the data. In some failover sequences, this left the leader and the follower holding different data. Kafka publishes its design changes as numbered Kafka Improvement Proposals (KIPs). The one that fixed this, KIP-101, replaced the high watermark with the leader epoch. Later, leadership changing twice in a short time turned up more ways for the two logs to end up different, and a follow-up proposal, KIP-279, fixed those. Kafka's whole product is an ordered log, and its team still needed two attempts at this. Do not expect to get it right by guessing.
When the other side cannot check
Sometimes you do not own the thing you are protecting. It might be a payment API somebody else runs, an SFTP server, a printer, or a vendor's database. None of them will check a number you made up.
Chubby has a fallback for this, called a lock delay. If a holder loses its lease without handing the lock back properly, Chubby lets nobody else take that lock for a while, usually around a minute. The delay puts the two writers in order by time. The number puts them in order by comparison: the database sees the old number and refuses that write. Here nothing on the other side can compare numbers, so nothing can refuse the old write. Instead, you wait until the old write has already happened. The cost is a minute of downtime every time a lease is lost this way. The other side cannot check anything, so waiting is the only thing you have left to trade.
After a minute, the old holder has either woken up, found its lease expired and stopped, or it has died. Either way, its writes have already landed by the time the new holder sends its first one. You still get one writer at a time, but you get it by waiting instead of by checking.
This is the weaker answer, because it rests on a guess: that a minute is longer than any pause you will ever see. If moving the old holder's virtual machine to another host pauses it for 90 seconds, the old holder wakes up after the new one has already started work. Both are writing. Nothing in the path can tell, so nothing reports an error. The number does not depend on any guess about timing.
So do this on paper before you build anything. List every place the holder writes to. Next to each one, mark whether it can check a number. The design follows from that list. Everything that can check gets the number. Everything that cannot check gets one of three things instead. It gets a lock delay, or a design where doing the same write twice is harmless, or a service of your own in front of it that does the checking.
The lease is 10 s. The holder promises to stop before it expires.
a JVM full GC pause 1.5 s survivable
a container throttled by cgroup 8 s marginal
a VM paused for live migration 30 s lease long gone
a network path blackholed minutes lease long gone
Raise the lease to 60 s to cover the VM pause
→ failover now takes at least 60 s, always,
for every real failure, forever
Raise it to 300 s to be safe
→ a genuinely dead leader costs 5 minutes of downtime
No lease length is both short enough to fail over quickly
and long enough to outlast a pause that has no upper limit.
The number removes the choice. Keep the lease short, accept
that two holders will sometimes exist, and let the database
throw the stale one's writes away.What it costs
The mechanism itself is cheap: one integer on every request, and one comparison at the other end. The costs are elsewhere.
Every place the holder writes has to take part. If even one place does not check, the old holder's writes get through there, and the guarantee is gone. The pattern is only as strong as the weakest place in the path.
The number has to survive a restart. Whatever hands out the locks must not start counting from 1 again. If it does, it hands out a number it has used before, and every comparison after that is meaningless.
A refused write needs somewhere to go. A holder that is told no should stop what it is doing and give up the lock. It should not retry. This handling on the client side matters as much as the check on the server side.
Where it shows up in the course
| article | the form it takes there |
|---|---|
| Design a Distributed Job Scheduler | the attempt number and the region's epoch together fence one run; the pair, compared epoch first, never goes down |
| Design a Distributed Message Queue | every batch carries its leader's epoch, and a returning broker truncates to where its last epoch ended |
| Design a Payment System | the claim number fences our own rows; the processor never sees it, so the call is protected by every resolver sending the same key |
| Design Google Docs (Collaborative Editing) | each claim raises the epoch in the document's header row, and every append checks it in the same transaction |
| Distributed Transactions and Sagas | a late retry of an old saga step, refused because the row's held_by no longer names that booking |
| Idempotency and Exactly-Once Delivery | ordering a retry against the work it duplicates, so a late arrival cannot overwrite a newer result |
| Key-Value Store | every log entry carries the leader's epoch, so a leader that paused through its lease has its next entry refused |
| Multi-Region and Disaster Recovery | a lease tells the old region to stop, and the epoch on every write refuses what it already sent |
| Quorums, Raft and Paxos | consensus can name the leader and cannot mute the previous one |
| Replication and Leader Election | why a lease alone permits two leaders, and where the term is checked |
| Ticketmaster Booking | held_by as the fence: every write to a seat names the order that owns it, so a late retry or release changes nothing |
| Uber Ride-Hailing | offer_id on the trip and driver rows fences off a late accept or a late release |
| Web Crawler | a partition's lease carries an epoch, and the new owner also waits out the politeness gap, because a website can't be fenced |
| WhatsApp and Chat Systems | a reconnecting device whose old socket is still registered, and the number that settles which one wins |
| Write-Ahead Logs | Raft's term is the epoch: every record carries it, and a follower rejects records from an older term |
Getting it wrong
Checking inside the holder instead of at the database. "The process checks that its lease is still valid before it writes" sounds like the same thing. It is not. The process can run the check, pass it, and then freeze before the write goes out. When it wakes up, it sends the write without checking again, because as far as it knows the check has just passed.
Letting the number start again from 1. If whatever hands out the locks can restart and reuse a number, the comparison at the other end is worthless.
Retrying after a rejection. Being told no means you are not the holder any more. Sending the same write again with the same number cannot work. It is worse to take a fresh lock and send the same write again without re-reading the current state, because you will overwrite whatever the real holder did while you were gone.
Thinking a longer TTL fixes it. A longer TTL makes the failure rarer, but it does not remove it. A rare failure that corrupts data without any error is harder to find than a common one.
Numbering some writes and not others. The old holder's writes get through on the path you forgot to number. Write the list down. Do not assume you already know what is on it.