DISTRIBUTED LOCK SERVICE

The lock is the easy part; the expiry is the hard part

L320 MINSYSTEM DESIGN
PREDICT

A lock grant is a lease (it expires on its own) and carries a token, a number that goes up with every grant. C1 holds a 10 s lease with token 33 and freezes in a GC pause. The lease expires; C2 acquires token 34 and writes. C1 wakes at 15 s and writes. The lock store is a healthy Raft cluster. What decides whether C1's write lands?

A lock service needs three things. The grant must survive a failover, so it lives in a store that commits on a majority (Raft, etcd, ZooKeeper), not on one node with an async replica. The grant must be a lease, because a dead holder never releases. And every grant carries a fencing token, a number that only goes up, which the protected resource checks on every write. The lease keeps the system moving; the token stops a holder whose lease expired behind its back from overwriting a newer holder. It only orders writes: a stale write that lands before the new holder’s first write is still accepted. For multi-step work the resource must also check the token on reads, or use conditional writes.

▶ SIMULATION
CLIENT C1
believes it holds: no
lease —
—
LOCK SERVICE (single node)
P primary: free · ctr 32
R replica: free · ctr 32
unreplicated grants: 0
CLIENT C2
believes it holds: no
lease —
—
clockt = 0 s
grants—
resource (fencing)value "—" · highest token — · accepted 0 · rejected 0 · older-epoch writes accepted 0
write log—
✓ at most one holder per epoch (no fencing token granted twice)✓ resource never accepts a write from an older epoch than one it has seen
SCHEDULE
01[LOCK]LOCK: single primary P + async replica R (lag 1 s); resource fences on token
02[C1]C1: acquire lock on /jobs/nightly @ 0 s
03[LOCK]LOCK: leader process dies @ 0.5 s; failover
04[C2]C2: acquire lock on /jobs/nightly @ 1 s
05[C1]C1: write "A1" to the resource @ 2 s
06[C1]C1: stop-the-world GC pause begins @ 3 s
07[LOCK]LOCK: clock reaches 12 s; C1 never renewed, lease ended at 10 s
08[C2]C2: acquire lock on /jobs/nightly @ 12 s
09[C2]C2: write "B" to the resource @ 13 s
10[C1]C1: GC pause ends @ 15 s; still believes it holds the lock
11[C1]C1: write "A2" to the resource @ 15 s
12[RESOURCE]RESOURCE: report
Start of single node + failover scenario. 12 steps.
// lock service: a lease on a consensus-backed key (etcd / ZooKeeper / Chubby)
grant = store.txn(if key is free or its lease expired:
                    put(key, me, lease=10s) -> revision)   // committed on a majority
token = grant.revision                                     // strictly increasing, survives failover

// client
while (work remains):
  if (!store.renew(lease)) abort()                         // lost it: stop
  resource.write(data, token)                              // a pause can still land here

// resource: the only place that can tell a stale holder from a live one
write(data, token):
  if (token < highestSeen) reject()
  highestSeen = token; apply(data)

All three designs run the same timeline: the lock leader dies half a second after granting C1, C2 asks for the lock, C1 freezes past its lease, C2 takes over and writes, C1 wakes and writes. SINGLE NODE breaks the epoch invariant at step 4, when the promoted replica hands out token 33 a second time. NO FENCING survives the failover and breaks at the end, when C1’s old token lands after C2’s. With FENCING both invariants stay green and C1’s last write is rejected.

BREAK IT NOT YET

A single-node lock server with an async replica, and a resource that checks fencing tokens. Inject one fault so that two clients hold the same epoch, or a write from an older epoch lands after a newer one. Try both faults; only one of them gets through, and only at the right moment.

GOAL: a fencing token is granted twice, or an older-epoch write lands after a newer one

FIX IT NOT YET

C1 writes a job in chunks under a 10 s lease; each chunk takes 4 s. Make runJob safe: keep the lease alive while you work, stop when you lose it, and pass the fencing token on every write so the resource can refuse you after a pause. Return true if every chunk landed, false if you lost the lock.

Mental model:

A distributed lock is a promise with an expiry date, and the holder cannot know when its clock and the store’s disagree. So stop trusting the holder. Put the grant in a consensus store so a failover cannot forget it, and make the resource the judge: every write carries a fencing token, and the resource refuses any number lower than one it has seen.

IN PRODUCTION

Leader election and cron-job singletons on etcd, ZooKeeper, Consul or Chubby; Kubernetes Lease objects; Redis SETNX locks that work until the first failover. The symptom is a job that ran twice, or a file written by two owners, with logs on both sides saying they held the lock.

IN INTERVIEWS

“Design a distributed lock service.” Start on the whiteboard with one lock server and ask what happens when it dies: no replica means unavailable, an async replica means a double grant. Move the lock into a Raft-backed key so a grant is committed on a majority before it is acknowledged. Then add a TTL, because clients crash, and draw the GC pause that outlives it. Close with fencing: the store issues a monotonic token per grant, the client sends it with every write, and the resource rejects anything older than the highest token it has seen. Say plainly that a lock without fencing is only safe for efficiency, never for correctness.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: UNIQUE ID GENERATOR →