To design a distributed locking service is to build a small service that lets many machines agree, at any moment, on which one of them may change a shared thing. A good answer explains what happens when the holder crashes or freezes, why a lease is needed, why a lock alone is not enough without a fencing token, how the lock state survives the loss of a node, why clocks cannot be trusted, how waiting workers should line up, and how big each lock should be.
This lesson designs LabSlot, the booking system of a university with 20 labs and 1,000 bookable lab slots. Many application servers accept bookings at the same time, and two students must never get the same slot. Six runnable programs in Java, with Python and C++ versions, test the decisions interviewers probe most: lease length, fencing, replication of the lock state, clocks, waiting rules, and lock size with deadlocks. All rates, failure chances and timings are assumptions chosen to make comparisons clear, not measurements of a product.
Key takeaways
A lock with no expiry was stuck for ever after the first crash, which came at holding 6,057. A 1 s lease let 10,928 of 100,000 holdings overlap with the next owner, a 5 s lease 3,162, and a 30 s lease none, at the price of making everyone wait 30 s after a crash.
Renewing the lease while the worker is alive cut the 5 s lease from 3,162 overlaps to 701. A frozen worker cannot renew, so renewal cannot remove the rest.
In 100,000 rounds, a lock with a 1 s lease still lost 2,787 bookings. Adding a fencing token to the storage cut that to 55 and rejected 2,732 stale writes. Compare-and-set on a version number lost none.
With every node crashing after a grant at 1 in 50, a single node gave 4,057 double grants in 200,000. A primary with an asynchronous replica gave 870, a 3-node majority 229 and a 5-node majority 17.
A worker that checks its own wall clock before writing made 213 unsafe writes in 100,000 holdings. A steady clock made 150. Stopping at 80% of the lease made none, and aborted 18,052 good holdings. Letting the storage check the lease made none of either.
Fifty workers retrying every 10 ms sent 5,750 requests. Queueing with a watch on the one in front sent 150, served everyone in order and finished at 2,598 ms.
One lock for all bookings gave 200 bookings a second. One lock per lab gave 666 and one per slot 1,581. Taking two slot locks in the order given caused 16 deadlocks that were broken only by timeouts. Taking the lower slot number first caused none.
1. Clarifying Requirements
Functional requirements
Acquire the lock for a named resource, such as one lab slot. If it is taken, say so, or wait.
Release it, and only the current owner may release it.
Every lock has a lease, a time limit after which it is released automatically.
The owner can renew the lease while it still holds the lock.
Non-functional requirements
Safety: no two workers may both be allowed to change the same slot, even when a worker is slow or a node fails.
Liveness: a crashed worker must not block a slot for ever.
The service stays available when a minority of its nodes fail.
Grants take a few milliseconds.
Ask what a wrong double grant costs. If the lock only avoids sending a duplicate email, a rare double grant is acceptable and a cheap design is fine. If it protects a booking, a payment or a file, the lock alone is never enough: the protected storage has to help. State this early, because it decides the rest of the design.
2. Back-of-the-Envelope Estimation
Requests: 20 labs with 50 slots each is 1,000 slots. In the busiest minute, 1,500 lock requests a second is a safe assumption.
Concurrency: a booking holds its lock for about 5 ms, so 1,500 requests a second keep about 7.5 locks (say 8) held at any moment.
State: 1,000 keys of about 100 bytes (owner, expiry time, token) is 100 KB. It fits in the memory of one node.
The load is small. Correctness under failure is the hard part.
Many lock services run at far higher rates, but the point stays the same: a lock service is a small, hot, very correct piece of state, not a big data store.
3. Core APIs
POST /v1/locks/{resource}/acquirewith{"owner": "app-3", "lease_ms": 5000}. The reply is either{"granted": true, "token": 42, "expires_in_ms": 5000}or{"granted": false, "retry_after_ms": 1800}.POST /v1/locks/{resource}/renewwith the owner and token. It fails if the lease has already passed to someone else.POST /v1/locks/{resource}/releasewith the owner and token. A release that carries the wrong token is refused.The protected storage gets a different kind of call:
PUT /slots/417with{"student": "...", "token": 42}, or a version number for compare-and-set.
4. High-Level Design
Workers call the lock service before they touch a slot. The service keeps, for every resource, the current owner, the time the lease ends and a token that grows by one on every grant. A worker that gets a token includes it in every write to the slot. The storage remembers the highest token it has seen for each slot and refuses anything lower.
The lock service decides who may start. The storage decides whose write still counts.
A grant stores the owner, the expiry and a token that is one higher than the last.
The storage rejects a write whose token is older than one it has already seen.
5. Leases: Locks That Expire
A worker can crash while it holds a lock. If the lock never expires, the slot is blocked for ever. A lease is a lock with a time limit: when the time is up the service may give the lock to someone else. The difficulty is that the old owner may still be alive. It may only be slow, stuck in a garbage collection pause or cut off by the network, and it will carry on as if it still owned the lock. The lease length is a trade between waiting after a crash and overlap with a slow owner. Renewal lets a healthy worker with a long task keep the lock without a long lease.
The first program runs 100,000 lock holdings. Normal work takes 50 to 249 ms, 1 holding in 10 is a big report taking 2 to 6 seconds, 1 in 100 freezes for 1 to 15 seconds (and cannot send a heartbeat while frozen), and 1 in 2,000 ends in a crash. An overlap means a second worker was given the lock while the first still thought it owned it.
Output
100000 lock holdings. Overlap = a second worker was given the lock while the first still thought it owned it.
lock rule overlaps avg ms wait after lock stuck worst ms crashed
a crash holdings
no expiry 0 0 never stuck after 6057 0 40
lease 1 s 10928 3401 1000 ms no 19464 40
lease 5 s 3162 1645 5000 ms no 15464 40
lease 30 s 0 0 30000 ms no 0 40
lease 5 s + renew 701 5147 5000 ms no 9989 40
lease 30 s + renew 0 0 30000 ms no 0 40
No expiry: no overlaps, but the first crash, at holding 6,057, blocked the lock for ever.
1 s lease: 10,928 overlaps, on average 3,401 ms long and at worst 19,464 ms. A big report is longer than 1 s even without a freeze.
5 s lease: 3,162 overlaps (average 1,645 ms, worst 15,464 ms), and a crash blocks the slot for 5 s.
30 s lease: no overlaps in this run, and every crash blocks the slot for 30 s.
5 s lease with renewal: 701 overlaps. Only the freezes longer than 5 s still overlap (average 5,147 ms, worst 9,989 ms). The 30 s lease with renewal had none.
A short lease waits less after a crash and overlaps more often.
Renewal is the first useful fix, and it still cannot remove the overlap. A frozen process cannot renew, and nothing tells it that its lease has gone when it wakes up. That is why leases need a second layer of defence.
6. Fencing Tokens
A fencing token is a number that the lock service increases on every grant. The worker sends it with each write, and the protected storage keeps the highest token it has seen and rejects any lower one. A worker that slept through its lease wakes up holding token 41 while the storage has already seen 42, so its write fails. The safety no longer depends on the worker noticing that it lost the lock. Martin Kleppmann described this clearly in his analysis of lock-based designs, and it is the idea to name in an interview.
The second program runs 100,000 rounds in which two students, A and B, try to book the same slot. A reads the slot and writes 100 ms later, but in 1 round in 20 A freezes first for 2 to 9 seconds. B arrives 0 to 9,999 ms after A. A lost booking means a student was told it worked but the slot records the other student. It compares five protections.
Output
100000 rounds, two students per round. Lost booking = a student was told 'booked' but the slot records the other student.
protection both read the lost writes
slot as free bookings rejected (safe)
no lock 3768 3768 0
lock, 1 s lease 2787 2787 0
lock + fencing token 2787 55 2732
compare-and-set only 3768 0 3768
lock + token + compare-and-set 2787 0 2787
No lock: 3,768 rounds in which both read the slot as free, and 3,768 lost bookings.
Lock with a 1 s lease, storage accepts anything: 2,787 overlapping rounds and 2,787 lost bookings. The lock helped (fewer overlaps) but did not make the system safe.
Lock plus fencing token: 55 lost bookings, and 2,732 stale writes rejected. The remaining 55 are a narrow window: if the old owner's write reaches the storage first and the new owner's write follows with a higher token, the storage accepts both, because a token only orders the owners, not the data they read.
Compare-and-set on a version number, no lock: 0 lost bookings. All 3,768 conflicts were detected and one of the two writers was told to retry.
Lock, token and compare-and-set: 0 lost, 2,787 safe rejections. The lock reduced how many conflicts there were, and compare-and-set made the rest harmless.
A lock reduces conflicts. A check in the storage makes them harmless.
The lesson is that a lock is an optimisation and the check in the storage is what protects the data. If the storage can do compare-and-set, you may not need a lock at all. When the storage cannot check anything, such as an email service or an external payment call, say plainly that the lock gives only a best-effort guarantee and make the action idempotent.
7. Keeping the Lock State Safe
A single lock node is a single point of failure, and if it restarts with an empty memory it has forgotten every lock it granted. Three designs are common. The first copies the state to a replica without waiting. The second waits for the replica before it answers. The third asks several independent nodes and counts a grant only when a majority (for example 3 of 5) agrees. The fourth, not simulated here, is a consensus protocol such as Raft or ZooKeeper's atomic broadcast, which makes the nodes agree on one ordered log of grants and is what etcd and ZooKeeper provide.
The third program makes 200,000 lock grants. After a grant each node crashes with a chance of 1 in 50 (far above real life, so that rare events show up) and comes back empty. A copy reaches the replica 0 to 9 ms after the grant and the primary crashes 0 to 19 ms after it. A double grant means the state was lost and a second worker could be given the lock.
Output
200000 lock grants, every node crashes after a grant with chance 1 in 50 (independent crashes).
lock service double grants per 100,000 extra wait per grant (ms)
1 node 4057 2028 0
primary + async replica 870 435 0
primary + replica, wait for it 76 38 4.49
3 nodes, majority 2 229 114 0 (parallel)
5 nodes, majority 3 17 8 0 (parallel)
1 node: 4,057 double grants (2,028 per 100,000), because any crash forgets the lock.
Primary with an asynchronous replica: 870 (435 per 100,000), the cases where the crash came before the copy.
Primary that waits for its replica: 76 (38 per 100,000), only when both nodes crash, and 4.49 ms of extra waiting for each grant on average.
3 nodes, majority 2: 229 (114 per 100,000), with the requests sent in parallel and no extra wait.
5 nodes, majority 3: 17 (8 per 100,000).
More copies and a majority rule make loss of lock state rarer.
The crashes in this program are independent. In real systems failures are often correlated: a rack, a power feed or a bad deployment takes down several nodes at once, and then a majority of nodes in the same rack gives much less protection than the table suggests. Place nodes in different failure domains. Also, a node that restarts empty should wait for at least one full lease before it grants anything, so that it cannot hand out a lock that an earlier version of itself already gave away. A consensus store removes this problem by persisting every grant to a majority before the reply.
8. Clocks
A lease is a promise about time, and time is measured by clocks that disagree. A wall clock can jump when the machine corrects its time, and a virtual machine can run slow after it has been paused. A steady (monotonic) clock never jumps back but still runs at a slightly different speed on each machine. The lock service should count the lease with its own steady clock. The worker's own opinion about whether the lease is still valid should never be the last line of defence.
The fourth program gives a worker a 10 s lease and lets it check its own clock just before it writes. The write happens 1,000 to 11,999 ms after the grant. In 1 holding in 100 the wall clock jumps by 100 to 4,999 ms, forward or backward. In 1 holding in 20 the machine's clocks run 3% slow. An unsafe write is a write after the lease has really ended. A needless abort is a worker that gave up while it still held the lease.
Output
100000 holdings with a 10 s lease. Unsafe write = the lease had already expired on the server but the worker wrote anyway.
worker's expiry check unsafe needless correct good
writes aborts aborts writes
wall clock 213 121 17877 81789
steady clock 150 0 17940 81910
wall clock, stop at 80% 35 18112 18055 63798
steady clock, stop at 80% 0 18052 18090 63858
storage checks the lease 0 0 18090 81910
Wall clock: 213 unsafe writes and 121 needless aborts per 100,000 holdings. Backward jumps hide time that has passed, and forward jumps cause aborts.
Steady clock: 150 unsafe writes and no needless aborts. The jumps no longer matter, but the slow machines still think they have time left.
Wall clock, stop at 80% of the lease: 35 unsafe and 18,112 needless aborts.
Steady clock, stop at 80%: no unsafe writes, and 18,052 needless aborts. A safety margin works, but the worker throws away every holding that was still valid between 8 and 10 seconds.
The storage checks the lease itself: no unsafe writes and no needless aborts, because the decision is made by one clock, the service's, and not by every worker's.
Do not ask a worker whether its own lease is valid.
A margin is a reasonable extra layer when the storage cannot check, but it should be sized from the largest clock error you can tolerate and it costs useful work. The cleanest fix is again the fencing check, which does not need the worker's clock at all.
9. Waiting for a Lock
When the lock is taken, a worker can fail at once, retry, or wait in line. Retrying has two costs: requests that all fail, and the lock sitting idle between a release and the next successful retry. A synchronised retry makes it worse, because all the workers come back at the same instant (a thundering herd). A queue avoids polling. Each waiter creates a numbered entry, watches only the entry in front, and is told when it is its turn. This is the recipe that ZooKeeper-style locks use.
The fifth program has 50 workers who want the same lab lock. They arrive within 200 ms and each holds the lock for 50 ms, so the best possible finish is about 2,500 ms after the first arrival. A failed try is a request, a release is a request, and a queue entry costs a create and a watch.
Output
50 workers, one lock, each holds it for 50 ms. The best possible finish is about 2500 ms after the first arrival.
waiting rule requests avg wait worst lock idle all done served requests per
(ms) wait (ms) (ms) at (ms) out of order worker x10
retry every 10 ms 5750 1130 2280 11 2511 535 1150
retry every 100 ms 713 1226 2800 488 2988 549 142
backoff, no jitter 568 4328 13270 10985 13485 541 113
backoff with full jitter 495 1363 3168 879 3379 578 99
queue + watch the one in front 150 1173 2349 98 2598 0 30
Retry every 10 ms: 5,750 requests (115 per worker), the lock idle for only 11 ms, finished at 2,511 ms. It is fast and it floods the service.
Retry every 100 ms: 713 requests, but the lock sat idle for 488 ms and the last worker finished at 2,988 ms.
Backoff without jitter (10, 20, 40 ms and so on up to 1,000 ms): 568 requests, and the lock idle for 10,985 ms. The workers' long, synchronised sleeps finished at 13,485 ms, and the worst wait was 13,270 ms.
Backoff with full jitter: 495 requests, 879 ms idle, finished at 3,379 ms. Randomness spreads the retries.
Queue and watch the one in front: 150 requests, 98 ms idle, finished at 2,598 ms, and nobody was served out of arrival order (the polling rules served 535 to 578 pairs out of order).
A queue sends fewer requests than polling and keeps the lock busy.
Polling is simpler to build, and with jitter it is a good choice for locks that are rarely contended. A queue costs more to implement and gives order and a low request count when many workers wait for the same lock. Whatever you choose, add a limit to the waiting time, so that a worker never waits longer than the work is worth.
10. Lock Size and Deadlocks
The size of the thing a lock covers decides how much work can run at once. One lock for the whole system is simple and serialises everything. A lock per lab is better. A lock per slot is the finest. A fine lock allows more parallel work but means more locks, and any operation that needs two locks can deadlock when two workers take them in opposite orders.
The sixth program has two parts. In part 1, 40,000 booking requests are served by 8 workers, each booking holds its lock for 5 ms, and half of the requests go to 100 popular slots in two labs. In part 2, a transfer moves a booking from one slot to another and needs both locks. Four workers each do 500 transfers between 20 busy slots. A worker takes the first lock, spends 2 ms reading, then asks for the second. If it waits 100 ms it gives up, releases the first lock and tries again after 1 to 20 ms, so the only way a deadlock ends is by that timeout.
Output
40000 booking requests, 8 workers, each booking holds its lock for 5 ms.
lock granularity finished bookings avg wait requests that
at (ms) per second (ms) waited (%)
one lock for everything 200000 200 34 99
one lock per lab (20) 60060 666 7 47
one lock per slot (1000) 25285 1581 0 1
2000 transfers (4 workers x 500), each needs two of 20 slot locks.
lock order finished deadlocks ms lost waiting
at (ms) broken for timeouts
locks in the order given 6822 16 1600
lower slot number first 5974 0 0
One lock for everything: 200 bookings a second, 99% of requests waited and the whole run took 200,000 ms.
One lock per lab: 666 bookings a second, 47% waited, 60,060 ms. The popular slots sit in two labs, so those two locks stay busy.
One lock per slot: 1,581 bookings a second, 1% waited, 25,285 ms.
Transfers, locks in the order given: 16 deadlocks, each broken only by a 100 ms timeout (1,600 ms lost), finished at 6,822 ms.
Transfers, lower slot number first: no deadlocks, finished at 5,974 ms.
Finer locks allow more work in parallel.
A fixed order for taking locks removes deadlocks.
The two points to remember: lock the smallest thing that keeps the data correct, and whenever an operation needs more than one lock, take them in one fixed global order (for example by resource id). A timeout is a safety net for a deadlock, not a plan.
11. Putting It on Real Systems
Do not build the consensus part yourself. The usual choices are:
A consensus store such as etcd or ZooKeeper. Leases, ordered revisions that work as fencing tokens, and watches for queueing come with the store. This is the usual answer for a lock that protects important data.
A single Redis instance with
SET key value NX PX ttl. It is quick and good for efficiency locks, where a rare double grant costs only some repeated work. Release with a script that checks the value, so a worker cannot delete someone else's lock. Replication is asynchronous, so a failover can lose a lock, exactly as the third program showed.A database row with an owner and an expiry updated under a transaction, or advisory locks. It is the simplest option when you already run the database that holds the data.
Redis's multi-node algorithm, Redlock, asks several independent instances and counts a majority. It improves on a single node, but because it relies on timing and has no fencing token, many engineers do not use it where safety matters. Mention the debate and say what you would pick.
12. Choosing the Design
Start from the cost of a double grant.
| Concern | Choice | Watch for |
|---|---|---|
| Crashed owner | Lease with renewal | A freeze longer than the lease |
| Stale owner | Fencing token and compare-and-set in the storage | A storage that cannot check |
| Losing lock state | Majority of nodes or a consensus store | Failures that happen together |
| Clocks | The service counts time; storage decides | Worker-side expiry checks |
| Waiting | Queue with a watch, or jittered backoff | Synchronised retries |
| Size and order | Per-resource locks taken in a fixed order | Two locks taken in opposite orders |
13. Trade-offs to Mention
A short lease frees a crashed worker's lock quickly and makes overlaps with slow workers more likely.
Waiting for the replica or a majority adds some milliseconds to every grant and makes loss of lock state rarer.
A safety margin before the lease ends is cheap and wastes good work.
A queue gives order and few requests, and costs more to build than polling.
Fine-grained locks give throughput and make multi-lock operations dangerous.
Fencing needs the storage to take part. A lock without it is a best-effort guarantee.
14. Common Mistakes
A lock with no expiry.
Treating a lock as proof that no one else can write, with no check in the storage.
Letting a worker decide that its own lease is still valid from its wall clock.
Releasing a lock without checking that you still own it, and so deleting someone else's.
Retrying without jitter, or with a fixed short interval.
Taking two locks in different orders in different code paths.
Using one lock for everything.
15. Interview Questions
What happens when the lock holder crashes? The lease expires and the lock passes on. The lease length trades waiting for overlap.
What happens when the holder is only slow? It may keep working after its lease has ended. A fencing token lets the storage refuse its writes.
Can a lock service ever be perfectly safe? Not by itself. Safety needs a check in the protected resource, or an idempotent action.
How do you keep the lock state if a node fails? Replicate to a majority, or use a consensus store that persists each grant to a majority before replying.
Why not use the worker's clock? Clocks jump and drift. Count the lease on the service and let the storage enforce it.
How do you stop many workers from hammering the service? A queue with a watch on the entry in front, or jittered exponential backoff.
How do you avoid deadlock? Lock the smallest thing, and take multiple locks in a fixed global order.
Summary
Every lock has a lease, and healthy workers renew it.
Every grant carries a fencing token that the storage checks, or the storage uses compare-and-set.
Keep the lock state on a majority of nodes, or in a consensus store.
Count time on the service, not on the worker.
Wait in a queue, or with jittered backoff.
Lock small things, in a fixed order.
Conclusion
A distributed lock looks like a simple flag and behaves like a promise about time and failure. The lease keeps a crashed worker from blocking the system, the fencing token keeps a slow worker from damaging the data, the majority keeps the promise alive when a node fails, and the queue and lock order keep the system moving. In an interview, say what a double grant costs, show where the check lives, and explain each of these choices with a number.
Previous topic: Design a Time-Series Database. Next topic: Design a Rate Limiter.
References and further reading
Martin Kleppmann, How to do distributed locking (2016), and the reply from the author of Redlock, for fencing tokens and the safety debate. Kleppmann, Designing Data-Intensive Applications, chapter 8, on clocks, process pauses and fencing.
Mike Burrows, The Chubby lock service for loosely-coupled distributed systems (OSDI 2006), for leases, sequencers and coarse-grained locks.
- ZooKeeper and etcd documentation on lock recipes, leases, sessions and watches. The Redis documentation on
SETwithNXandPXand on the distributed locks pattern. Ongaro and Ousterhout, In Search of an Understandable Consensus Algorithm (Raft, 2014).
Design Message Queue and Design a Time-Series Database on this site, for replication and acknowledgement ideas used here.