Design a Distributed KV Cache at Massive Scale
Whiteboard a 100M-DAU distributed cache from clarifying questions to consistent hashing, single-flight stampede defense, replication, and chaos testing.
1. Clarifying questions (Minutes 0–5)
Never jump straight into boxes and arrows. Spend the first five minutes narrowing the problem space so every design choice has a reason behind it:
- Read/write mix: Are we mostly serving reads (95/5, like user profiles, feature vectors, or inference metadata) or heavy writes?
- Latency SLO: Sub-5 ms p99 inside the region?
- Consistency vs availability: Is stale data for a few hundred milliseconds acceptable during a partition? For a cache, availability and tail latency almost always win (AP over CP).
- Value size & eviction: Typical payloads ~1 KB (capped at e.g. 1 MB)? Eviction policy LRU or TinyLFU + explicit TTL?
- Persistence: Purely ephemeral (DB is source of truth) or durable across restarts?
2. Back-of-envelope sizing (Minutes 5–10)
Adjust the sliders to test how hit ratio, replication factor, and value size shift whether the cluster is memory-bound or throughput-bound. Watch what happens to database fallthrough QPS when hit ratio drops from 95% to 80%.
3. API & data model
Keep the contract narrow so clients and proxies stay simple:
GET /v1/kv/{key} -> 200 value | 404 miss
PUT /v1/kv/{key} { value, ttl } -> 200 ok
DELETE /v1/kv/{key} -> 200 okInside each cache shard, a hash table + doubly linked list gives O(1) lookup, O(1) touch-to-head on read, and O(1) eviction from the tail when RAM hits the high-water mark. In practice, slab allocation (Memcached) or approximate sampled LRU / LFU (Redis) avoids heap fragmentation and lock contention.
4. Interactive whiteboard & chaos sandbox
Step through stages 1 to 5 to rehearse the 45-minute whiteboard build-up. Then flip the Chaos Injection switches—kill Shard B, fire a 10x hot key, or expire a hot TTL—and toggle defenses to see how the architecture responds.
5. Deep dive A: Sharding without melting the DB
A single machine holds ~100 GB RAM and serves ~100K ops/sec. To hold terabytes and millions of QPS, we shard keys across nodes.
If you partition with hash(key) % N, adding or removing a single machine changes N, remapping roughly (N−1)/N of all keys at once. Your cache effectively goes cold overnight and the database falls over.
Consistent hashing with virtual nodes solves both remapping and load skew. Switch VNODES / NODE between 1 and 32 below, and compare Add Node vs Kill Node:
6. Deep dive B: Cache stampede (thundering herd)
Suppose a celebrity profile or shared prompt-prefix key expires at t = 0. Within 10 milliseconds, thousands of requests miss simultaneously and all hit the database for the exact same value.
Compare Naive vs Single-Flight below:
Three defenses work together in production:
- Single-flight request coalescing: Only one caller fetches from the DB per missing key; concurrent callers await the same promise/future.
- TTL jitter: Add random jitter (
ttl + rand(0, 10%)) so keys written together do not expire together. - Probabilistic early refresh / stale-while-revalidate: Serve the slightly stale value while one background worker refreshes it.
7. Failure modes & trade-offs
| Failure / Tension | Trade-off & Mitigation |
|---|---|
| Hot key (10x–100x single key) | Consistent hashing still sends one key to one shard. Mitigate with an in-process L1 cache (short TTL, e.g. 5s) on app servers or key salting (key#0..key#k) for read-only hot items. |
| Shard crash | Async replication (RF=2 across AZs) lets the router promote a warm replica immediately instead of sending 1/N of traffic to the DB. |
| Cache-aside vs Write-through | Cache-aside only caches what is actually read and handles cache outages gracefully, at the cost of a cold first read. Write-through keeps cache warm and consistent on writes, at the cost of write latency and caching cold data. |
| Stale data on update | Prefer delete-on-write (invalidate cache after DB commit) over writing the new value to cache, avoiding concurrent-write reorder races. |
| Split-brain routing | Use a lightweight coordination service (etcd/ZooKeeper) or gossip membership to distribute ring topology updates to smart clients or dedicated proxies (Twemproxy/Envoy). |
8. What to mention if you have 5 minutes left
- Multi-region: Local cache cluster per region, async invalidation stream (CDC / Kafka) across regions.
- Observability: Track hit rate, eviction rate, p99 by shard (to spot hot keys immediately), and DB fallthrough QPS.
- ML twist: The exact same sharding + locality principles apply to LLM KV-cache prefix routing—sticky routing prompts with shared prefixes to the same GPU worker avoids recomputing prefill.