Design a Distributed Key-Value Store: CAP Theorem, Quorum, Vector Clocks & LSM Trees
Inside Dynamo-Style Distributed Key-Value Stores
Distributed Key-Value Store Architecture
1. CAP & PACELC Trade-Offs
- CP (Consistency + Partition Tolerance): Reject writes or stale reads on the minority side of a partition (e.g., etcd, ZooKeeper, HBase).
- AP (Availability + Partition Tolerance): Allow both sides to keep serving reads/writes, reconciling conflicts afterward (e.g., Cassandra, Dynamo).
2. Partitioning & Tunable Quorum Consistency
The Quorum Formula: $W + R > N$
- $N$: Replication factor (typically
3). - $W$: Write quorum (nodes that must confirm a write).
- $R$: Read quorum (nodes queried for a read).
| Configuration ($N=3$) | Behavior | Ideal Workload |
|---|---|---|
| $W=1, R=3$ | Ultra-fast writes, slower strong reads | Telemetry, event ingestion |
| $W=3, R=1$ | Ultra-fast reads, strict durable writes | Read-heavy configuration lookups |
| $W=2, R=2$ | Balanced strong consistency ($2+2 > 3$) | General-purpose primary KV data |
3. Conflict Resolution with Vector Clocks
LWW / Last-Write-Wins) lose updates due to NTP clock drift.[Node, Counter] to each object:[S1: 1, S2: 1]is strictly newer than[S1: 1](safe overwrite).[S1: 2, S2: 1]vs.[S1: 1, S2: 2]have diverged concurrently (neither dominates). Both siblings are stored and returned to the client for domain-specific reconciliation (e.g., merging a user's shopping cart union).
4. Failure Detection & Anti-Entropy
- Decentralized Gossip Protocol: Every second, nodes exchange heartbeat counters with a few random peers. If a node's heartbeat stops advancing for
T_failseconds across peers, it is marked down without needing a centralized coordinator. - Hinted Handoff: During temporary outages, a neighbor node buffers writes with a header hint and replays them once the failed node recovers.
- Merkle Trees: For permanent replica divergence, nodes exchange cryptographic hash trees over key ranges, pinpointing mismatched keys in $O(\log K)$ without transferring entire databases.
5. High-Speed Storage Engine: LSM Trees
- Commit Log (WAL): Append write sequentially to disk immediately for crash durability.
- MemTable: Insert sorted key-value into in-memory skip list / balanced tree.
- SSTables: When MemTable hits threshold (e.g., 64 MB), flush immutably to disk as sorted files, paired with in-memory Bloom Filters so missing keys never touch disk.
- Compaction: Background threads merge SSTables and discard tombstones/overwrites.