Build a Read-Optimized Geo-Replicated Key-Value Database
System DesignModel answerLast updated
Design a multi-region key-value database tuned for heavy reads, covering storage engine, sharding, replication, consistency, failure handling, hotspots and capacity planning.
You are asked to design a key-value database that runs in several regions around the world and serves a workload dominated by reads. Clients need point lookups, writes, deletes and optional expiry on keys. Multi-key transactions are not required.
Begin by stating your own assumptions (data volume, read/write ratio, value sizes, latency and availability targets, number of regions). Then walk through the design, justifying each decision and naming its costs in performance, complexity and resources.
Cover these eight areas:
- Operating-system level performance: threading model (threads vs. async I/O), context-switch cost, memory management and filesystem tuning.
- Storage layout and indexing: the on-disk engine, compaction strategy and the write-amplification trade-off.
- Partitioning: how keys are distributed, how data is split across nodes, and how the cluster is rebalanced.
- Replication and caching: read and write paths, cache coherence, TTLs and invalidation.
- Consistency: the model you choose, CAP trade-offs and what guarantees a client actually sees.
- Failure handling: failure detection, isolating faults, leader election and recovery.
- Overload protection: hot keys, backpressure and rate limiting.
- Operations: capacity planning, SLAs/SLOs and observability.
Include a quick back-of-envelope sizing and explain which resource ends up being the bottleneck.
Hints
Hint 1
Start with explicit numbers (keys, bytes, QPS, replicas, regions) and compute both storage-bound and throughput-bound node counts; the larger of the two drives provisioning.
Hint 2
For a read-heavy load with modest writes, think about which engine and compaction style trade extra write cost for cheaper, more predictable reads.
Hint 3
Separate the intra-region story (quorum, strong guarantees) from the cross-region story (asynchronous, conflict resolution), since their latency budgets are very different.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Assumptions and sizing
- Workload: about 100:1 reads to writes; point get/put/delete with optional TTL; values average 1 KB, max 1 MB; no multi-key transactions.
- Scale: 10B keys (~10 TB logical), 2M reads/s and 20K writes/s globally, 3 regions.
- SLOs: in-region read p99 < 10 ms, write p99 < 20 ms, 99.99% availability per region, no loss of acknowledged writes if one availability zone (AZ) fails.
- Consistency: read-your-writes inside a region by default; cross-region replication is asynchronous with lag under about 1 s.
Sizing per region: 10 TB x 3 replicas = 30 TB. With 4 TB NVMe drives and ~50% headroom for compaction and rebalancing, usable space is ~2 TB per node, giving ~15 nodes for storage. Reads of ~700K/s per region at ~100K/s per warm node need only ~7 nodes. Storage is the binding constraint, so provision around 24 nodes per region, which also tolerates losing an AZ.
2. API and data model
get(key, consistency = ONE | LOCAL_QUORUM | STRONG) -> (value, version)
put(key, value, ttl?, if_version?) -> version
delete(key) -> version # writes a tombstone
Each record holds key, value, a hybrid-logical-clock version, expiry and a tombstone flag. The version powers cross-region last-writer-wins and optional compare-and-set.
3. Architecture
Client SDK -> L4 load balancer -> stateless routing tier (partition map plus hot-key cache) -> storage nodes. Each partition is a Raft group of 3 replicas, one per AZ. A small Raft-based metadata service owns membership, the partition map and leases. A replicator tails each partition log and ships it asynchronously to other regions.
4. Deep dives
OS-level performance. Use a thread-per-core, shard-per-core model with async I/O (io_uring or epoll). Thread-per-connection pays a few microseconds per context switch plus cache/TLB pollution at 10K+ connections. Pinning a partition to a core removes most locking; the price is that nothing may block in the event loop. Size the block cache explicitly, use O_DIRECT to avoid double caching, jemalloc against fragmentation, huge pages for the cache arena, and disable swap. On the filesystem use XFS/ext4 with noatime, a simple NVMe scheduler, preallocated WAL files and group commit so one fdatasync covers many writes. Put the WAL on a separate device if write latency matters.
Storage engine. An LSM tree gives cheap sequential writes; per-file bloom filters (~10 bits/key, ~1% false positives) and pinned index/filter blocks keep reads to roughly one disk touch. Choose leveled compaction: low read and space amplification at the cost of high write amplification (~10-30x). At 20K writes/s x 1 KB x 30 = ~600 MB/s region-wide, that is easily affordable on NVMe. Rate-limit compaction I/O so it never starves reads. Drop expired keys and tombstones in compaction only after a grace period longer than replication lag, otherwise deleted data can resurrect. Separate large values (> ~4 KB) from keys (WiscKey-style) to cut write amplification. A B-tree is the alternative with lower read cost variance but worse write behavior.
Partitioning. Hash keys (e.g. xxhash) into a fixed number of virtual partitions (say 4,096 per region) mapped to nodes. This spreads load evenly but sacrifices range scans; if scans are required, use range partitioning with automatic split/merge. Adding a node moves whole partitions (snapshot copy, then log catch-up), so only ~1/N of data moves. Throttle transfer bandwidth and split partitions that exceed ~10 GB or a QPS threshold.
Replication and caching. Write path: router -> partition leader -> WAL append -> Raft majority (2 of 3 AZs) -> ack -> asynchronous cross-region shipping. Synchronous cross-region writes would add 70-150 ms and break the write SLO. Read path: router hot-key cache (short TTL) -> node block cache -> SSTables. Leaders holding a lease serve linearizable reads without a quorum round trip; followers serve ONE reads. For coherence, version-tag cache entries, bound staleness with 1-5 s TTLs, invalidate from the partition change stream, and use lease-based fills to prevent thundering herds and stale sets.
Consistency and CAP. Inside a region each partition is CP: the minority side of a split refuses writes. Across regions the system is AP with last-writer-wins on hybrid logical clocks; optionally assign a "home region" per key for strong writes. Client guarantees: linearizable reads at leader cost, read-your-writes via session tokens carrying the last seen version, and eventual consistency elsewhere. Be explicit that LWW can drop concurrent updates.
Failure handling. Use heartbeats with a phi-accrual style detector, tuned to avoid flapping. Raft elects a new leader in about a second or two after a leader failure. Isolate faults with per-partition groups, bulkheads between tenants and cells, and health-checked routing. Recovery: a replacement replica restores from a snapshot and replays the log; the node rejoins serving only when caught up. Regional failure: reroute clients to another region, accepting a small window of lost async writes (bounded by replication lag) unless a key is homed elsewhere.
Hotspots, backpressure, rate limiting. Detect hot keys via sampled counters. Mitigate with router-level caching, replicating hot keys across more followers, and request coalescing. Apply bounded queues and load shedding at each tier, return explicit "retry later" with jittered backoff, and enforce per-tenant token-bucket quotas. Prioritize foreground traffic over compaction and rebalancing.
Capacity, SLOs, observability. Plan for peak plus an AZ loss (N+1 AZ), with disks under ~50% full. Track p50/p99/p999 latency per operation, error rate, replication lag, compaction backlog, cache hit ratio, per-partition QPS skew and Raft leader changes. Alert on SLO burn rate rather than raw thresholds; run chaos tests and canary rollouts.
Common mistakes
- Skipping numbers and never identifying the true bottleneck (here, storage).
- Proposing synchronous cross-region writes while promising low write latency.
- Ignoring tombstone grace periods and replication lag, causing data resurrection.
- Choosing consistency "levels" without stating what the client sees during a partition.
- Forgetting that rebalancing and compaction compete with foreground traffic.