Leases, Locks and Fencing
A lock inside one process cannot be lost without its holder knowing. A lock across machines can. The holder stops for a while, the lock expires, someone else takes it, and the first holder wakes still sure that it holds the lock.
The fix is not a better lock. It is a resource that can tell an old holder from a new one, and a design that knows which of its locks protect correctness and which only save work.
The Holder That Paused
One story covers the whole problem. A web crawler's workers each take a lock on one partition of the frontier, the list of URLs still to fetch, which is the crawler of Chapter 12. One worker pauses: a long garbage collection, its virtual machine moved to another host, or a network cut. Its lock expires. A second worker takes the partition and writes. Then the first one wakes and writes too.
Checking the lock just before writing does not help, because the pause can fall between the check and the write. Locks inside one machine, and what they cost, are Computer Science Deep Dive's subject. Across machines, that gap between the check and the write is the whole problem.
Leases: Locks That Expire
A lock with no expiry is held for ever by a holder that crashed. A lease grants the right for a stated time and must be renewed; Gray and Cheriton named the idea in 1989. etcd deletes the keys attached to a lease whose holder stops keeping it alive, and ZooKeeper deletes an ephemeral node when its holder's session ends.
The length is a choice with a cost on each side. Assume a 10-second lease. A crashed holder blocks the work for up to 10 seconds. A pause longer than 10 seconds makes a second holder. Shorten the lease when the wait after a crash hurts; lengthen it when holders lose leases they were still using. Either way, the second holder is what fencing is for.
The holder stops acting a margin before its own deadline, and both sides time the lease on a monotonic clock, the one that never runs backward. So what matters is how fast the two clocks drift apart during one lease, not whether they agree on the time of day.
Fencing Tokens
The lock service gives every grant a number larger than the last one: etcd's revision, a ZooKeeper sequential node, or the lock generation number inside the "sequencer" of Google's Chubby. The holder sends the number with every write. The resource remembers the highest number it has accepted, and refuses anything lower.
In the story, the second worker takes the lease with token 34 and writes. The first wakes and writes with token 33, and the store refuses it. The check lives in the resource, so the resource must be able to make it: a conditional write on a token column, or a storage API that takes a precondition. A resource that cannot check, such as a card processor, gets an idempotency key instead, which Backend Deep Dive teaches in its lesson on idempotency keys.
A Lock in a Cache Is Not a Lock
The usual shortcut is a key set only if it is absent, with an expiry, on a cache node. Three things break it as a correctness lock. The expiry runs on the cache's clock. A replica that receives writes asynchronously can take over without the key, as Chapter 4's first lesson explains, and grant the lock a second time. And nothing in the key grows with each holder, so nothing downstream can fence.
It is still the right tool for a lock that only saves work. Backend Deep Dive runs its scheduler under one, safely, because the job it guards changes nothing when it runs twice. The rule: when a duplicate costs work, a cache key will do. When a duplicate costs money or data, use a lease from a consensus service with a fencing token, or no lock at all.
Often No Lock at All
The store's own conditional write, an update that applies only if the version is still the one you read, settles most races without a lock service, and so does a unique constraint. One owner per partition removes the race entirely.
A hotel's hold on a room while the guest pays, the design of Chapter 23, is a lease kept in the database: a row with an expiry that the booking path respects. The one-database version of the same race, settled with a row lock and a constraint, is Backend Deep Dive's lesson on the oversell.
An efficiency lock stops two workers doing the same work, and a lapse costs a duplicate run. Use a cache key with an expiry, and make the work idempotent.
A correctness lock stops two writers corrupting shared state, and a lapse costs data or money. Use a lease from a consensus service with a fencing token that the resource checks, or replace the lock with a conditional write in the store.
How Interviewers Probe This
Lock probes come back to the pause story and the fencing token, and to whether a lock was needed at all. The first probe is "Two workers both believed they held the lock. How did that happen, and what limits the damage?" A good answer tells the pause story, says that no check by the holder closes the gap, and adds a fencing token that the resource checks on every write.
The second is "Why not take the lock in Redis?" A good answer asks what a duplicate costs. For a job that is safe to run twice, a cache key with an expiry is right. For a write that must happen once, it says why the cache cannot fence, and moves the lock to a consensus service or to a conditional write. You might say: "If this job runs twice we lose a few seconds of work, so a key with an expiry is fine. The payout write is different, so it carries a token the ledger checks."
The third is "How long is your lease?" A good answer gives the length as an assumption with both of its costs: how long a crashed holder blocks the work, and the second holder that a longer pause creates, which the fencing token catches.
- "Check that you still hold the lock before writing." The pause can come after the check. Only the resource, checking a token at the moment of the write, closes the gap.
- "A lease renewed often cannot lapse." A paused process sends no renewals, so a pause longer than the lease lapses it however often the renewals were scheduled.
- "The lock service guarantees mutual exclusion." It guarantees one holder per grant as the service sees it. A holder that lost its lease without knowing is still running, and only fencing stops its writes.
- "A lock in a replicated cache is safe." Replication to the replica is asynchronous, so a failover can forget the key and grant the lock a second time.
- "A longer lease is safer." It shortens no pause, and it makes every crash cost the full lease before anyone takes over.
- Ask what a duplicate costs before choosing a lock: work, or data and money.
- Fence every correctness lock with a number that grows, checked by the resource on every write.
- State the lease length as an assumption with both of its costs: the wait after a crash, and the second holder after a pause.
- Use a conditional write or a unique constraint in the store instead of a lock service when one store holds the state.
Knowledge Check
A worker checks that it still holds the lock, then writes. Why does the check not stop a second holder's damage?
- Because the lock service answers checks from a cache that can be stale
- Because the pause can fall between the check and the write that follows
- Because the check itself renews the lease and so hides that it lapsed
- Because the lock service can grant one lease to two workers at a time
What must a resource be able to do for fencing tokens to protect it?
- Renew the lease on the holder's behalf whenever the holder is paused
- Read the lock service's current holder before every single write
- Remember the highest token it accepted and refuse any write below it
- Keep its clock in step with the lock service to within a millisecond
A scheduler job that rebuilds a report runs twice if two workers both take its lock. What is the lightest lock that is safe here?
- A cache key set only if absent, with an expiry, and an idempotent job
- A lease from a consensus service, with a token the report store checks
- A two-phase commit between the workers that agrees on which one runs
- No lock and no idempotency, since a report is only read by people
A team raises its lease from 10 to 60 seconds to stop seeing two holders. What does that change?
- It removes the second holder, since no pause lasts as long as a minute
- It changes nothing, because the lease length plays no part in either cost
- It makes renewals six times less frequent, so the lock service is faster
- A crashed holder now blocks the work for up to a minute before a takeover
Two requests may update the same account row in one database at once. What is the simplest safe choice?
- A lease from etcd around every update, with a fencing token on the row
- A conditional write that applies only if the row's version is unchanged
- A cache key per account, set only if absent, that each request takes first
- Let the last update win, since the two requests arrive close together
You got correct