Case Study 32 โ Distributed Coordination Service
Design a distributed coordination service like etcd, Apache ZooKeeper, or Google Chubby: strongly consistent metadata, distributed locks, leases, watches, and leader election built on consensus (Raft).
1. Problem
In a distributed system, nodes need a small, strongly consistent metadata store to:
- Elect a leader (only one scheduler, one primary writer)
- Hold configuration (service registry, feature flags, routing rules)
- Implement distributed locks with fencing
- Notify clients of changes via watches (push-ish notifications)
- Store ephemeral nodes that vanish when a session dies
Unlike a general database, the data set is small (MBโlow GB), read/write ratio varies, but linearizable reads/writes and valid watches are mandatory. CAP trade-off: choose CP โ partition tolerance + consistency; sacrifice availability during minority partition.
2. Requirements
Functional (MVP)
- Key-value store:
GET,PUT,DELETEon hierarchical keys (/services/payment/leader) - Linearizable writes and optional linearizable reads
- Ephemeral keys tied to session lease โ auto-delete on session expiry
- Watches: subscribe to key/prefix; receive events on change
- Distributed lock: acquire, release, optional fencing token
- Compare-and-swap (CAS):
PUT if version == X - Leader election: candidates compete via ephemeral sequential keys
- Session: heartbeat keeps lease alive; client gets session expired callback
Out of scope (initially)
- SQL queries, secondary indexes, full-text search
- Multi-key transactions spanning unrelated subtrees (MVP: single-key CAS)
- Geo-replicated active-active (single Raft cluster per cell)
- Petabyte storage โ this is coordination, not data lake
Non-functional
- Write throughput: 10K ops/s per cluster (typical etcd class)
- Read throughput: 100K+ ops/s with follower reads (bounded staleness option)
- Latency: p99 write < 10 ms LAN; watch notification < 100 ms
- Fault tolerance: survive
(N-1)/2failures with N=3 or N=5 nodes - Safety: never lose committed writes; never serve stale leader writes
- Liveness: elect new leader within seconds of leader failure
3. Back-of-the-envelope
These numbers are rough order-of-magnitude math โ not an etcd deployment guide. In interviews, the goal is to show you know what to count and which resource breaks first. A useful shortcut: 1 QPS sustained โ 86,400 requests/day (86,400 seconds in a day). Coordination services are write-light, read-heavy with occasional watch storms during config changes.
Why we estimate
A coordination service (etcd / ZooKeeper / Chubby) holds small, critical metadata โ not your product data. Estimates tell us:
- Whether Raft consensus or watch fan-out is the real bottleneck
- If linearizable reads on every GET are affordable or if follower reads are mandatory
- How much storage you actually need (usually tiny โ the surprise is network and CPU)
Assumptions
| Assumption | Value | Why it matters |
|---|---|---|
| Raft cluster size | 5 nodes | Survives 2 failures; typical production size |
| Connected clients | 2,000 | Each may hold watches and sessions |
| Peak write ops/s | 5,000 | Every write goes through Raft leader |
| Peak read ops/s | 50,000 | Most reads can use followers |
| Total keys | 500,000 | Service registry, locks, config โ stays small |
| Avg key+value size | 256 B | Coordination data, not blobs |
| Active watches | 10,000 | Clients waiting for key/prefix changes |
| Peak key changes/s | 1,000 | Drives watch notification volume |
Step A โ Traffic (QPS / throughput) with labeled arithmetic
Write throughput (consensus-bound):
Peak write QPS = 5,000 ops/second
Every write โ leader append โ replicate to 4 followers โ commit
This is the hard ceiling โ etcd-class systems target ~10K writes/s per cluster
Read throughput (can scale with followers):
Peak read QPS = 50,000 ops/second
If every read is linearizable (quorum read to leader + followers):
50K ร 3 network RTTs โ leader becomes read bottleneck
With follower reads + leader lease verification:
~95% of reads served locally โ leader load drops to ~2,500 reads/s
Watch notification rate:
Key changes/s = 1,000/s (peak, e.g. rolling deploy updates service registry)
Avg watchers/key โ 10
Notification events โ 1,000 ร 10 = 10,000 events/s push to clients
โ Must batch and coalesce prefix watches
Step B โ Storage
Key-value data (the actual metadata):
Total keys = 500,000
Bytes per key โ 256 B (key + value + version metadata)
KV storage = 500K ร 256 B โ 128 MB
(+ Raft log until snapshot โ still small at coordination scale)
Raft log (before compaction):
Write rate = 5,000 entries/s
Entry size โ 500 B (key, value, term, index)
Log append rate = 5,000 ร 500 B โ 2.5 MB/s
Snapshot every 10K entries โ compact old log; steady-state disk stays flat
Step C โ Bandwidth / other
Inter-node replication:
Leader โ 4 followers: 2.5 MB/s ร 2 (majority path) โ 5 MB/s replication bandwidth
Modest โ coordination is not a bandwidth problem
Leader election (rare but critical):
Leader failure โ election timeout 1โ2 s โ brief write unavailability
During partition: minority partition stops accepting writes (CP system)
Session heartbeats:
2,000 clients ร 1 heartbeat/5s โ 400 heartbeats/s
Keeps ephemeral keys alive; session expiry triggers delete + watch events
Step D โ Ratios and capacity table
| Metric | Value | Notes |
|---|---|---|
| Read:write ratio | 10:1 | 50K reads vs 5K writes at peak |
| KV storage | ~128 MB | Tiny โ this is not a data lake |
| Raft log append | ~2.5 MB/s | Consensus is the write bottleneck |
| Watch events/s | ~10,000/s | Batch + coalesce to avoid client overload |
| Replication bandwidth | ~5 MB/s | Modest between 5 nodes |
| Write p99 target | < 10 ms LAN | Dominated by Raft round-trip |
What the numbers tell us
- 128 MB of KV data is tiny โ coordination is about consistency and watches, not disk capacity
- 5K writes/s through one Raft leader is the write ceiling โ batch writes, avoid chatty lock renewals
- 50K reads/s requires follower reads โ linearizable quorum reads on every GET would crush the leader
- 10K watch events/s โ prefix watches + coalescing; naive per-key push doesn't scale
- CP, not AP โ during network partition, minority side stops writes rather than serve stale locks
- Leader election in 1โ2 s โ clients must retry; fencing tokens protect against stale lock holders
Common mistake for this problem
Treating a coordination service like a general-purpose database and storing large payloads or running analytics queries. Interviewers want you to see that consensus on a small log is the bottleneck โ keep values small, snapshot aggressively, and offer bounded-staleness follower reads instead of quorum reads on every GET. Another mistake: ignoring watch fan-out โ 1,000 key changes/s ร 10 watchers each is 10K push events/s.
4. High-Level Design (HLD)
Components
| Component | Role |
|---|---|
| Raft module | Leader election, log replication, snapshot |
| State machine (KV tree) | Apply committed log entries to in-memory tree |
| Session manager | Client leases, TTL, ephemeral key GC |
| Watch manager | Register watches; fan-out on apply |
| API server | gRPC/HTTP: get, put, delete, watch, lock helpers |
| WAL | Persistent log segments on each node |
| Snapshotter | Compact log; send InstallSnapshot to slow followers |
Flows
Linearizable write
- Client sends
PUTto any node; if not leader, redirect or forward - Leader assigns log index, appends to local WAL
- Replicate to followers via
AppendEntries; wait for majority ack - Commit entry; apply to state machine; respond to client
- Trigger watches for affected keys/prefixes
Session + ephemeral node
- Client
CreateSession(ttl=30s)โ receivessessionId - Client sends keep-alive every 10s; leader extends lease
- Client
PUT /workers/w1 EPHEMERAL session=sessionId - If keep-alive stops โ session expires โ delete all ephemeral keys โ watch events fire
Distributed lock (correct pattern)
- Create ephemeral sequential key
/locks/payment/lock-0000000123 - If lowest sequence among
/locks/payment/*โ hold lock - Else watch previous sequence key; wake on delete
- Return fencing token = sequence number for downstream resources
Watch
- Client registers watch on
/services/payment/(prefix) - On state machine apply of any key under prefix โ enqueue event
- Server streams event to client; client must ack/progress or watch may cancel on disconnect
Trade-offs
- Raft vs Paxos vs Zab โ Raft is easier to teach/implement; etcd/ZK use Raft-ish / Zab
- Linearizable read cost โ Quorum read or
ReadIndexfrom leader vs stale follower read - Watch on leader vs follower โ Follower watches lag one apply; leader watches add leader load
- Ephemeral via session vs TTL key โ Session model (ZK) vs lease per key (etcd)
- CP vs AP service discovery โ Coordination is CP; cache reads in clients with watch refresh
5. Low-Level Design (LLD)
APIs
PUT /v3/kv/put
Body: { "key": "base64...", "value": "base64...", "lease": 123, "prevKv": true }
โ { "header": { "revision": 88421 }, "prevKv": { ... } }
GET /v3/kv/range
Body: { "key": "...", "range_end": "...", "serializable": false }
โ { "kvs": [{ "key", "value", "create_revision", "mod_revision", "version" }] }
DELETE /v3/kv/deleterange
Body: { "key": "...", "range_end": "..." }
POST /v3/lease/grant
Body: { "TTL": 30, "ID": 0 }
โ { "ID": 123, "TTL": 30 }
POST /v3/lease/keepalive
Body: { "ID": 123 }
POST /v3/watch
Body: { "create_request": { "key": "...", "range_end": "...", "prefix": true } }
โ stream of { "events": [{ "type": "PUT|DELETE", "kv": { ... } }] }
POST /v3/lock/acquire
Body: { "name": "payment-processor" }
โ { "key": "/locks/payment-processor/000000042", "header": { "revision": 42 } }
Lock helper semantics (client-side recipe):
1. Grant lease
2. Create ephemeral sequential node under lock path
3. List children; if mine is smallest โ acquired
4. Else set watch on next smaller node; wait
5. On acquire, pass mod_revision as fencing token to DB/shard
Schema
Raft log entry (on disk):
LogEntry {
term: uint64,
index: uint64,
op_type: PUT | DELETE | CAS | SESSION_EXPIRE,
key: bytes,
value: bytes,
lease_id: uint64,
cas_version: uint64
}
State machine (in memory):
Node {
value: bytes,
create_revision: int64,
mod_revision: int64,
version: int64, // per-key change count for CAS
lease: uint64 | null
}
Tree = Map<path, Node> + revision counter (global monotonic)
Session {
id: uint64,
expiry: timestamp,
ephemeral_keys: Set<path>
}
WatchRegistration {
watch_id, client_stream, key_prefix, start_revision
}
Applied metadata:
-- Not SQL โ conceptual
revisions: global counter incremented each write
leases: id โ expiry heap for GC
watches: trie keyed by path prefix โ subscriber list
Modules
RaftNode
ElectionManager
LogReplicator
SnapshotManager
ApplyLoop
KVStateMachine
SessionLeaseManager
WatchManager
LockRecipeHelper
APIFrontEnd
LinearizableReadIndex
SerializableReadHandler
Algorithm โ Raft leader write path
function handlePut(key, value, lease):
if not isLeader(): redirect to leader
entry = LogEntry{ term, index=nextIndex(), PUT, key, value, lease }
wal.append(entry)
replicateToFollowers(entry.index)
waitUntilCommitIndex >= entry.index // majority ack
apply(entry) // state machine
notifyWatches(entry)
return success(mod_revision)
Algorithm โ apply to state machine
function apply(entry):
global revision++
switch entry.op_type:
PUT:
if entry.cas_version > 0:
if tree[entry.key].version != entry.cas_version:
return CAS_FAILED
tree[entry.key] = Node(value, revision, version++)
if entry.lease: attachLease(entry.key, entry.lease)
DELETE:
tree.delete(entry.key)
SESSION_EXPIRE:
for key in session.ephemeral_keys:
tree.delete(key)
enqueueWatch(DELETE, key)
Algorithm โ linearizable read (ReadIndex)
function linearizableGet(key):
if not isLeader(): forward
// Ensure this leader is still valid
readIndex = appendHeartbeatConfirmation() // quorum ack of commit index
if leaderTerm changed: retry
// Wait for state machine applied through readIndex
wait(appliedIndex >= readIndex)
return tree.get(key)
Algorithm โ watch delivery with revision
function registerWatch(prefix, startRevision, client):
watches.add({ prefix, startRevision, client })
function notifyWatches(entry):
affected = keysMatching(entry.key)
for watch in watches:
if entry.mod_revision > watch.startRevision and prefixMatch(watch.prefix, entry.key):
client.send({ type, key, value, mod_revision })
function catchUpWatch(watch):
// On reconnect: replay history from startRevision via log or MVCC store
for rev in (watch.startRevision, currentRevision]:
emit events from revision log
Algorithm โ distributed lock with fencing
function acquireLock(path, session):
myKey = createEphemeralSequential(path + "/lock-", session)
children = listChildren(path)
sort(children)
if myKey == children[0]:
token = getModRevision(myKey)
return ACQUIRED, token
prev = childBefore(myKey, children)
watch(prev)
return WAITING
function useResourceWithLock(db, token):
// CRITICAL: resource must reject stale lock holders
db.write("UPDATE shards SET owner=me WHERE fencing_token < ?", token)
Algorithm โ session keep-alive and expiry
function keepAliveLoop(sessionId):
every TTL/3:
send LeaseKeepAlive(sessionId)
function leaseGC():
while minHeap.peek().expiry < now:
session = minHeap.pop()
apply(SESSION_EXPIRE, session)
// deletes ephemeral keys atomically in apply
Concurrency & correctness
- All mutations through Raft โ single ordered apply loop per node
- At most one leader per term โ Raft safety proof
- Fencing tokens โ lock alone is insufficient; storage layer must validate token
- Watch ordering โ events per key ordered by revision; client tracks
startRevision - Split brain prevention โ old leader steps down when higher term seen
- Don't use lock for long work โ hold lock only to elect/assign, not for entire job
Failure modes
| Failure | Behavior | Mitigation |
|---|---|---|
| Leader dies | Writes pause until election | 3+ nodes; election timeout ~1s |
| Network partition (minority) | Minority stops accepting writes | CP โ minority unavailable |
| Slow follower | Log diverges | Snapshot + InstallSnapshot |
| Client session expires | Ephemeral keys deleted | Heartbeat + jitter |
| Watch flood | Leader CPU spike | Coalesce; watch on followers |
| Lock without fencing | Split-brain writes to DB | Require fencing token at resource |
| Stale leader read | Violates linearizability | ReadIndex or quorum read |
| Huge key space | Memory blowup | Not designed for this โ use real DB |
6. Scale evolution
| Stage | Change |
|---|---|
| MVP | 3-node Raft; single cluster; gRPC API |
| Read scale | Serializable follower reads + watch on followers |
| Multi-tenant | Key prefix quotas; rate limits per client cert |
| Many clusters | One etcd per AZ/cell; higher-level aggregator |
| Large watch count | Sharded watch managers; gRPC streaming backpressure |
| Cross-region | Separate Raft per region; async config replication (not one global Raft) |
7. Recap
- Built on consensus (Raft) โ committed log applied to KV state machine
- Sessions + ephemeral nodes enable crash detection and leader election recipes
- Watches turn poll into push; clients must handle gaps via revision
- Distributed locks need fencing โ the lock service alone doesn't prevent split brain
- Choose CP: consistent coordination beats availability during partition
Practice: draw Raft roles during normal operation and after leader failure; write pseudocode for lock acquire with sequential ephemeral keys and explain why fencing tokens matter.