System Design

Patterns

Fencing and Epochs

A process can take a lock, get frozen, lose the lock, wake up and carry on writing as if nothing happened. You cannot stop that. What you can do is number every lock and have the database refuse writes that carry an old number.

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 lease that runs out during a pause
Holder A freezes in a GC pause (1). The bracket above A's row is its lease from the lock service, and the lease expires while A is frozen (2). The lock service then gives the lock to holder B, and B starts writing (3). A wakes up and writes too (4). The database checks nothing, so it accepts both writes, and neither holder sees an error.Holder A freezes in a GC pause (1). The bracket above A's row is its lease from the lock service, and the lease expires while A is frozen (2). The lock service then gives the lock to holder B, and B starts writing (3). A wakes up and writes too (4). The database checks nothing, so it accepts both writes, and neither holder sees an error.
The old holder comes back and writes as if nothing happened. Holder A freezes in a GC pause (1). The bracket above A's row is its lease from the lock service, and the lease expires while A is frozen (2). The lock service then gives the lock to holder B, and B starts writing (3). A wakes up and writes too (4). The database checks nothing, so it accepts both writes, and neither holder sees an error.

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.

  1. 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.
  2. 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.
  3. 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 database refuses the old number
A holds token 4. It checks its own lease, the check passes, and A writes. The database records 4 as the highest token it has seen (1). Then A freezes (2). B gets the lock with token 5 and writes. 5 is higher than 4, so the database accepts the write and records 5 (3). A wakes up and sends a write with token 4. The database has seen 5, so it refuses the write, and A stops (4). A's own check passed before the pause, so only the database could catch this write.A holds token 4. It checks its own lease, the check passes, and A writes. The database records 4 as the highest token it has seen (1). Then A freezes (2). B gets the lock with token 5 and writes. 5 is higher than 4, so the database accepts the write and records 5 (3). A wakes up and sends a write with token 4. The database has seen 5, so it refuses the write, and A stops (4). A's own check passed before the pause, so only the database could catch this write.
Being refused is how the old holder finds out. A holds token 4. It checks its own lease, the check passes, and A writes. The database records 4 as the highest token it has seen (1). Then A freezes (2). B gets the lock with token 5 and writes. 5 is higher than 4, so the database accepts the write and records 5 (3). A wakes up and sends a write with token 4. The database has seen 5, so it refuses the write, and A stops (4). A's own check passed before the pause, so only the database could catch this write.

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.

systemthe numberwho compares it
Rafttermfollowers, on every append
Kafkaleader epochfollowers, when deciding where to truncate
Chubbythe sequencer's lock generation numberthe file server being written to
GFSchunk version numberchunkservers

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.

A lock delay, and a pause longer than it
In both rows, A's lease is lost at 0 s, part way through A's pause, and nobody can take the lock until 60 s. In the top row, A is frozen for 40 seconds. It wakes up, its last write lands, and it stops, all before B gets the lock (1). In the bottom row, moving A's virtual machine freezes it for 90 seconds. B has held the lock since 60 s, so when A wakes up and writes, both are writing at once (2). The red band marks that overlap.In both rows, A's lease is lost at 0 s, part way through A's pause, and nobody can take the lock until 60 s. In the top row, A is frozen for 40 seconds. It wakes up, its last write lands, and it stops, all before B gets the lock (1). In the bottom row, moving A's virtual machine freezes it for 90 seconds. B has held the lock since 60 s, so when A wakes up and writes, both are writing at once (2). The red band marks that overlap.
The delay works only while every pause is shorter than the delay. In both rows, A's lease is lost at 0 s, part way through A's pause, and nobody can take the lock until 60 s. In the top row, A is frozen for 40 seconds. It wakes up, its last write lands, and it stops, all before B gets the lock (1). In the bottom row, moving A's virtual machine freezes it for 90 seconds. B has held the lock since 60 s, so when A wakes up and writes, both are writing at once (2). The red band marks that overlap.

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.

Back of envelopeWhy a longer lease does not fix it
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

articlethe form it takes there
Design a Distributed Job Schedulerthe attempt number and the region's epoch together fence one run; the pair, compared epoch first, never goes down
Design a Distributed Message Queueevery batch carries its leader's epoch, and a returning broker truncates to where its last epoch ended
Design a Payment Systemthe 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 Sagasa late retry of an old saga step, refused because the row's held_by no longer names that booking
Idempotency and Exactly-Once Deliveryordering a retry against the work it duplicates, so a late arrival cannot overwrite a newer result
Key-Value Storeevery log entry carries the leader's epoch, so a leader that paused through its lease has its next entry refused
Multi-Region and Disaster Recoverya lease tells the old region to stop, and the epoch on every write refuses what it already sent
Quorums, Raft and Paxosconsensus can name the leader and cannot mute the previous one
Replication and Leader Electionwhy a lease alone permits two leaders, and where the term is checked
Ticketmaster Bookingheld_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-Hailingoffer_id on the trip and driver rows fences off a late accept or a late release
Web Crawlera 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 Systemsa reconnecting device whose old socket is still registered, and the number that settles which one wins
Write-Ahead LogsRaft'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.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.