Skip to main content

Distributed Leases

1. Executive Summary​

A distributed lease grants a holder time-limited, exclusive rights to a resource—a lock, a shard, write authority, or leadership—across processes that do not share memory or clocks. Leases decouple liveness from safety: if the holder stops renewing (crash, partition, GC pause), the lease expires and another participant may acquire the resource. Unlike pure consensus locks, leases trade strict mutual exclusion under all delays for availability and automatic recovery from failed holders.

Production leases almost always sit atop consensus or coordination services (Chubby, ZooKeeper, etcd, DynamoDB conditional writes) or wall-clock TTL with fencing tokens to protect storage from stale holders. Safety requires that expired lease holders cannot corrupt shared state; liveness requires renewal before timeout under normal conditions. Fencing tokens—monotonic numbers passed to downstream storage—are the standard defense against delayed writes from former lease holders.

This chapter covers lease semantics, renewal, fencing, comparison to consensus locks, failure modes, Chubby/etcd patterns, and principal-level design for lease-based systems.

2. Why This Topic Matters​

Distributed leases appear everywhere:

  • Leader election (Kubernetes controller leases, database primary).
  • Shard ownership in distributed storage.
  • Maintenance windows and migration gates.
  • Rate limiting and exclusive workers.

Architects must explain:

  • Why lease duration vs renewal interval matters (GC pause tolerance).
  • Why lease alone is insufficient without fencing for storage writes.
  • Difference between ephemeral ZK nodes and explicit lease APIs.
  • Clock skew assumptions in TTL-based leases.

Interview failures: treating leases as magic locks; ignoring stale primary problem; conflating lease with consensus commit.

Cost of getting leases wrong​

Incidents from missing fencing often exceed years of coordination-service cost—data corruption remediation, customer trust loss, and forensic engineering. The ROI of fencing is asymmetric: modest development effort on storage preconditions versus catastrophic tail risk. Principal architects should fund fencing integration before scaling shard leases to production traffic.

3. Problems Being Solved​

ProblemLease mechanism
Exclusive access with crash recoveryTTL + expiration
Leader election without permanent lockLease on coordination key
Prevent stale writerFencing tokens
Partition toleranceHolder stops renewing; loser stops writing
Load sheddingShort leases rotate work
Graceful handoffRelease lease before expiry

4. Assumptions and System Model​

AssumptionLease treatment
ClocksTTL leases assume bounded skew OR use logical renewal via consensus
NetworkRenewal messages may delay; must fit within TTL margin
Crash-stop holderStops renewing; lease expires
Storage layerMust honor fencing tokens if used
Coordination serviceOften consensus-backed for grant/renew atomicity
Not Byzantine by defaultMalicious holders need extra controls

Partial synchrony: Renewal succeeds if messages arrive within (TTL - safety_margin) under healthy conditions.

5. Essential Terminology​

TermDefinition
LeaseTime-bounded grant of exclusive right
TTL (time-to-live)Duration until lease expires without renewal
Renewal / keepaliveExtend lease before expiry
Lease holder / granteeProcess with current valid lease
Fencing tokenMonotonic ID issued with lease; storage rejects stale tokens
Stale lease holderProcess believing it holds lease after expiration
Grace periodOptional buffer before re-grant
Ephemeral znodeZooKeeper session-bound node (lease-like)
Lease revocationAdministrative early termination
Split brain (lease context)Two holders believe exclusivity—must prevent at storage
Safety marginTTL minus renewal interval minus max pause

6. Core Mechanism​

6.1 Basic lease lifecycle​

  1. Grant: Coordination service issues lease (resource, holder, expiry) or (resource, holder, ttl).
  2. Use: Holder performs privileged operations while valid.
  3. Renew: Holder periodically extends expiry before TTL elapses.
  4. Expire: If renewal fails, lease void; others may acquire.
  5. Release: Holder voluntarily ends lease early (optional).

Figure 1: Lease grant, renewal loop, expiration enables re-acquisition with new fencing token.

6.2 Fencing tokens (Martin & Stone 2005 pattern)​

Problem: Stale holder, after partition heals, writes to storage unaware lease expired.

Solution: Coordination service increments fencing token on each grant. Storage (e.g., GFS chunkserver, block store) rejects writes with token < highest seen.

Figure 2: Fencing—storage enforces monotonic tokens independent of lease holder belief.

6.3 Consensus-backed vs clock-based leases​

TypeGrant mechanismClock dependency
Consensus leaseReplicated log entry (Chubby, etcd lease)Low for validity; TTL may use logical time
TTL keySET key PX ttl NX (Redis)Higher clock sensitivity
Ephemeral sessionZK session + ephemeral nodeSession timeout driven

Figure 3: Lease grant paths—consensus vs TTL; both need fencing for storage safety.

6.4 Renewal timing inequality​

Let:

  • TTL = lease duration
  • R = renewal period
  • P_max = maximum process pause (GC, scheduling)

Safe operation requires: R + P_max < TTL (often R ≤ TTL/3 rule of thumb).

Violations cause false expiration or false confidence if holder continues without valid lease.

7. Step-by-Step Walkthrough​

Walkthrough A: etcd leader election lease​

  1. Controller calls Lease.Grant(TTL=15s).
  2. KeepAlive stream renews every 5s.
  3. Txn puts leader key bound to lease ID.
  4. Controller crashes; keepalive stops; key deleted after TTL.
  5. Standby acquires new lease and key.

Walkthrough B: Stale primary without fencing (failure)​

  1. Primary holds lease; partition isolates it from coordinator.
  2. Coordinator expires lease; secondary becomes primary (token 2).
  3. Primary rejoins; writes to database without token check.
  4. Split brain writes—data corruption.

Fix: Database or storage layer checks fencing token on every write.

Walkthrough C: Chubby advisory lock​

  1. Client acquires Chubby lock file with lease.
  2. Lock is advisory—must enforce at application/storage.
  3. Client maintains CheckSequencer or equivalent for storage writes.

Walkthrough D: Graceful release​

  1. Holder completes work; calls Revoke lease.
  2. Standby immediately competes—faster failover than waiting TTL.

Walkthrough E: ZooKeeper ephemeral node​

  1. Session established with timeout 30s.
  2. Create ephemeral /leader znode.
  3. Heartbeats maintain session.
  4. Client GC pause > 30s → session lost → node deleted → new leader.

Walkthrough F: DynamoDB conditional write as implicit fence​

Shard owner writes PutItem with condition attribute_not_exists(epoch) OR epoch < :new_epoch. New owner uses higher epoch after lease grant. No separate coordination service fencing token—version attribute plays the same role. Pattern generalizes: any storage supporting compare-and-swap can fence if epoch is monotonic and checked atomically with the write.

Walkthrough G: Lease duration sizing worksheet​

FactorExample value
P99 GC pause4s
P99 network jitter1s
Renewal interval5s
Minimum TTL≥ 3 × 5s = 15s (rule of thumb)
Safety-adjusted TTL15s + 4s + 1s = 20s recommended

Document these numbers in service SLO docs; revisit after JVM upgrades or kernel changes.

Walkthrough H: Graceful shutdown with lease handoff​

Holder calls Revoke, waits for coordinator ACK, then shuts down. Standby acquires immediately. Without revoke, standby waits full TTL—acceptable for batch jobs, unacceptable for user-facing failover targets under 5s. Product requirements drive TTL choice, not only infrastructure defaults.

8. Invariants and Guarantees​

8.1 Mutual exclusion (best effort)​

At most one valid lease holder per resource at coordination service—if service correct and clocks/consensus sound.

8.2 Safety with fencing​

Storage accepts writes only from holder with current fencing token → no stale writes even if holder misbehaves.

8.3 Liveness​

If holder crashes, lease expires within TTL; another can acquire.

8.4 Non-guarantees​

Lease does not guarantee holder stops immediately on partition—only that coordination service will eventually allow new holder.

8.5 Combining leases with consensus leadership​

Raft leaders implicitly hold leadership until higher term. Some systems add explicit leader lease (Raft lease read optimization) where followers trust leader for wall-clock window. This blends clock assumptions with consensus—document clearly when linearizability depends on bounded clock skew versus pure log ordering.

PropertyWithout fencingWith fencing
Exclusive grant at coordinatorYesYes
Stale writer prevention at storageNoYes
Automatic failoverAfter TTLAfter TTL

9. Failure Scenarios​

FailureBehavior
Holder crashLease expires; re-acquire
Coordinator partitionDepends on quorum; may pause grants
Renewal stormBackoff; risk expiry if overloaded
GC pause > TTLFalse loss of lease; duplicate holders without fencing
Clock skew forwardPremature expiry
Clock skew backwardDelayed expiry; longer stale holder window
Forgot fencingStale primary corruption risk
Lease too longSlow failover
Lease too shortChurn, false failovers

10. Performance Characteristics​

AspectBehavior
Acquire latency1 RTT to coordinator + consensus if replicated
Renewal overheadPeriodic load on coordinator
Failover timeUp to TTL (unless revoke)
ThroughputHigh for advisory; storage fencing adds check cost
Renewal fan-outN holders × (1/R) renewals per second
Coordinator CPULease keepalive streams dominate at scale

For N concurrent lease holders each renewing every R seconds, coordination service sees N/R renewal operations per second independent of business transaction rate. A cluster with 5,000 shard leases at R=5s generates ~1,000 renewals/s—size etcd or ZooKeeper clusters accordingly, or aggregate leases hierarchically.

11. Scalability Limits​

  • Coordinator hot spot for popular lease keys.
  • Renewal traffic scales with holder count.
  • Long TTL reduces renewal load but slows failover.
  • Shard lease responsibility by resource prefix.

12. Operational Considerations​

  • Set TTL ≥ 3 × renewal_interval.
  • Account for GC, container freeze, VM migration pauses.
  • Monitor lease expiration events and renewal failures.
  • Runbooks for manual revoke during stuck holder.
  • Document fencing support in downstream systems.
  • Kubernetes Lease objects: leaseDurationSeconds vs controller resync.

etcd lease specifics​

  • Leases are first-class objects with IDs.
  • Keys attached to lease deleted on expiry.
  • KeepAlive requires active gRPC stream.

Chubby lessons (from Google)​

  • Keepalive RPCs; advisory locks.
  • Sequencer for storage fencing.
  • Don't use Chubby as generic lock service without discipline.

Burrows' Chubby paper emphasizes that developers initially treated Chubby as a name service and only gradually learned lock discipline. The sequencer returned to clients monotonically increases on lock acquire and must be passed to GFS chunkservers. Principal takeaway: coordination and storage teams must jointly design fencing contracts—neither side alone delivers end-to-end safety.

Lease hierarchy and dependency​

Complex systems nest leases: cluster leader holds a coarse lease; shard owners hold finer leases. Dependency rules must ensure child leases expire when parent expires—otherwise a demoted cluster leader might still hold shard leases until TTL. Patterns include binding child keys to parent lease IDs in etcd or embedding cluster epoch in shard token validation.

Comparison to database row locks​

Single-database SELECT FOR UPDATE provides strong mutual exclusion within one partition but not across AZ failure. Distributed leases add partition tolerance at the cost of eventual exclusivity enforcement at the data plane without fencing. Interviewers may ask when to stay with DB locks—answer: single-region, single-primary DB with failover controlled by consensus or managed service, not ad hoc TTL keys.

13. Security Considerations​

  • Authenticate lease acquire/renew APIs.
  • Fencing tokens must not be guessable if security boundary depends on them.
  • Deny lease grant to unauthorized principals.
  • Audit lease grants on sensitive resources (shard ownership).

14. Cost Considerations​

  • Renewal traffic to coordination cluster (etcd/Chubby costs).
  • Short TTL → more renewals → more CPU/network.
  • Long TTL → longer outage detection window → business cost.
  • Engineering cost of fencing integration in storage layer.

15. Production Implementations​

SystemLease pattern
Google ChubbyLocks + sequencers + keepalive
etcdLease API + transactional keys
ZooKeeperEphemeral nodes + session timeout
Kubernetescoordination.k8s.io/Lease for leader election
RedisSET key value NX PX ttl (requires fencing elsewhere)
DynamoDBConditional writes with version attributes

16. Alternatives and Tradeoffs​

AlternativeWhen
Consensus lock (no TTL)Need strong exclusion; tolerate manual unlock
Database advisory lockSingle DB; not distributed partition tolerant
Raft leaderImplicit lease via leadership; no separate TTL
CRDT ownershipPartition-tolerant weak ownership

Leases when automatic expiry and crash recovery matter more than instant strict exclusion.

17. Common Misconceptions​

MisconceptionReality
"Lease = distributed lock with safety"Need fencing for storage safety
"Renewal always succeeds"Network/partition can fail renewals
"Ephemeral ZK node fences storage"Only coordination; app must enforce
"Short TTL always better"Causes false failovers
"Lease prevents split brain"Only with quorum coordinator + fencing
"Redis lock is production-ready alone"Redlock debates; fencing still required

18. Principal Architect Perspective​

  • Every lease design document must state fencing story.
  • Size TTL from measured P99 pause, not hope.
  • Prefer consensus leases for control plane; clock leases for best-effort caches.
  • Test partition with iptables—watch stale holder behavior.
  • Advisory vs mandatory locks—align team on enforcement layer.

19. Architecture Review Exercise​

Scenario: Sharded service uses 10s etcd lease for shard ownership; writes go directly to object store without token; JVM heaps cause occasional 8s GC pauses; overlapping shard writers reported.

Fix: Increase TTL margin (TTL ≥ 3× renewal + P99 GC); add monotonic shard epoch to object store conditional writes; metric on lease loss. Reject only shortening TTL.

Object store conditioning example: S3 conditional PUT on If-Match: "epoch-42" while new holder uses epoch-43. Document that eventual consistency stores without strong compare-and-swap may not fence—choose storage with linearizable conditional operations or layer a strongly consistent metadata service in front.

20. Whiteboard Explanation​

"A distributed lease gives one process exclusive rights to a resource for a limited time. It acquires the lease from a coordination service with a TTL and must renew before expiry. If the process crashes or can't renew, the lease expires and someone else can take over. The subtlety is that an expired holder might still try to write after a partition heals, so we issue monotonic fencing tokens with each lease grant and teach the storage layer to reject writes with old tokens. Leases trade immediate strong exclusion for automatic recovery and must be sized for renewal traffic, GC pauses, and clock skew."

21. Interview Questions​

  1. What is a distributed lease? — Time-bounded exclusive grant.
  2. Why renew leases? — Extend validity while holder healthy.
  3. What is a fencing token? — Monotonic ID; storage rejects stale.
  4. Stale lease holder problem? — Expired holder still writes.
  5. TTL vs renewal interval? — Renewal must fit inside TTL with margin.
  6. Chubby lock advisory? — Yes; enforce at storage/app.
  7. ZK ephemeral vs etcd lease? — Session node vs lease object API.
  8. Lease without consensus? — Clock TTL possible; weaker grant guarantees.
  9. Failover time bound? — Up to TTL after last successful renew.
  10. GC pause impact? — Can miss renew; duplicate holder risk.
  11. Why not infinite lease? — Crashed holder blocks forever.
  12. K8s Lease resource purpose? — Controller leader election.

22. Interview Follow-Ups​

  1. Design shard leader with etcd. — Grant, keepalive, txn put, fencing on store.
  2. Redlock critique awareness. — Clock assumptions; fencing still needed.
  3. Compare lease to Raft leadership. — Leadership is lease-like but log-scoped.
  4. Revoke vs wait TTL. — Revoke faster; must handle races.
  5. Metrics for lease health? — Renew latency, expiration rate, fencing rejects.

22A. Production Low-Level Design (Interview + Game Day)​

Design lease + fencing for shard ownership. Production LLD and Game Day Standard.

Control vs data plane​

PlaneComponentContract
Controletcd/ZK/Consul leaseTTL grant + renew; monotonic fence / epoch
DataShard store / object APIConditional write requires fence >= current

Acquire / renew / fence sequence​

Step-by-step flow:

StepActionNotes
1–2Grant + renewTTL ≥ 3× renew + GC p99
3–5Expiry + stale writeFencing saves safety
6–7New ownerStorage enforces epoch

APIs (sketch)​

  • LeaseGrant(ttl) → {lease_id, fence}
  • LeaseKeepAlive(lease_id)
  • Write(key, val, fence) → 409 if stale

22B. Game Day Playbooks​

#DrillInjectDetectMitigateVerify
GD-1GC pause > renewFreeze holder heapLease loss metricMargin TTL; fence rejectsNo dual writers
GD-2Partition holderIsolate holderExpiry; new grantFence oldStorage rejects F
GD-3Clock skewJump wall clockSpurious expiryPrefer monotonic lease serviceStable ownership

GD-2 — Partitioned stale holder​

23. Strong Answer Example​

Question: "Why are fencing tokens necessary if we already have distributed leases?"

Answer with the PRACTICE framework. Strong voice: leases = liveness of ownership; fencing = data-plane safety.

Student interview script (PRACTICE)​

P — Problem framing​

"A lease correctly expires at the coordinator when renewals stop—but the old holder may be partitioned, unaware, and still write to storage. Coordinator truth ≠ storage truth. Fencing tokens (monotonic epochs) make the storage reject stale holders."

R — Requirements​

GoalMechanism
Automatic failoverTTL lease
No dual writersFence on every write
Bound split windowTTL sizing + fence

A — Assumptions​

Lease service ≈ consensus-backed; storage supports conditional writes; clocks not trusted for safety across layers.

C — Capacity​

TTL ≥ 3× renew interval + GC/pause p99; renew QPS = holders / interval.

T — Topology​

Step-by-step:

StepLesson
1–3Ownership moved at coordinator
4–5Stale writer must fail at storage
6Only current fence commits

I — Invariants​

At most one valid fence for writes; lease expiry alone insufficient.

C — Constraints​

Advisory locks (Chubby-style) need app/storage enforcement; Redlock-without-fence is incomplete for mutual exclusion safety.

E — Evolution​

Add fence to object-store conditionals; metric fencing_rejects; chaos partition drills.

Closing line​

"Leases answer who should own and when to fail over. Fencing answers which writes storage may accept. You need both."

Scoring signals​

StrongWeak
Stale holder after partition"TTL means exclusive"
Storage enforces tokenetcd alone suffices
TTL margin for GCIgnore pauses

Compact outline (2 min)​

"Expired holder may still write. Monotonic fence on writes; storage rejects old fence. Lease=liveness; fence=safety."

24. Weak Answer Example​

Weak: "Leases expire after TTL so only one node writes. etcd handles exclusivity."

Red flags: No stale holder scenario; no fencing; conflates coordinator with storage.

25. Hands-On Exercise​

Lab: labs/lab-007-distributed-locks/ — leases + fencing on :8100

cd labs/lab-007-distributed-locks
go test ./... -v
docker compose -p lab007 -f docker/docker-compose.yml up --build -d
chmod +x scripts/demo_locks.sh && ./scripts/demo_locks.sh
StepEndpointWhat happens
1POST /v1/locks/acquireLease grant with TTL + lock token
2POST /v1/fencing/issueMonotonic fence token for resource
3POST /v1/resource/writeStorage accepts write when fence > max_fence
4POST /v1/locks/releaseExplicit release before TTL expiry
5POST /v1/resource/writeStale fence rejected after re-acquire

Swagger: http://localhost:8100/docs

Engineer guide: how the local stack works​

  1. Coordination plane — lock service simulates etcd/Redis lease acquire, renew, release.
  2. Fencing service — issues strictly increasing tokens per resource (Kleppmann pattern).
  3. Data plane — resource API enforces fence_id > last_fence — not advisory-only.
  4. Stale holder demo — release + re-acquire shows old fence rejected even if lock "felt" held.
  5. TTL semantics — short TTL + missed renewals allow second acquirer; fencing prevents corruption.

See also Fencing Tokens chapter for theory; this lab is the runnable stack.

Build-from-scratch exercise (optional)​

  1. Implement etcd lease lock with concurrency package or clientv3 lease API.
  2. Simulate holder pause > TTL; observe second acquirer.
  3. Add mock storage checking token > maxToken.
  4. Demonstrate stale write rejection after re-acquire.
  5. Tune TTL/renewal; graph false failover vs failover delay.

26. Knowledge Check​

  1. Lease lifecycle stages?
  2. Fencing token purpose?
  3. Safe renewal inequality components?
  4. Advisory lock meaning?
  5. etcd KeepAlive role?
  6. ZK session timeout effect?
  7. Failover time bound?
  8. Split brain without fencing?
  9. Why TTL not too short?
  10. Consensus vs clock lease?
  11. Chubby sequencer role?
  12. K8s Lease vs Endpoints legacy?

27. Flashcards​

FrontBack
Distributed leaseTime-limited exclusive resource grant
TTLDuration until expiry without renewal
Renewal / keepaliveExtend lease before timeout
Fencing tokenMonotonic ID; storage rejects lower tokens
Stale holderThinks lease valid after coordinator expired it
Safety marginTTL − renewal − max pause
Advisory lockCoordinator tracks; app/storage must enforce
Ephemeral znodeZK session-bound; deleted on session expire
etcd Lease APIFirst-class lease ID + KeepAlive stream
Failover bound≤ TTL after last successful renew
GC pause riskMissed renew → false expiry / dual holder
Fencing vs leaseLease transfers ownership; fencing protects storage

28. Cheat Sheet​

LEASE LIFECYCLE: grant → renew loop → expire/release

TIMING: renewal_period + max_pause < TTL (often TTL/3 renew)

STALE HOLDER: partition → expire → rejoin → writes anyway
FIX: fencing tokens at storage

FENCING: coordinator increments token; storage max(token) check

PATTERNS
etcd: Lease + KeepAlive + Txn attach key
ZK: ephemeral znode + session timeout
Chubby: lock + sequencer for storage
K8s: coordination.k8s.io/Lease

OPS: monitor renew failures, size TTL for GC, test partitions

30. References​

Primary sources (formal guarantees)​

  • Gray, C., & Cheriton, D. (1989). Leases: An Efficient Fault-Tolerant Mechanism for Distributed File Cache Consistency. SOSP. [Original lease concept]
  • Burrows, M. (2006). The Chubby lock service for loosely-coupled distributed systems. OSDI. [Production leases + fencing sequencers]

Implementation-oriented​

  • Sanfilippo, S. — Redlock critiques and responses [clock-based lock limitations—verify current arguments before citing in interviews]

Books​

  • Kleppmann, M. (2017). Designing Data-Intensive Applications. [Chubby, fencing discussion]

Distinction​

  • Formal guarantees — Lease validity at coordinator when protocol correct.
  • Implementation choices — TTL values, renewal transport, fencing integration.
  • Operational experience — GC pause incidents; measure P99 pause in your runtime.