Stage 3 · Distributed data · Hard · 20 min
Distributed locks and fencing tokens
Let only one worker do a job at a time across machines — and stay safe when the lock holder pauses — using leases and fencing tokens.
What each interview level is expected to know
Learn first: Time, clocks and ordering, Consensus and Raft
After this lesson you can:
- Take a lock with an expiry so a crashed worker cannot hold it for ever.
- Explain how a long pause lets two workers think they hold the same lock.
- Use fencing tokens so storage rejects the late writer.
Start here
See it in 60 seconds
When a lock runs out too soon
A lock can run out while its holder is frozen, so storage checks a fencing token that only goes up.
Scene 1 of 6 · Take the lock
Say client A takes the lock for 10 s and gets fencing token 33, a number that only goes up.
- Lock service — healthy — A holds it, 10 s
- Client A — healthy — token 33
- Client B — healthy
- Storage — healthy
- Take the lock. Say client A takes the lock for 10 s and gets fencing token 33, a number that only goes up.
- A freezes. Then A freezes, say its program pauses for 15 s, and it does not notice the time passing.
- The lock runs out. After 10 s the lock runs out, so the lock service treats A as gone.
- B gets token 34. Client B takes the lock, gets token 34, and writes; storage notes 34 as the highest token so far.
- A wakes up late. A wakes up, still believes it holds the lock, and sends a write with token 33.
- Storage says no. Storage has already seen 34, so it refuses 33, and the late write does no harm.
- Now you try. Tap writes in the order they reach storage, and see which ones it accepts. For example, tapping A writes, token 33, B writes, token 34 and A writes, token 33 gives this: A accepted, B accepted and A refused; storage's highest token is now 34. Once storage has seen token 34, it refuses 33, so a client whose lock ran out cannot write.
Scene 1 of 6: Take the lock. Say client A takes the lock for 10 s and gets fencing token 33, a number that only goes up.
Key points
- A lock lasts a set time, so a frozen client can lose it without noticing.
- Each time the lock is given out, it comes with a fencing token one higher than before.
- Storage remembers the highest token it has seen and refuses any lower one.
- So a client whose lock ran out cannot overwrite the work of the next holder.
In plain words
Say two workers, client A and client B, both want to change the same record. A asks a lock service for the lock and gets it for 10 seconds. With the lock comes a number, 33. Then A's program freezes for 15 seconds. The lock runs out, so B takes it, gets the number 34 and writes. When A wakes up it knows none of this, and it sends its write with 33. The storage took a write with 34 a moment ago, so it turns 33 away. A lock with a time limit is called a lease. The rising number is called a fencing token.
In practice the lock service is a small group of servers that agree by majority, such as etcd or ZooKeeper, so it survives one crash. A lock kept on a single (A widely used data store that keeps its data in memory, so it answers much faster than a database on disk. It is often used as a cache.) server can be lost when that server fails and a copy takes over. The worker should renew its lease while it works, well before the time runs out. And the storage must check the token itself, because only it sees every write in order.
The problem it solves
A lock across machines needs a time limit, or a crashed holder would keep it forever. But a holder can be slow without having crashed. Its program may pause to free memory, called a garbage collection pause, or its network may stall. The lock then runs out while the holder is still working. A second worker takes it, and both write to the same data.
Why it matters
Many systems run the same job on several machines, for speed or as a spare. Some work must still be done by one worker at a time: charging a card, booking seat 14C, sending the monthly bill. A lock shared across machines is the usual answer. It fails in ways that a lock inside one program does not.
A worked example
A worker takes a lock with a 10-second lease and fencing token 33. A 15-second pause then makes the lease expire 5 seconds before the worker finishes, since 15 − 10 = 5. A second worker takes over with token 34 and writes first. When the first worker finally (A tree that stores words one letter per step, so words that start the same share a path.) to write using token 33, the storage rejects it because 33 is less than 34.
Think of it like…
Think of a meeting room booked for 30 minutes at a time. Each booking gets a slip with a rising number: 33, then 34. The door remembers the highest number it has seen, and stays shut for a lower one.
Where this analogy stops working
A time limit plus a rising number is the useful part. But in a building, the desk and the door are one system. In software they are apart. The lock service hands out the number, and the storage must check it on every write. A store that cannot check it gets no protection.
Try it
See it working
Also try: Raft leader election
Mechanics
How it works
The pictures follow this page's example: client A takes a lock, freezes for 15 seconds, and wakes after its lease has run out. The first shows what a fencing token stops. The second shows why a release must check whose lock it is.
Take the lock with an expiry
A worker asks the lock service for the lock on one resource, such as seat:14C. The service grants it for a fixed time, such as 10 seconds. This timed lock is called a lease. The expiry matters: if the worker crashes, the lock frees itself.
Get a fencing token
With each lease, the lock service also hands out a number that only goes up: 33, then 34. This number is a fencing token. Services built on consensus, such as ZooKeeper or etcd, can provide one. A plain Redis lock does not, so you must add a counter yourself.
The storage checks the token
Pick a case to follow belowWith this case: Storage took A's late write with token 33, and B's change was lost. The lock alone did not stop it.
Client A, a worker Client A a worker Client B, a worker Client B a worker Lock service, leases of 10 s, NOW Lock service leases of 10 s held by A NOW Storage, the record Storage the record - Client A — a worker — healthy
- Client B — a worker — healthy
- Lock service — leases of 10 s — healthy — NOW — held by A
- Storage — the record — healthy
- Granted
- Write
Step 1 of 5Step 1 of 5 · Lock service
Done: A takes the lock for 10 seconds
- What happens
- The lock service grants A a lease of 10 seconds, with fencing token 33.
- Why
- The lease frees the lock by itself if A crashes.
- What changes
- A starts its work.
- Next
- A freezes for 15 seconds
Lock held byAHighest token at storage–storage ignores itThe record holdsthe first versionas it should beStep 1 of 5: Lock service. A takes the lock for 10 seconds. The lock service grants A a lease of 10 seconds, with fencing token 33.
Every write carries its token. The storage, such as a database, refuses any write whose token is lower than the highest token it has already accepted. So a worker that paused and woke up late with token 33 is rejected once token 34 has written. The storage must do this check itself, because the lock service never sees the write.
In the picture, step through both cases. A's lease of 10 seconds runs out while A is frozen, B takes the lock with token 34 and writes. When A wakes, it writes with token 33.
If storage ignores the tokens, A's late write replaces B's change, and nobody sees an error. If storage checks them, 33 is lower than 34, so the write is refused and B's change stays.
Release only your own lock
Pick a case to follow belowWith this case: A deleted B's lock. Another client could now take it while B is still working.
Client A, a worker Client A a worker Client B, a worker Client B a worker Lock service, leases of 10 s, NOW Lock service leases of 10 s held by A NOW Storage, the record Storage the record - Client A — a worker — healthy
- Client B — a worker — healthy
- Lock service — leases of 10 s — healthy — NOW — held by A
- Storage — the record — healthy
- Granted
- Request
Step 1 of 4Step 1 of 4 · Lock service
Done: A takes the lock for 10 seconds
- What happens
- The lock service grants A a lease of 10 seconds, and stores A's id, a-7f, with the lock.
- Why
- The lease frees the lock by itself if A crashes.
- What changes
- A starts its work.
- Next
- A freezes for 15 seconds
Lock held byAas it should beId stored with the locka-7fStep 1 of 4: Lock service. A takes the lock for 10 seconds. The lock service grants A a lease of 10 seconds, and stores A's id, a-7f, with the lock.
What these pictures simplify. These pictures use two clients, one record and stated times: a 10-second lease and a 15-second freeze. A real client can also be late because of a slow network or a wrong clock. The distributed lock lab above lets you freeze a worker yourself.
When the work is done, the worker releases the lock. It must first check that the lock is still its own, by comparing a unique id stored with the lock. Check and delete must happen as one step. Otherwise a slow worker could delete a lock that now belongs to someone else.
In the picture, A wakes after its lease ran out and releases the lock, which now belongs to B. A plain delete removes B's lock, so a third client could take it while B is still working. Checking the stored id first, in the same step as the delete, leaves B's lock alone.
In code: checking a fencing token
// The lock service gives each new holder a bigger number: 33, then 34, and so on.function makeStore(db) { let highestSeen = 0 return function write(token, record) { if (token < highestSeen) return "rejected" // an older holder woke up late highestSeen = token db.save(record) return "saved" }}- The check runs in the storage, not in the client, so a paused client cannot skip it.
- Holder 33 pauses and its lock runs out. Holder 34 writes. When 33 wakes up and writes, the store refuses it.
- The check and the save must happen as one step, such as in one (A group of database changes that succeed or fail together: either all of them are saved, or none are.).
Use it when
- One resource that many workers may change, such as seat 14C or one hotel room: the lock lets one booking go through at a time.
- A job that must not run twice at once, such as the monthly billing run: only the worker holding the lock runs it.
- Choosing one active copy among several copies of a service: the copy holding the lease acts, and another takes over when the lease ends.
Skip it when
- An update to one row in one database: a version check on the row, called optimistic locking, is faster and needs no lock service.
- A rule the database can enforce itself, such as one booking per seat: a unique constraint rejects the second insert with no lock at all.
- Work that is safe to repeat, such as setting a status to "sent": make the operation (Safe to repeat. Doing it twice has the same effect as doing it once.) and let two workers both do it.
Check yourself
Judgement
Trade-offs and how it fails
What you give up
- Safety
- A lease on its own only makes two holders unlikely. After a pause, two workers can both believe they hold the lock. The fencing token check in the storage is what stops the late write.
- Latency
- Taking and releasing the lock are extra network calls on every job. If many workers want the same lock, they wait in line, and the lock becomes the slowest part of the system.
- Lease length
- A short lease frees the lock soon after a crash, but it can run out under a holder that is only slow. A long lease runs out less often, and makes everyone wait longer after a crash.
Failure modes
- A pause outlasts the lease: A holds a 10-second lease and its program pauses for 15 seconds. B takes the lock and writes. With no fencing token, A's late write then overwrites B's.
- Releasing someone else's lock: A's lease runs out and B takes the lock. A then finishes and deletes the lock key without checking whose it is, so B's lock is gone.
- The lock service loses the lock: a single Redis server fails, and its (A copy of a database kept on another machine.) takes over before it has copied the lock key. A second worker can then take a lock that is still held.
In the real world
- Google's Chubby paper (2006) describes a lock service built on consensus. It hands out a number that lets servers reject a stale lock holder. Source: Google: the Chubby paper (2006) (checked 14 October 2026)
- ZooKeeper removes a client's lock node when that client's session ends, and etcd offers leases that expire. Many lock libraries build on these.
- Martin Kleppmann's article "How to do distributed locking" (2016) shows a lock failing after a pause, and how a fencing token prevents the damage. It argues that Redlock, a Redis lock algorithm, is not safe when correctness depends on the lock. Source: Martin Kleppmann, "How to do distributed locking" (2016) (checked 14 October 2026)
- Redis's documentation says its replication is asynchronous, so a lock key can be lost when a replica takes over. It says such a lock is still fine where a rare race is acceptable.
Trade-offs to be ready to discuss: Optimistic vs pessimistic locking
Check yourself
Interview
What interviewers look for
- Say what the lease cannot do: "A lease can run out while its holder is paused. So I add a fencing token, and the storage refuses any older token."
- For a Redis lock, say how you release it: "Each holder stores a random id with the lock. A short Lua script checks the id and deletes the key in one step."
- Ask first whether a lock is needed: "For one row I would use a version check. For one booking per seat I would use a unique constraint."
- Say what the lock is for. If it only saves repeated work, a rare double run is fine and one Redis lock is enough. If it keeps data correct, use a consensus-based service and fencing tokens.
Say it out loud: What is a fencing token, and why does a lock with a lease need one?
Expected depth by interview level
Levels describe the depth interviewers probe, not years of experience. Choose a level on the learning path to highlight it.
- JuniorBeyond this level
- Not usually expected.
- MidUseful
- Why a lock across machines is harder than a mutex.
- SeniorCore
- Leases, fencing tokens, and what goes wrong when a holder pauses.
- StaffExpected
- Designing so a lock is not needed at all.
Practice
Apply it
Three harder questions
The first two use the idea on a new case. The last asks you to judge a design.
Apply it
Apply it
Judge a design
Go deeper
Sources and further reading
First-hand sources to check this page against and to go further. They are standards, official docs, original papers, and guides from engineering and security teams. Each link was opened on 8 November 2026.
- Engineering guideHow to do distributed lockingMartin KleppmannWhy a lock with a timeout is unsafe on its own, and how fencing tokens fix it.
- Official docsDistributed locks with RedisRedis documentationRedis’s own lock recipe and its stated limits. Read it next to the article above.
- Research paperThe Chubby lock service for loosely-coupled distributed systems (2006)Mike Burrows, USENIX OSDIGoogle’s lock service built on consensus, including its sequencer, a form of fencing token.