← Back to System Design, page 3

system-design-0045 · Hard senior

Design a distributed lock service. How do you guarantee safety when a lock holder pauses or crashes?

Build the lock service on a consensus store such as etcd or ZooKeeper: a lock is a key created only if absent and tied to a lease that expires unless the holder renews it. Every grant returns a monotonically increasing fencing token, and the protected resource rejects requests carrying an older token, which keeps things safe even if a paused holder wakes up after its lease expired.

Full answer

Requirements

Functional:

  • acquire(name, ttl), renew, release; optional blocking acquire with a wait timeout.
  • Only one holder per lock name at a time.

Non-functional:

  • Safety: two clients must never both act as the holder in a way that corrupts data.
  • Liveness: a crashed holder's lock is released automatically.
  • Highly available; acquire latency of a few milliseconds inside a region.

Capacity estimates

Assumptions: 20,000 lock acquisitions per second at peak (for example, per-student job locks in a grading pipeline); each lock lives 2 seconds on average with one renewal; a 3-node consensus cluster sustains about 10,000 writes per second (an assumption that depends heavily on disks and network; benchmark it).

  • Writes per lock lifecycle: acquire + renew + release = 3 consensus writes.
  • Total: 20,000 x 3 = 60,000 writes per second.
  • At 10,000 per cluster: 6 clusters minimum; plan 8 for headroom. Partition lock names across clusters by hash. A single lock always lives on one cluster, so safety is unaffected by partitioning.
  • Storage is tiny: active locks at any moment = 20,000 x 2 s = 40,000 keys (Little's Law), a few MB.

These numbers show that consensus throughput, not storage, is the limiting resource, and that heavy lock users should consider partitioning work so fewer locks are needed.

API

POST /v1/locks/{name}/acquire {"ttl_ms": 5000, "wait_ms": 1000} -> 200 {"lease_id": "L77", "fencing_token": 918273} or 409 if not acquired in time POST /v1/locks/{name}/renew {"lease_id": "L77"} -> 200 | 410 (lease expired) POST /v1/locks/{name}/release {"lease_id": "L77"} -> 204

Most teams use the client libraries of etcd or ZooKeeper directly rather than wrapping them in a service; the design is the same.

Data model

  • Key /locks/{name} -> {owner_id, lease_id}.
  • The fencing token is the store's revision number at creation (etcd's mod_revision or ZooKeeper's zxid), which increases with every write in the cluster.
  • Waiters: in ZooKeeper, each waiter creates a sequential ephemeral node under /locks/{name}/ and watches only the node just before it; in etcd, waiters watch the key before theirs by revision. This gives a fair queue and avoids waking all waiters at once.

High-level design

mermaid
flowchart LR
  C1[Client A] --> LS[Lock client library]
  C2[Client B] --> LS
  LS -->|"hash of lock name"| E1[(Consensus cluster 1: 3 nodes)]
  LS --> E2[(Consensus cluster 2)]
  LS --> EN[(Cluster ...8)]
  C1 -- write + fencing token --> RES[(Protected resource)]
  RES -. rejects older tokens .-> C2

Why fencing tokens matter

Client A acquires the lock with token 33, then suffers a 10-second garbage collection pause. Its 5-second lease expires; client B acquires with token 34 and writes to the storage. A wakes up, still believing it holds the lock, and sends a write. Without fencing, A overwrites B's work. With fencing, the storage remembers the highest token it has seen (34) and rejects A's write carrying 33. The lock service alone cannot prevent this because A's pause happened outside its control.

Redis-based locks

SET lock:name <random-value> NX PX 5000 on a single Redis node is simple and fast, and release must use a script that deletes only if the value matches. It is fine when the lock is an efficiency optimisation (avoid doing the same work twice) and an occasional double holder is harmless. With asynchronous replication, a failover can lose the lock and grant it again. The multi-node Redlock algorithm is debated because it relies on timing assumptions and provides no fencing token; for correctness-critical locks, use a consensus store plus fencing.

Bottlenecks and trade-offs

  • The bottleneck is consensus write throughput and latency, shown in the estimate above; renewals are a large share of it, so longer leases with fencing reduce load.
  • Short TTLs release crashed holders quickly but risk expiry during long pauses; long TTLs are safer for the holder but delay recovery. Renew at about one third of the TTL.
  • Consensus stores give safety at the cost of write throughput and a few milliseconds per operation.
  • Often the best lock is no lock: partition work by key so only one worker owns each partition, or use database row locks and conditional updates where the data already lives.

By level

Fresher: Explain why a lock needs an expiry, what happens if a holder crashes, and that only one client should hold it at a time. A fresher should know that releasing someone else's lock is a bug.

Mid: Design acquire, renew and release on etcd or ZooKeeper with leases and fair waiting, and estimate consensus write load. Expect the consensus write estimate to set the cluster count.

Senior: Explain fencing tokens and the pause problem, critique Redlock, partition across clusters, discuss cross-region locks and recommend designs that avoid locks altogether. Expect the pause scenario to be explained with fencing token numbers.

Key points

  • Locks need leases so crashed holders release automatically
  • Use a consensus store (etcd, ZooKeeper) for correctness-critical locks
  • Fencing tokens let the resource reject stale holders after pauses
  • Consensus write throughput is the scaling limit; partition lock names across clusters
  • Single-node Redis locks suit efficiency locks, not safety-critical ones

Common mistakes

  • Assuming a lease guarantees the holder has not been paused past expiry
  • Releasing a lock without checking ownership
  • Using Redis with async replication for correctness-critical locks
  • Having all waiters watch the same key and wake together

Follow-ups

  • Walk through the GC-pause scenario with and without fencing
  • How would the storage system check fencing tokens?
  • How would you design a lock that spans two regions?

Tips

  • Separate safety from liveness in the requirements
  • Tell the pause story with concrete token numbers
  • Suggest avoiding locks through partitioning where possible

Evaluation rubric

  • Safety and liveness requirements explicit
  • Throughput estimate drives cluster count
  • Correct use of leases, consensus and fencing tokens
  • Balanced discussion of Redis locks and TTL trade-offs