SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
  • Consensus Algorithms
  • Paxos
  • Raft
  • Leader Election
  • ZooKeeper and etcd
  • Distributed Locks
  • Fencing Tokens
  • Gossip Protocol
  • CRDTs
  • Operational Transformation
  • Distributed Unique ID Generation (Snowflake, UUID)
  • Two Generals Problem
  • Byzantine Fault Tolerance (BFT)
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Distributed Systems/Coordination and Consensus

Fencing Tokens

A number that grows with every lock, so storage can reject a client that woke up too late.

โฑ 11 min readAdvancedInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A fencing token is a number that goes up every time a lock is given out. The client sends it with every write, and the storage rejects any write whose number is lower than one it has already seen.

  • The problem: a lock with a time limit (a lease) can expire while its owner is paused. The owner wakes up and still believes it holds the lock.
  • The fix: the check happens at the resource, not in the client. A paused client cannot lie its way past a number comparison.
  • The rule: accept token t only if t is at least the highest token already accepted.

02Concept: What is it?

A distributed lock tells a client "you are the only one allowed to do this now". With a lease, that promise has an end time. The trouble is that the client cannot tell for sure whether the end time has passed. A long garbage collection pause, a slow disk, or a network delay can make a client act after its lease is gone. This was described by Martin Kleppmann in his well-known analysis of Redis-based locks.

A fencing token solves this by moving the final check to the thing being protected. Every time the lock service grants the lock, it also hands out a monotonically increasing number: 33, then 34, then 35. The client attaches that number to each request. The storage remembers the highest number it has accepted, and refuses anything lower.

The storage is the last line of defence
๐Ÿ˜ดClient 1woke up late, token 33
โ†’โ†“write (33)
๐Ÿ—„๏ธStoragehighest seen: 34
โ‡ขโ‡ฃrejected
Client 1 is paused and holds an old token. The storage turns it away.
๐Ÿง A lock alone is not enough
Holding a lease does not prove you are alone. Only the resource itself can safely say "this request is too old". The lock service cannot, because it has no way to stop a paused client.

03Real-Life Example

๐ŸตThe Numbered Hotel Key Cards
A hotel gives you key card number 33 for room 12. You fall asleep in the lobby, and your booking runs out. The hotel issues a new card, number 34, to another guest. The door lock remembers "the newest card I have seen is 34". When you wake up and wave card 33, the door stays shut. The door is checking, not you, and not the front desk.
Hotel
Fencing tokens
The front desk
The lock service
Key card number
The fencing token
A new card for each guest, always higher
A growing counter on each grant
The door lock
The storage or resource
The door remembers the newest card seen
The storage keeps the highest token
An old card is refused
A write with an old token is rejected
The sleeping guest
A paused client (GC, slow network)

04Why Do We Need It?

๐Ÿ˜ดPauses are real
Garbage collection, swapping, VM migration and slow networks can freeze a process for seconds.
โฑ๏ธLeases expire
A lock must expire, or a crashed owner would block everyone forever. Expiry creates the danger.
๐Ÿ›ก๏ธReal safety
The check sits at the resource, so correctness does not depend on the client being on time.
๐ŸชถVery cheap
One integer per request and one integer stored per resource.
๐Ÿ”Safe failover
A new owner can take over quickly without waiting to be sure the old one is dead.
๐ŸงฎNo clock needed
The order comes from a counter, not from comparing clocks that may disagree.
Leases tell you who should be working. Fencing tokens make sure that if the wrong one still tries, nothing bad happens.

05Where Do We Use It?

๐Ÿ”Distributed locks
Any lock that protects a shared file, row or object, and can expire.
๐Ÿ‘‘Leader election
The leader's term or epoch is a fencing token. Followers ignore messages from an older leader.
๐Ÿ—ณ๏ธRaft and Paxos
Terms and ballot numbers do the same job: a node that sees a higher number steps down.
๐Ÿ—‚๏ธReplicated databases
A primary has an epoch. Replicas reject writes from an old primary after a failover.
๐ŸงฑStorage systems
HDFS and others use generation stamps or epochs to stop a stale writer.
๐Ÿ“ฆJob workers
A job runner passes the token to the database so a late duplicate worker cannot overwrite results.

06Types / Parts / How It Works

Where a token can come from

SourceHow it growsNotes
Lock service counter+1 on every grantThe simplest: ZooKeeper zxid or version, etcd revision
Consensus term or epoch+1 on every electionUsed by Raft, Paxos and primary-backup databases
Database sequenceNext value of a sequenceFine if one database is the source of truth
TimestampWall clockRisky: clocks can move backwards or disagree. Prefer a counter.

What the storage must do

The check on every write
Accept
โœ…token 34 (highest 34)same owner, more writes
โœ…token 35 (highest 34)newer owner, raise highest to 35
Reject
โ›”token 33 (highest 34)old owner, stale
Remember the highest token. Accept equal or higher, reject lower.
Accepted Rejected
VisualizerA paused lock holder, with and without the checkStep through the story. Make the pause longer than the lease, then switch the storage between โ€œaccepts any writeโ€ and โ€œrejects old tokensโ€ and watch what happens when Client 1 wakes up.
Does the storage check the token?
๐Ÿ˜ดClient 1token 33
โ†’โ†“
๐Ÿ—„๏ธStorageno writes yet
โ†
๐Ÿง‘โ€๐Ÿ’ปClient 2waiting
File content: v0
Step
1 / 5
Highest token seen
none
kept by the storage
Data
safe
Client 1 takes the lock. The lock service gives Client 1 the lock with fencing token 33.

A simplified model with fixed numbers (tokens 33 and 34). A real lock service hands out a bigger number on every grant, and the storage remembers the highest one it has accepted.

07How to Use It / Steps / Implementation

Using fencing tokens

  1. 1
    Make the lock service return a token
    On every grant, return a number bigger than any it has given before.
  2. 2
    Send the token with every request
    Put it in a header or field on each write that is protected by the lock.
  3. 3
    Store the highest token at the resource
    Keep one integer next to the data (or the file or the row).
  4. 4
    Compare on each write
    If the request token is lower than the stored one, reject it. Otherwise accept it and save the new value if it is higher.
  5. 5
    Do the check and the write together
    Use a transaction or a compare-and-set, so two requests cannot slip between the check and the write.
  6. 6
    Handle the rejection
    A rejected client should stop, drop what it was doing, and try to get the lock again.
๐Ÿ’กOne line of SQL
UPDATE doc SET body = ?, token = ? WHERE id = ? AND token <= ?. If no row changes, the write was stale.
โš ๏ธThe resource must take part
If the storage cannot check a number (for example, an email service or a third-party API), fencing tokens cannot protect it. Use an idempotency key, or another way to make repeats harmless.

08Key Terms to Know

TermMeaning in easy words
Fencing tokenA growing number given with each lock grant, used to reject old owners
LeaseA lock that expires after a set time
Stale ownerA client that still thinks it holds a lock it has lost
MonotonicOnly ever goes up, never down
Epoch / termA counter for each leadership period, the same idea as a fencing token
Compare-and-setA write that only succeeds if a value is still what you expect
GC pauseA freeze while a runtime cleans up memory, often a cause of stale owners
ZombieA process that was thought dead but is still running
Fencing (STONITH)Cutting off a bad node, for example by powering it down, so it cannot do harm
Highest token seenThe number the storage remembers and compares against

09Pros, Cons and Trade-offs

โœ… Pros
  • Gives real safety, not just a hopeful time limit
  • Costs one integer per request
  • Does not depend on synchronized clocks
  • Simple to explain and test
  • Same idea as terms in Raft and Paxos
โš ๏ธ Cons
  • The resource must be able to check tokens
  • The lock service must hand out growing numbers
  • Does not stop a stale client from wasting work
  • Needs an atomic check and write
  • Useless for systems you cannot change

Trade-offs

ChoiceWe gainWe lose
Lease onlySimpleUnsafe if the owner pauses
Lease + fencing tokenSafe even with pausesStorage must check tokens
Counter tokenStrict order, no clocksNeeds a reliable counter
Timestamp tokenEasy to produceClock errors can break the order
Short leaseFast failoverMore false expiries during pauses

10Common Problems and Mistakes

Common mistakes

  1. Checking the lock in the client only. "I checked my lease a moment ago" proves nothing if the client then pauses.
  2. A storage that ignores tokens. The token is useless if nobody compares it.
  3. Check and write in two steps. Another request can slip in between. Make it atomic.
  4. Tokens that can go down. A counter that resets after a failover brings the old owner back to life.
  5. Using wall-clock time as the token. Clocks can step back, and then a new owner gets a smaller number.
  6. Forgetting to send the token on every write. One unprotected write path breaks the safety.
  7. Not stopping the stale client. After a rejection the client should stop working, not retry blindly.

Things to watch

๐Ÿ”ŒSeveral resources
If a job touches two storages, each one needs its own check.
๐ŸงฎCounter source
The counter must survive restarts and failovers of the lock service.
๐Ÿ“คOutside effects
An email or payment already sent cannot be fenced. Use idempotency keys.
๐Ÿ”Equal tokens
The same owner sends many writes with one token. Accept equal, reject lower.

11Real-World Examples

๐Ÿ˜ZooKeeper
The zxid or a znode version works as a token. Many recipes pass it to the resource.
๐Ÿงฐetcd
Each key has a revision number that always grows. Locks return it so clients can send it along.
๐Ÿ—ณ๏ธRaft
Term numbers fence old leaders. A node that sees a higher term steps down at once.
๐Ÿ—‚๏ธHDFS
Uses generation stamps and epochs so a stale writer or old NameNode cannot corrupt data.
๐Ÿ“ŠKafka
Producer epochs and leader epochs reject writes from fenced-off zombies.
๐Ÿ“„Chubby
Google's lock service describes sequencers, which are the same thing as fencing tokens.
Mini case: paused worker after failover
1๏ธโƒฃWorker A, token 7pauses for 20 s
โ†’โ†“lease ends
2๏ธโƒฃWorker B, token 8finishes the job
โ†’โ†“A wakes, sends 7
๐Ÿ›ก๏ธDatabasehighest 8, rejects 7
The second worker finishes. The first wakes up and is turned away.

12Related Topics to Read Next

Distributed Locksโ†’

The lock that fencing tokens make safe.

Lamport Timestampsโ†’

The same growing-number idea, used for ordering.

Leader Electionโ†’

Terms and epochs fence off old leaders.

Split Brain Problemโ†’

What fencing prevents when two nodes think they lead.

ZooKeeper and etcdโ†’

Lock services that can hand out growing numbers.

Raftโ†’

Terms are fencing tokens built into consensus.

Failure Detectorsโ†’

Why a node thought dead may still be running.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • โœ”Problem: a paused client can act after its lease has expired.
  • โœ”Fix: the lock service gives a growing number, and the storage checks it.
  • โœ”Rule: reject any write with a token lower than the highest seen.
  • โœ”Check where: at the resource, atomically with the write.
  • โœ”Source: a counter, epoch or revision. Not a wall-clock time.
  • โœ”Same idea: Raft terms, Paxos ballots, Kafka epochs.
  • โœ”Cannot fence? Use idempotency keys instead.
  • โœ”One line: โ€œA lock says who should go; the number lets the door say who is too late.โ€
โ† Previous
Distributed Locks
Next โ†’
Gossip Protocol