Ch.67: System Design: What a Distributed Lock Really Protects
Outline
- 0:00 What a distributed lock protects
- 0:25 Separate ownership from the receiving check
- 0:49 Define acquisition, waiting and recovery
- 2:03 Calculate renewal and control traffic
- 3:12 Agree on one ownership decision
- 4:21 Authenticate the grant and reject stale writes
- 5:50 When a newer grant has not reached the catalog
- 6:59 Check current ownership in one transaction
- 8:12 Recover an acquisition after a lost reply
- 9:32 Renew permission without assuming execution stops
- 10:46 Wait for a predecessor and recheck the queue
- 11:59 Cancel or release the exact grant
- 13:05 Keep one authority through quorum loss
- 14:24 Find the delay without disabling protection
- 15:33 Return to the complete architecture
- 16:08 Match the promise to the commit check
Transcript
0:00 A distributed lock service lets programs on different machines take exclusive turns with a named resource, such as publishing a backup catalog entry. We'll design how they acquire, wait, renew and recover ownership, then follow the protected write to the system that actually accepts it. Because an old owner can wake up after losing permission and overwrite newer catalog data. That's the risk our receiving system has to contain. So our map separates two decisions. Client programs ask a replicated lock store for a turn; later their catalog writes face a separate receiving check.
0:33 Yes. The store records ownership and notifies waiters. The catalog accepts or refuses the resulting change; it can't stop whoever sent it. Let's use A and B to define the caller's operations. We'll come back to this diagram once we've followed both decisions. Now imagine two backup programs, A and B. Our functional requirements cover publishing the catalog pointer that tells readers which completed backup to use. A asks for a named lock and gets an exact grant or busy. Waiting, renewal, release and cancellation must also be explicit caller operations.
1:06 And authorize the customer's namespace, or tenant. A and B share one backup-entry name; another customer's identically named lock must stay separate. I'd keep uploading the backup outside that short ownership period. The lock covers publishing its pointer, not the whole potentially long transfer. Yes. A session tracks the client's continuing relationship with us and can expire. Each grant identifies one acquired turn within it. Suppose A never receives the grant response. Do we also need to tell it whether its request succeeded?
1:37 We do. Looking up that outcome is a requirement, not an optional debugging endpoint. Otherwise a timeout can leave A retrying beside its own successful request. Okay, the API needs more than lock and unlock. It must let the caller resolve uncertainty without inventing another owner. And an explicit busy response lets the client choose whether to wait. We don't need to keep an unlimited queue on its behalf. With uncertain replies in mind, our non-functional requirements preserve acknowledged ownership, isolate tenants, and refuse conflicting grants when the authority cannot safely agree.
2:11 For scale, assume a fictional 10,000 sessions renewing every 5 seconds. That's 2000 renewals each second before anyone acquires a new lock. Add 500 acquisitions and 500 releases per second. We now have 3,000 logical control commands, before retries, waiting and replication work. Oh, most of our requests are keeping existing sessions alive. We could size this service around new jobs and miss the cost of maintaining their ownership. Those numbers are design inputs, not measured capacity. We still need to test the chosen store and distinguish a quick uncontended request from waiting behind another owner.
2:49 Could we promise every acquisition finishes quickly, then put the slow ones in a queue? We can promise a prompt status response, not a short ownership wait. If A holds the name, B's wait depends on A and recovery. Fair enough. B can get a quick answer saying it's waiting, yet spend much longer behind A. We'd measure those two delays separately. So A and B need one replica group to agree about their lock. Every gateway sends decisions about this name to that same group. So could each gateway remember the last owner it heard from?
3:24 Or does even that first acquisition have to reach this shared record? It reaches the shared record. If A's valid session asks for a free name, one checked update grants it. A gateway's possibly stale memory can't decide. And a quorum is the set of replicas required to agree. For example, a three-replica design normally needs two, rather than letting an isolated replica issue its own grant. Agreed, we'll use an existing store's replica-agreement algorithm, not invent one. What does the client receive besides the grant identity?
3:56 An increasing fencing number, an order marker for successive grants on this name. We'll carry it to the catalog alongside the proposed pointer change. The Chubby paper puts responsibility at the receiving server too; its links are in the description. The lock decision alone isn't the end of the operation. Yes. Keep one durable grant and enough request identity to recover it. A retry mustn't quietly become a separate acquisition. Now consider a delayed catalog update. A pauses with an old pointer; its session expires.
4:27 B takes over and publishes a more recent backup. Give A fencing number 41 and B 42. How does the catalog use those numbers when A's delayed update eventually arrives? First, our authority signs a receipt binding the caller, tenant, lock name and fencing number. The catalog knows that authority's trusted public verification key. And verifies the signature, caller and target before trusting the number. That proves the grant was issued, not that A has permission now. Exactly. Then the catalog atomically compares that authenticated number with the entry's durable highest accepted number and performs the update.
5:04 Keep both changes together. B's accepted 42 moves that stored boundary forward. When A presents 41, the catalog refuses to replace the pointer with A's older choice. Exactly. Not a separate read, then an unguarded write. Otherwise both requests could pass their checks before either update changes the stored boundary. The indivisible check reminds me of numbered delivery instructions at one desk. Once it accepts instruction 42, an old instruction 41 can't reverse it. The clerk has to check the instruction while changing the ledger, not wave it through and let another clerk update the ledger later.
5:40 Yes, and that check survives a catalog restart. A number remembered only in memory could disappear just when the delayed request finally turns up. But the delivery-desk picture exposes a limit: the clerk can reject an obsolete instruction only after learning a newer number. Hold on. B might own 42 while the catalog remembers 40. Can A's expired 41 get accepted first? Under this stored-highest-number rule, yes, if A's grant authenticates and 42 hasn't arrived there. The receiver can't infer new ownership from an unseen message.
6:15 Ah, already accepted. We're stopping 41 from undoing 42, not refusing every write after expiry. I'd been giving that comparison a stronger promise. That's the promise. It doesn't stop A's execution, its upload, or necessarily its first stale write before the newer boundary arrives. Then why not ask the lock service whether A is current immediately before accepting the catalog write? That read can become stale before the separate write commits. A check followed by a network hop still leaves time for ownership to change.
6:48 Okay, I'd want the stronger requirement stated explicitly before shipping. If every write must belong to the current owner at commit, this separate high-water check isn't enough. That stronger requirement leads to moving the protected record into the same transactional store as ownership, if the application can accept that design. Then one transaction checks that A's exact ownership key still exists and changes the protected record. Expiry and that checked write have an authoritative order. The etcd lock API explicitly returns a key you can use in such a transaction.
7:22 It doesn't extend that transaction across arbitrary external systems. So a small coordination record may fit there, while a huge backup upload doesn't. We'd still separate storing backup data from publishing its catalog pointer. And sometimes the application database already owns the invariant. A transaction or conditional update there can remove the need for a separate lock service. I like starting with that objection. If both coordinators update one database row, adding another authority may add uncertainty rather than remove it.
7:53 Yes. Our two designs differ in what gets checked at commit: an observed order marker at an external catalog, or current ownership inside one transaction. With either design, a lock doesn't turn an external mail request into part of our transaction. That service still needs its own duplicate-handling contract. With both receiving rules clear, consider a lost reply. A's acquisition commits, but A times out while our store already records that acquisition as successful. Wait, retrying could pit A against an acquisition that already succeeded.
8:26 My first thought was to start over. How do we recover the original outcome? A request identifier, scoped to that authenticated caller, session and name. Retry it or look it up, and return its recorded outcome while the session remains valid. Like keeping the receipt number when a reservation page stops responding. Starting over with a new number can reserve twice instead of discovering the first result. And the service has to remember the receipt. We retain request outcomes for the active session; an expired or unknown session doesn't silently become a fresh acquisition.
8:58 Then A explicitly opens a new session when needed. It can't assume an old request succeeded just because the same lock name is currently free. ZooKeeper's published lock recipe handles a related lost-create reply by finding the contender's unique identifier. That's one concrete recipe, not every vendor's API. Got it. A timeout means an unknown result to resolve. Once A recovers a real grant, it still needs to keep that grant alive. We also reject reuse with different parameters. Keeping the identifier while changing the target name must not accidentally return ownership of something else.
9:32 Once A has recovered its grant, renewal keeps it alive. A lease is permission with an expiry; a heartbeat requests an extension, not proof of finished work. Suppose we request a 15-second lease and renew every 5 seconds, purely as an illustration. Missing one heartbeat doesn't immediately prove A has died. It may be paused, partitioned or waiting on a slow response. Longer leases reduce sensitivity to those gaps, but can delay reassignment after a real disappearance. And shorter renewal intervals mean more traffic.
10:05 We still haven't made A's CPU stop when its permission expires. Yeah. The backend owns the actual expiry decision. A local timer in A is a conservative reason to stop starting protected work, not authority to grant B ownership. I'm not sure how that uncertainty should appear in the client library. What can it safely tell the application when renewal stops replying? Mark ownership uncertain and hold back new protected changes while checking with the authority. Confirmed expiry means lost ownership; silence never counts as a renewal.
10:37 That helps a cooperative client, not a paused one. It's why the catalog keeps its check even when our library loses contact with A. Now handle the clients waiting behind A. If 1,000 contenders all wake after each release, they send 1,000 requests toward one available turn. Suppose A holds the lock, then B and C join in order. Does C need to wake whenever A's grant disappears, even with B ahead? No. In ZooKeeper's recipe, B watches A's entry, and C watches B's. Each waits for the request directly ahead, then checks the queue again.
11:13 So C starts watching B's entry, but B disappears before that watch is installed. Could C wait forever for a notification it already missed? If B's entry is already gone, C rereads the queue instead of sleeping. After a notification it also rechecks. A wakeup still isn't an ownership grant. Right, the notice only says something may have changed. Timeouts and retries also need that recheck, rather than trusting an old queue position. I'd keep fairness claims modest. A predecessor queue limits unnecessary wakeups, but it doesn't give every client a bounded wait through disconnects and expired sessions. So we can reduce the stampede without claiming unlimited fairness.
11:53 A waiting request still has a distinct identity, which matters when its caller gives up. Now cancellation has to remove the right waiting identity, even when leaving the queue races with becoming owner. Resolve which state actually won. For example, B cancels its waiting request just as A releases. If B's grant already committed, acknowledge that outcome and release that exact grant. Otherwise that client hears canceled while B still owns the name. Normal release needs the same precision if its message is delayed.
12:23 Absolutely. Suppose A's late release arrives after B takes ownership. Deleting by lock name alone would erase the wrong grant, allowing another client to acquire. So require the expected grant identity in the release operation. If the current grant differs, A's message can't change it. Check the caller's authorization too. Knowing a name or guessing a grant number doesn't entitle someone to release another customer's lock. The catalog checks incoming writes; conditional release guards the ownership record.
12:53 Knowing the resource's name doesn't let A remove whoever owns it now. Yes. A tidy ownership record doesn't make old requests disappear. Cancellation, release and resource checks each guard a different operation. Now protect that commit guarantee during a coordination failure. Losing one replica must not mean inventing a second independent ownership authority. With our three replicas, two connected ones can still decide. Changing which replica coordinates decisions may delay replies, so callers check their uncertain request outcomes.
13:23 But lose the required quorum and new grants stop. Could an isolated gateway temporarily grant a lock that its local cache says is free? No. Its cache can lag behind an accepted grant on the other side. Favoring availability that way can create exactly the conflicting authority we're avoiding. Refusing an acquisition doesn't erase existing application work either. The receiving catalog enforces its contract while clients handle uncertain or expired sessions. For more names, use separate replica groups.
13:51 If we move this name, what stops A reaching the old group while B reaches the new one? They need one authoritative group, even during that move. Separate owners on old and new groups would recreate our original failure. And 1,000 machines wanting this backup entry still share one turn. I'd shorten its protected update and bound the queue before adding capacity. Otherwise we just store more frustrated contenders. Expose a busy response when that waiting budget is full instead of pretending the extra requests are progressing.
14:24 With that waiting queue staying full, how do we tell whether our lock service is slow or A simply isn't finishing its catalog update? Start with B's wait and A's publication. Healthy renewal replies don't explain a growing queue. Separate request handling delay from time spent behind the owner. And if the catalog rejects A's old fencing number, a delayed request reached a receiver that already accepted something newer. That's evidence from the receiver. Find A's request, session and grant under that customer's lock name.
14:54 Don't log credentials or show another tenant's records. Suppose the operator sees no recent heartbeat and wants an administrative break. Does forcibly removing the grant make the old worker harmless? No. Canceling the reservation doesn't unplug A's machine. Record the break, check the catalog, and keep its protections; old requests may still arrive. Yeah, I'd rather the diagnostic screen show uncertain than quietly imply safe. A broken connection gives us less knowledge, not more control over the client.
15:23 So the operator has to find which boundary is holding B up, not just clear a lock. Let's trace A and B on our original map. Finally, back on the same complete architecture, A's request reaches the ordered ownership store. Renewal keeps its session alive until the authority eventually expires it. The next waiting coordinator rechecks and B gets the next grant. B's accepted catalog change stores the higher fencing number alongside its backup pointer. A can still wake up. But its lower-numbered update can't reverse that accepted change at the catalog.
15:57 The receiver enforces what the lock service alone cannot. Or we keep the small protected record beside ownership and check both in one transaction. The placement determines which promise we can make. So two processes may believe they have a turn even though the service records one current owner. Neither a timer nor a wakeup removes that gap. We resolve uncertain requests by identity, order ownership decisions, and check protected changes at their commit boundary. Choose the external fencing promise or same-store transaction honestly.
16:27 Then acquisition success means exactly what it says: a grant under that service's rules. The application still needs a receiving system that can enforce the promised protection. Thanks for listening to Learning Podcasts.