A config service looks like a tiny database with a trivial job: store database.max_connections = 200, hand it back when asked. Then you remember who reads it. Every service in the fleet - thousands of processes - reads its runtime config from this one store, and they all expect that when an operator flips a feature flag or rotates a database endpoint, every dependent process learns the new value within milliseconds and acts on it, in agreement, without a restart. That is not a database. That is a coordination service, and coordination has two brutal constraints a database does not: the value has to be the same everywhere at the same logical instant (a split-brain config where half the fleet thinks the primary database is A and half thinks it is B is a production incident), and a change has to push to everyone watching, instantly, not get discovered on the next poll.
So the real system has two hard halves. The write/read half must be linearizable - a read must never return a value older than a write that already acknowledged, even if a leader just died. That is Raft (or Paxos), and the subtle part is that even reads need consensus-grade guarantees, which naively means a round trip through the log for every GET. The notification half must take one committed key change and fan it out to potentially millions of watch subscriptions sitting on long-lived connections, firing within a few milliseconds, without re-scanning every watcher on every write. etcd and ZooKeeper are exactly this system. Let me build it the way I would in an interview: requirements, sizing, architecture, then take the genuinely hard parts - Raft, linearizable reads without a log round trip, and millions of watches - from the naive version, break them, and evolve.
Functional Requirements (FR)
In scope:
- Key-value store with a hierarchical keyspace. Keys are paths (
/cluster/db/primary_host), values are small blobs. StandardPut,Get,Delete, andRange(prefix/range scan over/cluster/db/). - Strongly consistent reads and writes. A successful write is immediately visible to every subsequent read cluster-wide. No stale reads after an ack. This is the whole point.
- Atomic compare-and-swap (CAS) / transactions.
Put key=v if current_version == Nand small multi-key transactions (if A==x then put B=y, C=z), so clients can do leader election, locks, and safe config updates without races. - Watches. A client subscribes to a key or a prefix and is pushed every change (the new value, or a delete) from a given revision onward, over a long-lived connection, within milliseconds of commit. Watches survive reconnects by resuming from the last seen revision.
- Leases / ephemeral keys and TTLs. A key can be tied to a lease with a TTL that the client keeps alive with heartbeats; when the client dies and the lease expires, the key is auto-deleted. This is how you build “this node is the current leader” and “this node is alive” primitives.
- MVCC / revisioned history. Every mutation bumps a global monotonically increasing revision. Clients can read at a revision and watch from a revision, which is what makes reconnect-and-resume exact.
Explicitly out of scope (own the boundary so you control scope):
- Being a general-purpose database. Values are small (bytes to a few KB), the whole dataset fits in memory, total size is gigabytes not terabytes. No large blobs, no rows, no analytics, no secondary indexes beyond the key order. If someone wants to store a 5 MB file, the answer is “store it in object storage and put the URL here.”
- High write throughput. Writes go through consensus and are serialized through one leader; this is a low-write, high-read, high-watch system. Tens of thousands of writes/sec is a lot here, by design. If you need a million writes/sec, you want a different system.
- Cross-datacenter strong consistency on the hot path. One Raft group spans a small set of nodes with low inter-node latency (one region / a few close AZs). Global config distribution is done by read replicas and caching layers, not by stretching consensus across the WAN.
- Durability of ephemeral state. Leases are soft state rebuilt from client heartbeats; we do not promise lease liveness survives a full-cluster outage without re-registration.
The one decision that drives the whole design: this is a consensus system, not a storage system. The data is tiny and lives in RAM. The expensive, hard, interesting parts are agreement (every node sees the same ordered sequence of changes, even across leader failures) and propagation (a committed change reaches millions of watchers in milliseconds). Everything below follows from treating those two as the product.
Non-Functional Requirements (NFR)
- Consistency: linearizable for reads and writes. A read returns a value at least as fresh as the most recent committed write at the time the read was issued. CAS is atomic. This is the strongest consistency model and it is non-negotiable here - a config service that returns stale values defeats its purpose.
- Availability: tolerate a minority of node failures, not a majority. With a 5-node cluster we survive 2 failures and keep serving. During a partition, the majority side stays available and linearizable; the minority side refuses writes (and refuses linearizable reads) rather than serve stale or split-brain data. This is a deliberate CP choice: we pick consistency over availability, because a config store that lies is worse than one that is briefly unavailable.
- Durability: a committed write survives the loss of a minority of nodes. Every write is fsynced to the Raft log on a quorum of nodes before it is acknowledged. Losing the leader loses nothing committed.
- Read latency: single-digit milliseconds for linearizable reads from a cluster node; sub-millisecond from a local client-side cache that a watch keeps fresh. Most reads should never touch the cluster at all (see watches).
- Watch notification latency: a few milliseconds from commit to the change landing on the watcher’s connection, at p99. This is the headline number for the notification half.
- Scale: a dataset of up to ~1-2 GB (millions of small keys), ~10,000 writes/sec peak, ~100,000s of reads/sec (mostly served by caches/watches), and up to ~1 million concurrent watch streams across the fleet, each potentially watching a prefix. A single key update under a hot prefix may need to notify tens of thousands of watchers at once.
- Fault model: crash-stop and network partitions, not Byzantine. Nodes crash, pause (GC, VM stall), or get partitioned; they do not forge messages. Raft assumes non-Byzantine; that is fine for an internal cluster.
Back-of-the-Envelope Estimation (BoE)
The numbers justify why this is a coordination system and where the pressure actually is.
Dataset size:
Keys ~2,000,000 small config keys
Avg key path ~60 bytes
Avg value ~200 bytes
Avg MVCC/version overhead ~40 bytes (revision, create/mod rev, lease id)
Per key ~300 bytes
Total live dataset 2e6 * 300B ≈ 600 MB
With a few historical revisions retained (compacted) ≈ 1-2 GB
The entire keyspace fits in RAM on every node, several times over. There is no disk read path for serving GET; disk is only the Raft write-ahead log and periodic snapshots. This is the first proof that the hard part is not storage.
Write path (the serialized bottleneck):
Peak writes ~10,000 writes/sec
Every write = 1 Raft log entry, replicated to a quorum, fsynced.
On a 5-node cluster, each write costs:
leader fsync + 2 follower fsync-acks (quorum = 3) + 1 network RTT.
With fast NVMe fsync (~0.5 ms) and intra-region RTT (~0.5-1 ms):
write commit latency ≈ 1-3 ms p50, a few ms p99.
Throughput ceiling: batching many entries per fsync pushes a single
Raft group to ~tens of thousands of commits/sec. One group, one leader,
is the write ceiling. If you need more, you shard the keyspace into
multiple Raft groups (see Scaling) - not a bigger leader.
Read path:
Peak reads ~300,000 reads/sec cluster-wide
If every read were a linearizable read through Raft, that is 300K
consensus operations/sec - impossible on one leader.
Reality: the overwhelming majority of reads are served from a
client-side cache kept fresh by a WATCH. A process reads
`feature.x_enabled` once, watches it, and thereafter reads from local
memory in nanoseconds until a change is pushed. So the cluster sees
maybe a few thousand linearizable reads/sec (initial fetches,
explicit strong reads), not 300K. Watches convert reads into pushes.
Watch fan-out (the headline pressure):
Concurrent watch streams ~1,000,000 (one or more per process in the fleet)
Each stream watches a key or a prefix.
A single write to a HOT prefix (e.g. /features/ that 50,000 processes
all watch) must notify 50,000 watchers from ONE committed change.
At 10,000 writes/sec, with an average fan-out of (say) 100 watchers
per changed key, that is 10,000 * 100 = 1,000,000 notifications/sec,
with bursts far higher when a hot key changes.
This is the real scaling number: not writes, not storage, but
notification fan-out from a committed change to a million subscriptions.
Bandwidth:
A notification ≈ key + value + revision ≈ ~300 bytes on the wire.
1e6 notifications/sec * 300B ≈ 300 MB/sec ≈ ~2.4 Gbps at steady state,
spiking on a hot-key change. This is why watch fan-out is pushed to a
tier of stateless proxies, not served from the Raft leader directly.
Memory for watches:
Per watch stream we hold: connection state, the watched key/prefix,
last-sent revision, buffer. ~1-2 KB per watch.
1e6 watches * 1.5 KB ≈ 1.5 GB of watch state, spread across a fleet
of watch-serving proxies (say 50 proxies => 20K watches and ~30 MB each).
Never all on the leader.
The headline: the dataset is tiny (1-2 GB, in RAM), writes are modest and serialized through one Raft leader (tens of thousands/sec ceiling), reads are mostly free (served from watch-fed caches). The expensive, architecture-defining number is watch fan-out: one committed change notifying up to a million subscriptions within milliseconds. That, plus making linearizable reads cheap, is the entire design.
High-Level Design (HLD)
The spine: a small Raft cluster (3 or 5 nodes) that is the source of truth - it holds the replicated log, the in-memory MVCC keyspace, and elects one leader that serializes all writes. A tier of stateless watch/read proxies (the gRPC frontend) sits in front, holding the millions of long-lived client connections, serving cached reads, and fanning out watch notifications. Clients talk to proxies; proxies talk to the cluster. The leader streams committed changes to the proxies, which dispatch to watchers.
┌────────────────────────────────────────────────────────────┐
│ Fleet clients (thousands of processes, SDK with local cache)│
│ Put / Get / Txn / Watch(prefix) / Lease keepalive │
└───────────────┬──────────────────────────┬──────────────────┘
│ (long-lived gRPC streams) │
┌──────────▼───────────┐ ┌──────────▼───────────┐
│ Watch/Read Proxy │ │ Watch/Read Proxy │ ... (stateless,
│ - holds 20K streams │ │ - holds 20K streams │ horizontally
│ - serves cached reads│ │ - serves cached reads│ scaled, ~50)
│ - watch dispatch │ │ - watch dispatch │
└─────┬───────────▲─────┘ └─────┬───────────▲─────┘
writes & strong │ │ change stream │ │
reads forwarded │ │ (committed │ │
▼ │ revisions) ▼ │
┌──────────────────────┴────────────────────────────┴─────────┐
│ RAFT CLUSTER (3 or 5 nodes) │
│ ┌───────────────┐ ┌───────────────┐ ┌───────────────┐ │
│ │ LEADER │──▶│ Follower │ │ Follower │ │
│ │ - appends to │ │ - replicates │ │ - replicates │ │
│ │ Raft log │◀──│ log │ │ log │ │
│ │ - fsync + │ │ - fsync + ack │ │ - fsync + ack │ │
│ │ quorum ack │ └───────────────┘ └───────────────┘ │
│ │ - applies to │ │
│ │ MVCC store │ all nodes hold: │
│ └───────┬───────┘ - Raft WAL (on disk, fsynced) │
│ │ - in-memory MVCC keyspace (B-tree) │
│ apply committed - snapshots (periodic, on disk) │
│ entries -> store -> emit change to proxies │
└──────────────────────────────────────────────────────────────┘
Write flow (serialized, linearizable):
- A client calls
Put /cluster/db/primary = hostBon its proxy. The proxy forwards it to the leader (writes only ever go to the leader; followers redirect). - The leader assigns the next log index, appends the entry to its Raft log, and sends
AppendEntriesto all followers in parallel. - Each follower appends the entry to its own log, fsyncs it to disk, and acks. When the leader has acks from a quorum (including itself - 3 of 5), the entry is committed. Nothing is acknowledged to the client before quorum fsync, which is what makes it durable against a minority loss.
- The leader applies the committed entry to its in-memory MVCC store: it bumps the global revision, writes the new key version, and the write is now the authoritative current value.
- The leader acks the client (through the proxy) and emits the committed change (key, value, revision) onto the change stream that the proxies consume. This is the trigger for watch notifications.
Read flow (linearizable, but cheap):
- Most reads never leave the client: the SDK holds a local cache that a watch keeps fresh, so
Getis a memory lookup. The watch guarantees the cache is never behind a committed change by more than the notification latency, and the client can request a linearizable read when it needs a hard guarantee. - An explicit linearizable read goes to a cluster node. The node does not blindly return its local copy (a stale follower, or a leader that was just deposed, could lie). It confirms it is still the leader with a valid quorum (ReadIndex, deep dive 2), then returns the value at that committed revision. Single-digit ms, no log write.
- A client that accepts bounded staleness can do a serializable read straight from any follower’s local store - no quorum, sub-millisecond - trading freshness for latency when it is safe.
Watch flow (the fan-out half):
- A client calls
Watch(prefix=/features/, from_revision=R)on a proxy. The proxy registers the watch in its in-memory watch index (keyed by prefix) and, if the client is resuming, replays any changes betweenRand now from the MVCC history so no event is missed. - The leader streams every committed change to all proxies. Each proxy, on receiving a change for revision
r+1, looks up which of its local watchers’ prefixes match the changed key and pushes the event onto exactly those streams. - The watcher receives
(key, value, revision)within milliseconds and updates its local cache / acts on the new config.
The structural insight: the Raft cluster does agreement; the proxy tier does fan-out. The cluster stays small (consensus latency is dominated by the number of nodes, so you never make the cluster big) and never holds a million connections. The proxies are stateless, horizontally scalable, hold all the connections, absorb the read and watch load, and turn one change stream into a million notifications. Keeping those two concerns separate is what lets a 5-node consensus group serve a million watchers.
Component Deep Dive
The genuinely hard parts, naive-first then evolved: (1) Raft - replicating an ordered log and electing a leader so writes are consistent across failures; (2) linearizable reads without paying a log round trip per read; (3) millions of watches firing within milliseconds of a commit; (4) leases and ephemeral keys for leader election and liveness.
1. The replicated log and leader election (Raft)
The job: every node must apply the exact same sequence of writes in the exact same order, and a single leader must serialize writes, even as nodes crash and leaders change - with no split-brain where two leaders both accept writes.
Naive approach: a primary with async replication to backups
The obvious first cut: pick one node as primary, it takes all writes and streams them to backups asynchronously. If the primary dies, promote a backup.
Primary: write applied locally, ack client immediately
then async-replicate to backups (best effort)
Primary dies -> some tool promotes a backup to primary
Where it breaks:
- Acknowledged writes get lost. The primary acks a write, then dies before the async replication reaches any backup. The promoted backup has never seen that write. A config value you were told was saved silently reverts. For a config store, that is catastrophic - you rotated the DB password, got an ack, and the fleet is still using the old one.
- Split-brain under partition. The old primary is only partitioned, not dead. The failover tool promotes a backup. Now two primaries accept writes. Half the fleet reads from each.
/cluster/db/primaryhas two different values. This is the exact failure a config store exists to prevent. - Failover is a manual/external decision with no agreement. “Is the primary really dead or just slow?” has no principled answer here; whoever runs the promotion script decides, and two scripts can disagree.
Async primary-backup gives you neither durability of acked writes nor protection from two leaders. It is unusable for a linearizable store.
Evolved approach: Raft - quorum commit, terms, and election with a log-completeness constraint
Replace “ack then replicate” with “replicate to a quorum, then ack,” and replace “a tool promotes someone” with “nodes elect a leader by majority vote, and only a node with an up-to-date log can win.”
- Quorum commit for durability. A write is committed only when a majority of nodes have appended and fsynced it. On 5 nodes that is 3. Because any two majorities overlap in at least one node, any committed entry is present on at least one node of any future majority - so it can never be lost by a minority failure, and a new leader is guaranteed to have it.
- Terms and single-leader-per-term. Time is divided into terms, each with at most one leader. A leader is elected by receiving votes from a majority for its term. Because a node votes for only one candidate per term, two candidates cannot both get a majority in the same term - no two leaders in the same term. An old, partitioned leader is in an older term; the moment it contacts any node in the new term, it learns it is stale and steps down. That kills split-brain at the protocol level.
- Election with a log-completeness guard. When a follower’s election timeout fires (no heartbeat from a leader), it bumps the term and requests votes. A node grants its vote only if the candidate’s log is at least as up-to-date as its own (compare last log term, then index). This guarantees the winner has every committed entry - you can never elect a leader missing an acked write. Randomized election timeouts make split votes rare and self-correcting.
- Replication and conflict repair. The leader sends
AppendEntrieswith the previous entry’s index/term; a follower rejects if its log does not match there, and the leader walks back until they agree, then overwrites the follower’s divergent tail. Logs converge to the leader’s. Heartbeats are emptyAppendEntriesthat also carry the current commit index. - Apply to the state machine deterministically. Once committed, each node applies entries to its in-memory MVCC keyspace in log order. Same log + same starting state + deterministic apply = identical state on every node. The MVCC store is just a materialized view of the committed log.
- Snapshots and log compaction. The log cannot grow forever. Periodically each node snapshots its MVCC state and truncates the log before the snapshot. A follower that has fallen too far behind is caught up by shipping the snapshot, then resuming log replication.
Client Put ─▶ LEADER (term 7)
append @ index 42, term 7
AppendEntries(prev=41/7, [42]) ─▶ F1 fsync ack
─▶ F2 fsync ack (quorum of 3 incl leader)
index 42 COMMITTED ─▶ apply to MVCC (revision++) ─▶ ack client ─▶ emit change
Leader dies ─▶ followers time out ─▶ F1 (log up-to-date) requests votes, term 8
gets majority (its log has entry 42) ─▶ new leader, no committed entry lost
Old leader returns ─▶ sees term 8 > 7 ─▶ steps down. No split brain.
Why this is right: quorum-before-ack makes every acknowledged write durable against a minority failure; one-leader-per-term plus the vote rule makes split-brain impossible; the log-completeness vote guard means a new leader never misses a committed entry. That is exactly the linearizable, partition-safe foundation a config store needs, and it is why real systems (etcd, Consul, TiKV) use Raft rather than hand-rolled primary-backup.
2. Linearizable reads without a log round trip
The job: a Get must never return a value older than a write that already committed, even right after a leader change - but we cannot afford to push every read through the Raft log (300K reads/sec of consensus would melt the leader).
Naive approach A: just read the leader’s local memory
The leader has the latest state, right? So a read just returns the leader’s in-memory value for the key. Fast, no replication.
Where it breaks:
- A deposed leader does not know it is deposed. The leader got partitioned; a new leader was elected and has already committed newer writes. The old leader, still thinking it is leader, happily serves its stale local value. The client reads a config that is already two versions behind. Linearizability violated.
- The leader may not have applied the latest committed entry yet. Even a legitimate leader can be behind its own commit index on the apply step for a moment.
Reading local leader memory is fast and wrong - it is exactly the stale-read bug a config store must not have.
Naive approach B: write a no-op through the log for every read
To be safe, turn every read into a consensus operation: append a read marker to the log, wait for it to commit, then read. Now the read is ordered with respect to all writes and is provably linearizable.
Where it breaks:
- Every read costs a quorum fsync round trip. That is a disk write and network round trip per read. At hundreds of thousands of reads/sec it is utterly impossible - you have turned a read-heavy workload into a write-heavy one and saturated the leader and its disk.
- Reads now contend with writes on the single log. The read-heavy path throttles the write path. The whole cluster slows to the speed of fsync.
Correct but catastrophically slow. We need linearizable reads without writing to the log.
Evolved approach: ReadIndex (confirm leadership with a heartbeat quorum, then read after apply)
Decouple “prove I am still the leader and know the latest commit point” from “write to the log.” This is the ReadIndex protocol.
- Capture the commit index. When a linearizable read arrives, the leader records its current commit index
RI(the index of the latest committed entry it knows about). - Confirm leadership with a heartbeat round, not a log write. The leader sends a round of heartbeats and waits for acks from a majority. If a majority still follow it in the current term, it is provably the real leader right now (a deposed leader could not get a majority to ack its heartbeat in the current term). Crucially this is a lightweight network round trip, no disk fsync, no log entry.
- Wait until applied, then read. The leader waits until its state machine has applied up to index
RI, then serves the read from the in-memory store. The value is guaranteed to reflect every write committed at or before the read was issued. Linearizable, and the only cost is one heartbeat round trip amortized across many concurrent reads (one heartbeat round can clear a whole batch of pending reads). - Lease-based reads (a faster variant). If the leader holds a leader lease - a bounded time window within which it is guaranteed no other leader can have been elected (derived from election timeout and clock bounds) - it can skip even the heartbeat round and serve reads directly from local applied state for the duration of the lease. This trades a dependency on bounded clock drift for even lower latency. etcd supports both; ReadIndex is the safe default, lease reads the optimization.
- Follower reads, done safely. A follower can serve linearizable reads too: it asks the leader for the current ReadIndex, waits until its own apply has caught up to that index, then reads locally. This spreads read load off the leader while staying linearizable - the follower only serves once it has applied far enough.
- Serializable reads as an explicit opt-out. Clients that can tolerate bounded staleness request a serializable read, served from any node’s local state with no coordination, sub-millisecond. The config SDK uses linearizable reads for correctness-critical fetches (leader election, locks) and leans on watch-fed caches for everything else.
Linearizable Get:
leader records RI = commitIndex
leader sends heartbeat ─▶ majority ack (still leader, this term) [no fsync]
leader waits until appliedIndex >= RI
return value from in-memory MVCC store (single-digit ms, batchable)
Lease variant: within valid leader lease, skip heartbeat, read local applied state.
Follower read: ask leader for RI, wait own appliedIndex >= RI, read locally.
Why this is right: ReadIndex gives full linearizability (no stale read, even across a just-happened leader change, because a deposed leader cannot win the heartbeat quorum) while paying only a network round trip, not a disk write - and that round trip batches across all concurrent reads. It is the difference between a config store that can serve reads at scale and one whose reads are as expensive as writes. This exact mechanism is why etcd can offer linearizable reads cheaply.
3. Millions of watches firing within milliseconds
The job: one committed key change must be delivered to every watcher of that key or a matching prefix - potentially tens of thousands of them for a hot prefix - within a few milliseconds, with up to a million watch streams total, and resumable exactly after a reconnect.
Naive approach: clients poll the store on an interval
The first cut: no push at all. Each client polls Get(key) every, say, second to see if the value changed.
Where it breaks:
- Latency is the poll interval, not milliseconds. A change takes up to a full interval to be noticed. Shorten the interval to get closer to real-time and you multiply load linearly.
- Load is catastrophic and constant. One million clients polling once a second is one million reads/sec whether or not anything changed. The cluster spends all its capacity answering “nope, still the same.” To get millisecond freshness you would need ~1000 polls/sec each - a billion reads/sec. Absurd.
- No exactness. Between two polls a key could change twice; the client sees only the final state and misses intermediate events (a problem if it is watching for a specific transition).
Polling makes freshness and load fundamentally trade off against each other, and both are unacceptable at this scale.
Naive approach B: push, but the leader scans every watcher on every write
So push instead. Keep all watch registrations and, on each committed change, walk the full list of watchers, check each one’s key/prefix against the changed key, and send to matches.
Where it breaks:
- O(writes * watchers) work. At 10,000 writes/sec and 1,000,000 watchers, that is 10^10 match checks/sec. The leader cannot do it; it would do nothing else.
- The leader holds a million connections. The small consensus node is now also a connection server for the entire fleet, with gigabytes of connection state and all the fan-out bandwidth funneling through it. It falls over, and taking down the leader stalls writes too.
- No efficient matching. A linear scan to find which watchers match
/features/xignores the structure of the keyspace entirely.
Pushing is right; doing the fan-out on the leader with a linear scan is not.
Evolved approach: a stateless proxy tier, an interval-tree watch index, and revision-based resume
Move all watch state and fan-out to a horizontally scaled proxy tier, index watchers so matching is logarithmic not linear, and use MVCC revisions to make reconnects exact and lossless.
- Watches live on stateless watch proxies, not the leader. Clients connect to one of ~50 proxies. Each proxy holds its share of the million streams (~20K each) and the watch registrations for them. The leader’s only job is to stream the ordered sequence of committed changes to the proxies - one fan-out to ~50 proxies, not to a million clients. The proxies do the million-way dispatch. This is the single most important move: consensus stays on a tiny cluster, fan-out scales out on stateless nodes.
- An efficient per-proxy watch index. Each proxy indexes its local watchers for fast “which watchers match this changed key.” For single-key watches, a hash map
key -> [watchers]. For prefix/range watches, an interval tree (or a radix/trie over key prefixes) so a changed keykfinds all watchers whose prefix coverskin O(log n + m) where m is the number of matches, not O(all watchers). A hot change to/features/xdirectly yields its matching watcher set without scanning unrelated watchers. - The change stream carries ordered, revisioned events. The leader emits every committed mutation as
(key, value, revision)in revision order. Proxies receive this stream (fanned out through the followers too, to spread bandwidth) and, for each event, look up matching local watchers and push. Because events are globally ordered by revision, every watcher sees changes in commit order. - Revision-based resume makes reconnects exact. Every watch is anchored to a revision. A client watching from revision
Rthat disconnects and reconnects re-issuesWatch(prefix, from_revision=last_seen+1). The proxy serves any missed events from the MVCC history (the store keeps recent revisions until compaction) before switching to the live stream. No event is lost, none duplicated out of order - the revision is the cursor. This is what makes watches a reliable change-data-capture feed, not a best-effort push. - Coalescing and backpressure for hot keys and slow watchers. If a key changes rapidly, a slow watcher does not need every intermediate value - the proxy can coalesce to the latest value per key for that watcher (config semantics care about the current value, not every transition). Each stream has a bounded send buffer; a watcher that cannot keep up is either coalesced or, past a limit, disconnected and told to re-sync from its last revision (better to force a clean re-sync than to let one slow consumer balloon memory). Fan-out to tens of thousands of watchers of a hot prefix is parallelized across the proxy’s worker pool.
- Compaction bounds history. Old revisions are compacted on a schedule (keep, say, the last N revisions or last hour). A watcher that tries to resume from a revision older than the compaction point gets a “compacted” error and must do a fresh
Get+ re-watch from current - a deliberate bound so history does not grow without limit.
Leader commits change @rev=8125 (/features/x = on)
└─▶ ordered change stream ─▶ all ~50 proxies
Proxy P (holds 20K watchers):
interval-tree lookup: which local watchers' prefix covers /features/x ?
-> {w12, w88, ... w40000} (O(log n + m), not a full scan)
push (key,value,rev=8125) to exactly those streams (parallel workers)
slow watcher? coalesce to latest-per-key or disconnect -> client re-syncs from last rev
Client reconnects: Watch(prefix=/features/, from_revision=8120)
proxy replays 8121..current from MVCC history, then joins live stream. No gaps.
Why this is right: offloading watches to a stateless proxy tier keeps the Raft cluster small while letting fan-out scale horizontally to a million streams; the interval-tree/trie index turns per-change matching from O(all watchers) into O(log n + matches); revision anchoring makes reconnects lossless and ordered, which is what turns “push notifications” into a dependable config-change feed; and coalescing plus backpressure stop a hot key or a slow consumer from taking the tier down. The leader fans out to 50 proxies; the proxies fan out to a million clients. That decomposition is the whole trick.
4. Leases, ephemeral keys, and leader election for clients
The job: let clients build “I am the current leader of subsystem X” and “node N is alive” on top of the store - keys that automatically disappear when the owning client dies - which requires the store to track client liveness and expire keys safely under consensus.
Naive approach: clients set a TTL on a key and whoever writes last wins
First cut: a client that wants to be leader does Put /svc/leader = me with ttl=10s and re-puts it every few seconds to refresh. If it dies, the TTL expires and the key is gone; someone else grabs it.
Where it breaks:
- Races on acquisition. Two clients
Put /svc/leadernearly simultaneously; last write wins, both think they might be leader, or they flap. There is no atomic “create only if absent.” - TTL expiry is not coordinated. If each node expires the key on its own local clock, different nodes disagree about whether the lease is still valid at a given instant - a split-brain on who holds the lock. Expiry must be a committed, ordered event, not a local timer.
- One TTL per key is wasteful. A client holding 1,000 ephemeral keys would send 1,000 separate refreshes. Liveness tracking should be per-client, not per-key.
Per-key local TTLs give you neither atomic acquisition nor a single coordinated notion of “this client is alive.”
Evolved approach: leases as first-class objects, CAS-based election, expiry through the log
Make a lease a first-class server object with its own TTL and keepalive, attach many keys to one lease, and drive both acquisition and expiry through consensus so every node agrees.
- Lease objects with a single keepalive. A client creates a
Lease(ttl=10s)and gets alease_id. It attaches ephemeral keys to that lease. It sends oneLeaseKeepAliveheartbeat per interval for the whole lease, not per key. The leader tracks each lease’s expiry deadline. - Expiry is a committed operation. When a lease’s deadline passes (tracked by the leader, whose clock is the single reference), the leader proposes a
LeaseRevokeentry through the Raft log. Only when that entry commits do all nodes delete the lease’s attached keys, in order, at the same log position. Every node agrees on exactly when the keys vanished, and that deletion is itself a watch event - watchers of/svc/leaderare notified the leader slot is now empty. Expiry being an ordered log entry (not a local timer on each node) is what makes it split-brain-free. - Atomic election via a mini-transaction. Leader election is a CAS:
Txn: if create_revision(/svc/leader) == 0 then Put /svc/leader = me (attached to my lease) else Get /svc/leader. The “create only if the key does not exist” is atomic under consensus, so exactly one client wins. The winner’s key is tied to its lease; if the winner dies, lease expiry deletes the key and a watcher is instantly notified to run a new election. This is the canonical etcd/ZooKeeper leader-election recipe. - Fencing tokens prevent stale-leader action. The elected leader gets the key’s revision as a monotonic fencing token. When it acts on a shared resource, it presents the token; the resource rejects any token lower than the highest it has seen. So even if a paused old leader wakes up after its lease expired and thinks it is still leader, its stale (lower) token is rejected. This closes the “zombie leader” gap that liveness alone cannot.
- Keepalive load stays bounded. One heartbeat per lease per interval, and a client with many ephemeral keys still sends one. The leader processes keepalives cheaply (refresh a deadline in memory); only acquisition, revoke, and real config writes go through the log.
Client A: lease = CreateLease(ttl=10s) -> lease_id=L1
Txn: if create_rev(/svc/leader)==0
then Put /svc/leader="A" lease=L1 -> A is leader, token=rev 5012
every 3s: LeaseKeepAlive(L1) (one heartbeat, refreshes deadline)
A crashes -> no keepalive -> deadline passes
leader proposes LeaseRevoke(L1) through Raft log -> commits
-> /svc/leader deleted on every node at that log index
-> watchers of /svc/leader notified "deleted" -> B runs the election Txn, wins, token=5090
A wakes up, acts with token 5012 -> resource has seen 5090 -> REJECTED (fencing)
Why this is right: a lease as a first-class object with one keepalive makes liveness per-client and cheap; driving expiry and acquisition through the Raft log means every node agrees on exactly when a lease died and who holds a lock, with no local-clock split-brain; the CAS election gives exactly-one-winner atomically; and fencing tokens defend against a zombie leader that liveness alone cannot catch. Together these turn the KV store into a correct coordination primitive - which is the entire reason a config service doubles as a lock/election service.
API Design & Data Schema
API
The API is gRPC (long-lived streams for watch and keepalive); shown here in a readable form.
Key-value operations:
Put(key, value, lease_id?, prev_version?) -> { revision, prev_kv? }
prev_version set => CAS: fails with 409 if current version != prev_version
Get(key, revision?, serializable?) -> { kv{ key, value, create_rev, mod_rev, version, lease }, revision }
revision set => read historical value at that revision (MVCC)
serializable => read from local node, no quorum (bounded-stale, fast)
default => linearizable read (ReadIndex)
Delete(key, prev_version?) -> { revision, deleted_count }
Range(prefix | [start,end), limit?, revision?, serializable?)
-> { kvs[...], more, count, revision } // prefix/range scan over the keyspace
Transactions (the primitive that makes CAS and election work):
Txn(
compare: [ { target: VERSION|VALUE|CREATE_REV|MOD_REV, key, op: ==|!=|<|>, value } ],
success: [ Put|Delete|Get ... ], // applied atomically iff all compares pass
failure: [ Put|Delete|Get ... ] // applied atomically otherwise
) -> { succeeded: bool, responses[...], revision }
Watch (long-lived server stream):
Watch(key | prefix | [start,end), start_revision?, prev_kv?, progress_notify?)
-> stream of WatchResponse {
events: [ { type: PUT|DELETE, kv{ key, value, mod_rev, version }, prev_kv? } ],
revision, // the store revision this batch reflects
compacted?: bool, // true => start_revision was compacted, must re-sync
canceled?: bool
}
start_revision => resume exactly from that revision (missed events replayed from history)
progress_notify => periodic "nothing changed, we are at revision R" keepalive
Lease / ephemeral keys:
LeaseGrant(ttl) -> { lease_id, ttl }
LeaseKeepAlive(lease_id) -> stream { lease_id, ttl } // one heartbeat refreshes all attached keys
LeaseRevoke(lease_id) -> {} // explicit release, deletes attached keys
LeaseTimeToLive(lease_id, keys?) -> { ttl, granted_ttl, attached_keys[...] }
Maintenance:
Compact(revision) -> {} // drop history before revision (bounds disk/memory)
Snapshot() -> stream (backup of the keyspace)
MemberList() / MemberAdd() / MemberRemove() // cluster reconfiguration
Status() -> { leader, raft_term, raft_index, db_size, ... }
Data model and storage
This is NOT a SQL vs NoSQL question in the usual sense - it is a custom in-memory MVCC store backed by a Raft log. There is no external database. Here is why and what the internal structures are.
The store is custom because the requirements are unusual: tiny dataset, must be fully in RAM, must be an exact deterministic state machine over a replicated log, must support linearizable reads, revisioned history, prefix watches, and leases. No off-the-shelf SQL or NoSQL engine gives you “deterministic state machine replicated by Raft with revisioned watch streams.” So you build the state machine and persist only the log and snapshots.
1. The Raft log (on disk, write-ahead, fsynced). The source of truth. Append-only sequence of committed (and in-flight) entries. Fsynced on a quorum before ack. Truncated behind snapshots.
WAL entry:
log_index uint64 (Raft log position, monotonic)
term uint64 (Raft term)
type enum (PUT | DELETE | TXN | LEASE_GRANT | LEASE_REVOKE | CONF_CHANGE)
payload bytes (the mutation)
crc uint32
Persisted append-only; fsync before quorum ack; compacted behind snapshots.
2. The in-memory MVCC keyspace (the applied state). A persistent/ordered structure (B-tree) keyed by key for range scans, plus a secondary index from revision to key for history and watch replay. Every mutation bumps the global revision.
Logical key record (in RAM, materialized from the log):
key string (e.g. /cluster/db/primary_host)
value bytes
create_rev int64 (revision at first creation; 0 => does not exist, used by CAS)
mod_rev int64 (revision of last modification)
version int64 (number of writes since creation; used by CAS)
lease_id int64 | null (ephemeral if attached to a lease)
Global: current_revision int64 (bumped on every mutation; the linearization point)
Index A (B-tree): key -> current key record // Get, Range, prefix scan
Index B: revision -> (key, record) // read-at-revision, watch replay
3. Snapshots (on disk, periodic). A point-in-time serialization of the MVCC state at a given log index, so the log can be truncated and a lagging/new node can be bootstrapped quickly.
Snapshot: { last_included_index, last_included_term, serialized_keyspace, lease_table }
4. Lease table (in RAM, part of the state machine). Tracks each lease’s TTL, deadline, and attached keys. Expiry proposes a LEASE_REVOKE through the log.
lease_id -> { granted_ttl, deadline (leader-tracked), attached_keys: set<string> }
5. Watch index (in RAM, on each proxy - NOT in the Raft state machine). Per-proxy, rebuilt from live connections, never persisted; it is soft state.
single-key watches: key -> set<watch_stream, from_revision> (hash map)
prefix/range watches: interval tree / radix trie over key ranges -> set<watch_stream>
lookup(changed_key) -> all matching watch streams in O(log n + matches)
Why these choices, stated plainly: the dataset is tiny and must be a deterministic replicated state machine, so it lives in RAM as a custom MVCC store, not in any external DB - an external database would break determinism and add a second consistency problem. Durability is provided by the Raft WAL on disk (fsynced) plus periodic snapshots, which is strictly simpler and faster than fronting a general database. MVCC revisions are not a luxury: they are what make read-at-revision, watch-from-revision resume, and CAS via create_rev/version exact. The watch index is deliberately not part of the replicated state - it is per-proxy soft state rebuilt from connections, because replicating a million ephemeral subscriptions through consensus would be absurd. SQL/NoSQL does not enter the hot path at all; the design is “replicated log + in-memory state machine,” which is the defining shape of etcd and ZooKeeper.
Bottlenecks & Scaling
Where it breaks first, in order, and the fix for each.
1. Watch fan-out from a hot key (breaks first, worst). One change to a popular prefix must notify tens of thousands of watchers in milliseconds; doing it on the leader is O(writes * watchers). Fix: a stateless watch-proxy tier (the leader fans out to ~50 proxies, proxies fan out to a million clients); a per-proxy interval-tree/trie watch index so matching is O(log n + matches) not a full scan; parallel dispatch across worker pools; coalescing to latest-per-key for slow watchers; backpressure that disconnects a hopelessly slow stream and makes it re-sync from its last revision rather than ballooning memory.
2. The write ceiling of one Raft group. All writes serialize through one leader and one fsynced log; a single group tops out at tens of thousands of commits/sec.
Fix: batch many mutations per fsync/round trip (the biggest single-group win), and when one group is genuinely not enough, shard the keyspace into multiple independent Raft groups (range or prefix partitioned - e.g. /features/* in one group, /services/* in another), each with its own leader. Shard key = key prefix / key range, chosen so related keys that need a cross-key transaction land in the same group (cross-group transactions are expensive and avoided). This is the etcd-at-scale / TiKV multi-raft approach.
3. Linearizable read load on the leader. Naive linearizable reads concentrate on the leader; at hundreds of thousands/sec it saturates. Fix: ReadIndex so reads cost a heartbeat round trip, not a log write, and batch many pending reads behind one heartbeat; follower reads (follower asks leader for ReadIndex, waits for its own apply, reads locally) to spread read load; serializable reads from any node for clients that accept bounded staleness; and above all, watches feed client-side caches so the vast majority of reads never reach the cluster at all.
4. The leader as a bandwidth / connection bottleneck. A million long-lived connections and gigabits of notification traffic cannot sit on a consensus node. Fix: clients connect only to proxies; the leader streams the change feed to a small set of proxies (and can relay through followers to spread egress). The consensus cluster never holds client connections and never serves the fan-out bandwidth.
5. History growth from MVCC. Every mutation creates a new revision; unbounded, the log and memory grow forever.
Fix: periodic compaction (Compact(revision)) drops history older than a bound (last N revisions or last hour), plus snapshot + log truncation. A watcher resuming from a compacted revision gets a compacted error and does a fresh Get + re-watch - a deliberate bound on history.
6. Slow or stuck watchers and reconnect storms. A mass reconnect (proxy restart, network blip) makes a million clients re-watch and replay history at once. Fix: revision-anchored resume means each client replays only its own missed range, not the whole keyspace; bounded per-stream buffers and coalescing cap memory; spread clients across many proxies so one proxy restart re-homes only its share; jittered reconnect in the SDK to avoid a synchronized thundering herd.
7. Cluster size vs latency. Making the Raft cluster bigger to “scale” actually slows writes (more nodes to reach quorum) and does not add read/watch capacity. Fix: keep the voting cluster small (3 or 5). Add non-voting learners for read offload and for safely bootstrapping new members. Scale reads/watches on the stateless proxy tier, scale writes by sharding into more Raft groups - never by adding voters.
8. Leader as a single point of failure. The leader serializes all writes; its loss must not lose data or stall long. Fix: Raft re-elects a log-complete leader from the surviving majority in ~one election timeout (sub-second with tuned timeouts); no committed write is lost (quorum durability); proxies transparently redirect writes to the new leader. Run an odd number of nodes across separate AZs so one AZ loss keeps a quorum.
9. Hot shard / hot key on write. One key (or prefix) taking a disproportionate write rate concentrates load on one group’s leader. Fix: for genuinely hot config writes, place the hot prefix in its own Raft group so it does not throttle others; for read/watch hotness the proxy tier and caches absorb it. Never shard by something like timestamp - config keys shard naturally by prefix, which also keeps related keys co-located for transactions.
10. Partition behavior (CP, by choice). Under a partition, the minority side must not serve stale or split-brain data. Fix: the majority side stays available and linearizable; the minority side refuses writes and linearizable reads (it cannot reach quorum / confirm leadership) and returns an error, optionally offering an explicit stale serializable read if the client opts in. We pick consistency over availability - a config store that returns a value must be able to stand behind it.
Shard keys and placement, stated plainly: keyspace sharded across Raft groups by key prefix / range (related keys co-located so transactions stay within one group); within a group, writes serialize through that group’s leader; watches sharded across proxies by client connection (soft, rebalanced on proxy churn); the watch index keyed by watched key/prefix; reads served by ReadIndex on leader, follower reads, or serializable local reads. Cluster stays small (3/5 voters + learners); proxies and groups scale out.
Wrap-Up
The trade-offs that define this design:
- Consistency over availability (CP), on purpose. We serialize writes through a Raft leader and refuse service on a partitioned minority rather than ever return a split-brain config. A config store that lies is worse than one that is briefly unavailable, so we pay availability for linearizability.
- Consensus cluster small, fan-out tier large. The Raft group stays at 3 or 5 nodes (bigger = slower writes, not more capacity) and never holds client connections. A stateless proxy tier holds the million watch streams and does the million-way fan-out. Separating agreement from propagation is what lets a tiny cluster serve a huge fleet.
- Linearizable reads without a log write. ReadIndex confirms leadership with a heartbeat quorum and reads from applied state, so linearizable reads cost a network round trip (batchable), not an fsync - the difference between serving reads at scale and not. Watches feed client caches so most reads never hit the cluster.
- Watches are a revisioned change feed, not best-effort push. MVCC revisions make watches resumable exactly after a reconnect (replay the missed range, no gaps, in order), an interval-tree index makes per-change matching logarithmic, and coalescing + backpressure keep a hot key or slow consumer from melting the tier.
- The KV store doubles as a coordination primitive. Leases with a single keepalive, CAS-based election, expiry committed through the log (not local timers), and fencing tokens turn plain keys into correct distributed locks and leader election - which is the real reason teams run a config service instead of a database.
One-line summary: a small Raft cluster that replicates an ordered log and serves an in-memory MVCC keyspace with linearizable ReadIndex reads and lease-based ephemeral keys, fronted by a stateless proxy tier that holds millions of revision-anchored watch streams and fans one committed change out to tens of thousands of watchers in milliseconds - a strongly-consistent, partition-safe config store and coordination service in the shape of etcd and ZooKeeper.
Comments