Part 7 · Blueprint 38
Distributed Lock Manager (etcd / ZooKeeper / Chubby Internals)
12 min reading · Sources · Editorial review pending
A paused holder can resume after its lease expires and corrupt state unless the target rejects it.
Page details
Published date · Last edited:
Draft edition. Editorial review and supplementary reading recommendations are still being completed.
Format: Architecture walkthrough. Prerequisites: the beginner bootcamp. Chapter prerequisites: Idempotency Keys & Distributed Retries, Distributed Consensus: Raft & Multi-Paxos.
Sixty-second mental model
Problem: A paused holder can resume after its lease expires and corrupt state unless the target rejects it.
Use: Enforce the fence at the resource, not just in the lock client.
Design boundary: Grant exclusive coordination claims without confusing lease expiry with stopping a paused process. The protected resource must enforce a monotonic fence where stale owners can cause harm.
Layer 1 · Intuition
Hypothetical scenario: Northwind is designing distributed locks. Maya represents product requirements, Dev implementation and Priya reliability. The team must agree what one lease means and which component owns the fenced storage operation.
Think of a numbered permit checked at the protected gate. Separate the requester from fenced storage operation, then identify the retained evidence needed after failure.
- Authority
- The entitled state owner.
- Invariant
- A rule preserved across concurrency and failures.
- Fencing token
- A monotonically ordered authority value checked by the protected resource to reject stale owners. Analogy: A newer numbered permit invalidating older permits at the gate.
Architecture and worked reasoning
Design boundary: Grant exclusive coordination claims without confusing lease expiry with stopping a paused process. The protected resource must enforce a monotonic fence where stale owners can cause harm.
Responsibilities on the request path
Workload and limiting resource
Hypothetical holder A receives fence 41 and pauses. Holder B later receives 42. The target remembers 42 and rejects A’s resumed mutation carrying 41 because 41 < 42. A timeout at the lock client cannot itself enforce that target-side comparison.
Keep the units attached to each intermediate result. The assumptions above describe a hypothetical exercise, not observed vendor capacity. A real capacity decision also needs a measured service curve, skew, recovery traffic and an explicit admission policy for overload.
Mutation or publication path
- Acquire lock with an exclusive epoch/fence.
- Attach that fence to protected mutations.
- Renew or stop initiating work when authority is lost.
Observation and recovery path
- Read current lease/epoch evidence.
- Reject stale fences at the protected target.
- Recover uncertain accepted work with stable operation identity.
Failure that changes the decision
Hypothetical scenario: A process pauses longer than its lease but resumes without knowing it expired. The target must reject its stale claim; local process health is irrelevant.
Attempt this decision before reading the explanation
Does checking the lease immediately before writing remove the race?
No. The process can pause between the check and the write. Enforce authority at the write boundary, not solely in the client.
Supporting mechanism analysis
Hypothetical scenario: Northwind. Maya represents product, Dev implementation and Priya reliability. The following workflow develops the underlying mechanism.
Priya: “What tells the effect boundary to reject the old worker when it returns?”
Before you continue: Does the passage of a lease deadline physically stop the old process?
This makes stale ownership visible at the relevant boundary. Work through the overlapping-run example before selecting the claim and recovery policy.
For this hypothetical sweep, identify an occurrence by the schedule identity and its intended scheduled instant. A delayed attempt should retain that identity rather than becoming a new logical occurrence merely because it starts later. Attempts and occurrences are separate in the same way that deliveries and product-update intents were separate in Page 20.
Several scheduler or worker instances can inspect the same due set. A claim mechanism must make the selected ownership transition exclusive under its database or coordination contract. Merely reading “unclaimed,” then writing an owner in a separate unprotected action, leaves a race where two processes can both proceed.
The protected metadata target must reject generation 7 after accepting generation 8 under the selected fencing rule. A process checking its lease before starting a network call leaves a pause window between check and effect. A token carried only in logs has no enforcement power. The target needs a monotonic comparison at the guarded transition, combined with the object publication and retained-reference rules.
Hypothetical worked example. Choose a sweep interval of sixty seconds and a run duration of ninety seconds. A run starts at time zero and would finish at ninety. The next scheduled instant is sixty. If both run, their overlap is 90 − 60 = 30 seconds.
Choose a claim made at time zero with a thirty-second lease and generation 7. Its worker pauses and does not renew. At time thirty-five, another worker obtains generation 8 under the selected atomic claim rule. The old worker resumes at time forty.
If the external object operation cannot enforce that generation directly, the application needs another supported protocol. For cleanup, a conditional metadata decision plus a carefully controlled object-deletion path may be part of it. A local ownership flag alone cannot certify safety for an unconstrained remote deletion.
Inspect the other stages rather than increasing scan concurrency reflexively. A remote deletion path, lock wait or repeated unresolved object check can dominate. An oldest-unfinished-intent signal tells a different story from the count of scheduler ticks that fired.
Kubernetes CronJob documentation describes scheduling behavior and concurrency policy. It also explains why scheduled work should tolerate the possibility of repeated or missed creation. Use the documented policy scope rather than assuming a scheduler provides a universal once-only business effect.
Revalidate the required object/version and publication state at the protected decision boundary. Ensure the chosen deletion protocol cannot act on obsolete authority after publication wins. A shorter lease or faster heartbeat does not repair this stale-decision race by itself.
Northwind chooses a recoverable sweep with explicit overlap, missed-run and cleanup rules. The next page gives occurrences, logical operations and delivery attempts distinct identities, then separates identity from chronological and causal order.
Layer 3 · Internals
An etcd lease can associate a lock key with a bounded lifetime, but the protected database does not automatically know that the client lost that lease. Imagine holder A pausing, its lease expiring, holder B acquiring ownership, then A resuming. A client-side assertion that A still owns the lock cannot prevent a late write.
Carry an increasing fencing token to the protected resource and require that resource to reject older tokens atomically with the mutation. An acquisition revision can be useful as a token only if its ordering and the resource's comparison rule match the design. A fence is not a secret and does not replace authorization. Lock-release operations also need an ownership check: an old client must not delete a successor's key. Use leases to discover ownership loss, watches to reduce unnecessary polling, and fencing to enforce authority where the effect actually occurs.
Trade-offs and limits
| Approach | Provides | Requires |
|---|---|---|
| Database conditional mutation | Enforces the invariant at the protected record. | Requires the database's contention and transaction budget. |
| Lease plus resource fence | Coordinates work while allowing a paused holder to be rejected. | The protected target must atomically enforce the monotonic token. |
Recovery decision
Hypothetical scenario: A process pauses longer than its lease but resumes without knowing it expired. The target must reject its stale claim; local process health is irrelevant.
No. The process can pause between the check and the write. Enforce authority at the write boundary, not solely in the client.
Write your design before revealing the review
Does checking the lease immediately before writing remove the race?
Drafts and self-review are stored only in this browser. They are separate from reading completion.
Compare your decision
No. The process can pause between the check and the write. Enforce authority at the write boundary, not solely in the client.
A process pauses longer than its lease but resumes without knowing it expired. The target must reject its stale claim; local process health is irrelevant.
Check your understanding
Does checking the lease immediately before writing remove the race?
No. The process can pause between the check and the write. Enforce authority at the write boundary, not solely in the client.
How would you recover from this failure: A process pauses longer than its lease but resumes without knowing it expired. The target must reject its stale claim; local process health is irrelevant.
Start with the exact boundary that failed. Acquire lock with an exclusive epoch/fence. Attach that fence to protected mutations. Renew or stop initiating work when authority is lost. Then recover evidence through the observation path: Read current lease/epoch evidence. Reject stale fences at the protected target. Recover uncertain accepted work with stable operation identity. Preserve the distinction between a confirmed state change and an unavailable response.
Which assumption in the worked calculation would a burst or concentrated tenant invalidate first?
Hypothetical holder A receives fence 41 and pauses. Holder B later receives 42. The target remembers 42 and rejects A’s resumed mutation carrying 41 because 41 < 42. A timeout at the lock client cannot itself enforce that target-side comparison. Recompute the affected resource rather than multiplying unrelated storage and network budgets by the same factor. Grant exclusive coordination claims without confusing lease expiry with stopping a paused process. The protected resource must enforce a monotonic fence where stale owners can cause harm.
Which component in this topology could be removed from a smaller first deployment?
Lease service, Lock holder, Fenced target, Recovery reader name responsibilities, not a requirement for separate processes. Co-locate responsibilities when their transaction, trust and capacity boundaries permit it. Acquire lock with an exclusive epoch/fence.
What evidence must a caller have before relying on the observation path?
Read current lease/epoch evidence. Reject stale fences at the protected target. Recover uncertain accepted work with stable operation identity. No. The process can pause between the check and the write. Enforce authority at the write boundary, not solely in the client.
45-minute interview rubric
- 00–05: scope lease and fenced storage operation.
- 05–12: identify the limiting resource and derive the domain workload above, retaining units and assumptions.
- 12–28: draw fenced storage operation, numbered writes and reads.
- 28–40: challenge recovery: Enforce the fence at the resource, not just in the lock client.
- 40–45: defend resource_id placement, observations and remaining assumptions.
Go deeper
- etcd API guarantees | etcd · Primary document · etcd.io. Enforce the fence at the resource, not just in the lock client. Verified 2026-10-26.
- CronJob | Kubernetes · Primary document · kubernetes.io. Enforce the fence at the resource, not just in the lock client. Verified 2026-10-26.
Decision log
Enforce the fence at the resource, not just in the lock client.
Preserve lease identity and fenced storage operation ownership.
Revisit changed workload, observations or recovery objectives.