Design a Distributed Cache
One zone goes down and miss traffic jumps.
Topic tools
Layout updated
Problem statement
Design a distributed cache that applications can use to read, store, and delete temporary copies of data. Entries can expire, and the cache should grow across machines and recover when a machine fails.
Functional requirements
- GET finds a live key or returns a miss. PUT creates or replaces a key with a . DELETE invalidates it.
- Expire entries at their deadline and evict entries under memory pressure.
- across nodes, route automatically, and recover with replicas across availability zones.
- Optional changes a value only when its entry version matches.
Non-functional requirements
- Illustrative targets: 1M peak requests/s, regional under 5 ms and 99.99% availability. Validate under skew and failover.
- Three copies across availability zones, eventually consistent replication and limited key movement on membership changes.
- An accepted cache write can be lost during failover. Optional is at the active primary, with no claim of durable application consistency.
Back-of-the-envelope estimates
| Illustrative estimate |
|---|
| 100M keys × 1 KB ≈ 100 GB raw values |
| 1M peak requests/s at 90% reads ≈ 900k reads/s and 100k writes/s |
| Three copies ≈ 300 GB plus overhead and spare capacity |
Entities
| Entity / logical owner | Minimal authoritative fields and boundary |
|---|---|
| Entry(key, value, expiresAt, entryVersion) | Lives on the primary and two replicas. Replicate the expiry deadline so promotion does not restart a . |
| placement(tokens, owners, ) | Durable control-plane state. Clients cache a and send the with requests. |
| Optional version floor(key, minSourceVersion) | Cache-aside extension. Keep the floor after deletion so a late refill cannot restore an older source value. |
API design
| Operation / input | Response and retry contract |
|---|---|
GET(key) | value + entryVersion | NOT_FOUND. Expired keys are absent. A timeout or stale route is a separate error. |
PUT(key, value, ttl) | OK after primary accepts the write. starts at acceptance. Replica catch-up is asynchronous. |
DELETE(key) | OK even if absent. Replicate the delete so a promoted copy can apply it. |
CAS(key, expectedVersion, value, ttl) | SUCCESS | CONFLICT. Compare and update atomically on the current primary. |
High-level design
How to draw this design
- Reach the right Application and cache client SDK
- Route requestsPartition mapping held by the SDK
- Store cached values primaries and cross-zone replicas
- Manage topologyMembership, health checks, and durable topology store
The SDK uses its routing map to reach a . Cache-aside callers fetch misses from the application database.
- State ownership
- The application database owns source values. The topology store owns membership and placement.
- Scale
- Spread keys across shards and expensive cache misses.
- Correctness
- Version checks prevent a late fill from undoing an invalidation.
- Failure and recovery
- Fence the old primary and refresh client routing after promotion.
Distributed cache architecture
The SDK hashes the key and looks up the primary using its local partition map. Each has one primary and two replicas, one copy in each availability zone. The dotted topology and ownership arrows run outside the request path. A primary returns the result on the same request.
- Edge
- Compute
- State
━━ Synchronous┄┄ Asynchronous···· Recovery / control▧ Fault
Each arrow is one interaction. Request, background and recovery branches are not one linear transaction.
Read the 15 flow steps
Consistent hashing with virtual nodes
Hash each key onto the ring and move clockwise to the first node token. K1 goes to B, K2 goes to A₂, and K3 and K4 wrap around to A₁. A₁ and A₂ belong to the same physical node A. Multiple tokens spread ownership around the ring. Adding a token moves only the interval between that token and the one before it.
━━ Synchronous┄┄ Asynchronous···· Recovery / control▧ Fault
Each arrow is one interaction. Request, background and recovery branches are not one linear transaction.
Read the 8 flow steps
Application integration · cache-aside
The database and request coalescing belong to the application’s cache-aside flow. A GET on the generic cache does not fetch the source itself.
- Edge
- State
━━ Synchronous┄┄ Asynchronous···· Recovery / control▧ Fault
Each arrow is one interaction. Request, background and recovery branches are not one linear transaction.
Read the 5 flow steps
End-to-end flow
Core cache: the SDK hashes the key, finds the owning and sends the operation with its topology . A hit returns the value. A miss returns NOT_FOUND. Writes go to the primary, which replicates to the other zones.
Cache-aside read: the application asks the cache first. On a hit it returns the value. On a miss, share one database fetch per key, fill the cache with a and return the value. A cache timeout uses its own bounded fallback policy.
Cache-aside write: commit the application change to the DB first, then invalidate the cached copy. Invalidating before commit lets a concurrent reader reload the old value. Even after commit, delayed invalidation or an in-flight refill can leave stale data.
STATE → in-memory entries and durable topology. SCALE → partition keys and isolate hot reads. CORRECTNESS → fence writers, define and freshness. FAILURE → promote replicas and bound fallback. MULTI-REGION → rebuild regional caches from their source.
High-level design component walkthrough
Application services
Call the cache
Why, tradeoff and connected operations
Applications decide how to handle misses.
Tradeoff: Fallback can overwhelm the source.
Connected operations: GET / PUT / DELETE
Cache client SDK
Hash the key and route using local topology
Why, tradeoff and connected operations
Direct routing saves a network hop.
Tradeoff: Clients need topology refresh and retry budgets.
Connected operations: GET / PUT / DELETE; Hash key to partition; Publish topology
Partition mapping
Hash each key and look up its primary in the local map.
Why, tradeoff and connected operations
Routing runs inside the SDK, using cached topology. Requests go directly to the primary after this local lookup.
Tradeoff: Clients refresh old maps when ownership changes.
Connected operations: Hash key to partition; Route 1; Route 2; Route 3
Control plane · membership and health
Manage placement, leases and promotion
Why, tradeoff and connected operations
Ownership changes stay off the request path.
Tradeoff: Loss of delays safe reconfiguration.
Connected operations: Commit topology; Load committed state; Publish topology; Manage ownership
Durable topology store
Store assignments, state and ownership epochs
Why, tradeoff and connected operations
A small -backed metadata store gives controllers one authoritative placement and changes. It holds topology, while cache values remain in memory.
Tradeoff: A is needed to change placement safely.
Connected operations: Commit topology; Load committed state
Shard 1 primary · AZ A
Serve GET, PUT, DELETE and . Enforce expiry and eviction.
Why, tradeoff and connected operations
Local memory keeps reads and writes fast. One primary orders each key’s updates and sends them to replicas.
Tradeoff: State can disappear after eviction or failover.
Connected operations: Route 1; Replicate updates; Replicate updates; Manage ownership
Shard 1 replica · AZ B
Keep one in-memory replica in this zone.
Why, tradeoff and connected operations
Surviving copies can take over a failed primary without fetching every key from the application database.
Tradeoff: Asynchronous copies can lag.
Connected operations: Replicate updates
Shard 2 primary · AZ B
Serve GET, PUT, DELETE and . Enforce expiry and eviction.
Why, tradeoff and connected operations
Local memory keeps reads and writes fast. One primary orders each key’s updates and sends them to replicas.
Tradeoff: State can disappear after eviction or failover.
Connected operations: Route 2; Replicate updates; Replicate updates
Shard 2 replica · AZ A
Keep one in-memory replica in this zone.
Why, tradeoff and connected operations
Surviving copies can take over a failed primary without fetching every key from the application database.
Tradeoff: Asynchronous copies can lag.
Connected operations: Replicate updates
Shard 3 primary · AZ C
Serve GET, PUT, DELETE and . Enforce expiry and eviction.
Why, tradeoff and connected operations
Local memory keeps reads and writes fast. One primary orders each key’s updates and sends them to replicas.
Tradeoff: State can disappear after eviction or failover.
Connected operations: Route 3; Replicate updates; Replicate updates
Shard 3 replica · AZ A
Keep one in-memory replica in this zone.
Why, tradeoff and connected operations
Surviving copies can take over a failed primary without fetching every key from the application database.
Tradeoff: Asynchronous copies can lag.
Connected operations: Replicate updates
Shard 1 replica · AZ C
Keep one in-memory replica in this zone.
Why, tradeoff and connected operations
Surviving copies can take over a failed primary without fetching every key from the application database.
Tradeoff: Asynchronous copies can lag.
Connected operations: Replicate updates
Shard 2 replica · AZ C
Keep one in-memory replica in this zone.
Why, tradeoff and connected operations
Surviving copies can take over a failed primary without fetching every key from the application database.
Tradeoff: Asynchronous copies can lag.
Connected operations: Replicate updates
Shard 3 replica · AZ B
Keep one in-memory replica in this zone.
Why, tradeoff and connected operations
Surviving copies can take over a failed primary without fetching every key from the application database.
Tradeoff: Asynchronous copies can lag.
Connected operations: Replicate updates
A₁ · 0
Virtual token on physical node A.
Why, tradeoff and connected operations
Each token owns the interval from the previous token up to itself.
Tradeoff: Keys can be evenly placed while request traffic is skewed.
Connected operations: Clockwise; Wrap to 0
K1 · 15
Example key at its hashed position.
Why, tradeoff and connected operations
Walk clockwise to the first token to find its owner.
Tradeoff: Keys can be evenly placed while request traffic is skewed.
Connected operations: Clockwise;
B · 32
Virtual token on physical node B.
Why, tradeoff and connected operations
Each token owns the interval from the previous token up to itself.
Tradeoff: Keys can be evenly placed while request traffic is skewed.
Connected operations: ;
K2 · 43
Example key at its hashed position.
Why, tradeoff and connected operations
Walk clockwise to the first token to find its owner.
Tradeoff: Keys can be evenly placed while request traffic is skewed.
Connected operations: ;
A₂ · 52
Virtual token on physical node A.
Why, tradeoff and connected operations
Each token owns the interval from the previous token up to itself.
Tradeoff: Keys can be evenly placed while request traffic is skewed.
Connected operations: ;
C · 67
Virtual token on physical node C.
Why, tradeoff and connected operations
Each token owns the interval from the previous token up to itself.
Tradeoff: Keys can be evenly placed while request traffic is skewed.
Connected operations: ;
K3 · 76
Example key at its hashed position.
Why, tradeoff and connected operations
Walk clockwise to the first token to find its owner.
Tradeoff: Keys can be evenly placed while request traffic is skewed.
Connected operations: ;
K4 · 90
Example key at its hashed position.
Why, tradeoff and connected operations
Walk clockwise to the first token to find its owner.
Tradeoff: Keys can be evenly placed while request traffic is skewed.
Connected operations: ; Wrap to 0
Application services
Call the cache
Why, tradeoff and connected operations
Applications decide how to handle misses.
Tradeoff: Fallback can overwhelm the source.
Connected operations: Check cached key; Fetch on miss; Fill with ; Commit source update; Invalidate after commit
Distributed cache
Return hits or misses and accept fills
Why, tradeoff and connected operations
Keep popular values in shared memory to avoid repeated database reads. The application refills missing entries from its source.
Tradeoff: Expiry and eviction can increase misses.
Connected operations: Check cached key; Fill with ; Invalidate after commit
Application source DB
Own durable values and versions
Why, tradeoff and connected operations
For this example, transactions can commit the value and its version together. The cache can be rebuilt from these records.
Tradeoff: Concurrent fallback needs a limit.
Connected operations: Fetch on miss; Commit source update
Engineering control room
Deep dives — decisions, failures and recovery
Open a deep dive to follow the steps, try an example and see how recovery works.
Tradeoffs and alternatives
| Decision | Tradeoff / alternative and recovery implication |
|---|---|
| SDK vs proxy | The SDK saves a network hop. A proxy centralizes routing and is easier to update across languages, but adds capacity and latency to manage. |
| Ring vs fixed partitions | Virtual tokens spread ownership and limit movement. Fixed partitions make reassignment explicit and easier to schedule. |
| Async vs sync replication | Async keeps writes fast but may lose an acknowledged update. Sync waits for replicas and can reject writes during a partition. |
| Cache-aside vs write-through | Cache-aside leaves the DB and refill policy with the application. Write-through centralizes updates but couples writes to both systems. |
| vs LFU | favors recent keys. LFU protects frequently used keys from scans but is slower to adapt to changing popularity. |
| Availability vs consistency | Require a valid for writes. Where acceptable, reads can use stale copies within an explicit freshness budget. |
Production scars & failure modes
One zone goes down and miss traffic jumps.
Look for: Compare ownership, hit rate, retry volume and source database latency.
Recovery and invariant: Promote surviving replicas and cap fallback traffic while the hottest entries warm up.
| Component / failure | Impact | Recovery mechanism | Alternative / tradeoff |
|---|---|---|---|
| Primary unreachable | temporarily unavailable | Fence old owner, promote a replica and refresh client placement. | Replication lag can lose recent cache updates. |
| Zone outage | Lower cache capacity and hit rate | Use surviving replicas, then warm under bounded origin load. | A request budget protects the database even if more callers see errors. |
| loses | Unsafe to change ownership | Keep routing to -valid owners. Stop mutations where safe authority cannot be proved. | Prefer a brief outage over two writable primaries. |
| Memory pressure | Live entries evicted | Enforce memory budgets and expire keys before reclaiming live entries. | Approximate is simple. LFU better protects frequent keys from scans but adapts more slowly. |
75-second interview summary
I’d build a regional in-memory key-value service. The client SDK hashes each key into a using a ring with , then sends the request directly to the current primary. The tracks membership and publishes versioned topology. It stays off the request path.
Each has two replicas in other zones. I’d acknowledge writes at the primary and replicate asynchronously to keep latency down. If the primary fails, fence it before promoting a replica. Clients refresh their map and retry within a deadline. Some acknowledged cache writes can disappear, so the application still owns durable truth.
A hot key needs extra read copies or a short-lived local cache because hashing alone sends all those reads to one . On misses, I’d requests and cap database fallback, especially after a zone failure. For fresher cache-aside reads, I’d use version-aware invalidation and reject late fills. The freshness requirement determines when to bypass the cache.
Explain it without looking
Explain hot keys and cache stampedes
Reveal answer
Spread reads for a popular key and share the work of refilling it.
If product:42 gets 200,000 reads per second, every request still hashes to the same . A short-lived cache in each application process or extra read copies can absorb those reads.
Read copies and local caches can serve older values. Add them only where the freshness budget allows it.
Explain primary node failure
Reveal answer
Promote a replica and give it a new ownership .
The can restore requests quickly using a copy already in memory.
An acknowledged PUT can be lost if it was not replicated. Synchronous replication reduces that window at the cost of write latency and availability during partitions.
Explain stale cache-fill race
Reveal answer
For keys that need fresher results, reject a refill older than the most recent invalidation.
A delete removes the current entry but cannot stop a reader already holding an older value.
Version floors use memory and must survive long enough to cover in-flight refills. Ordinary content may only need a short and bounded refill deadlines.
Explain failure and miss storms
Reveal answer
Restore coverage and protect the database while hit rate recovers.
One fetch per key still overloads the database if many different keys go cold at once.
Reserve capacity for a zone outage and accept slower warmup to keep the origin healthy.
Explain rebalancing and topology changes
Reveal answer
Warm the new owner, then switch the at a new .
Only affected key ranges move. Most clients keep using their existing placement.
A ring makes range movement intuitive. Fixed logical partitions offer explicit placement and migration control, with a larger ownership map to maintain.
Revision checklist
Revision checklist
- Reconstruct hot keys and cache stampedes: Spread reads for a popular key and share the work of refilling it.
- Reconstruct primary node failure: Promote a replica and give it a new ownership .
- Reconstruct stale cache-fill race: For keys that need fresher results, reject a refill older than the most recent invalidation.
- Reconstruct failure and miss storms: Restore coverage and protect the database while hit rate recovers.
- Reconstruct rebalancing and topology changes: Warm the new owner, then switch the at a new .
- Name the authoritative state, boundary, retry identity and failure-domain durability guarantee.
- Explain one alternative and exactly which guarantee you would relax.
- Redraw the request and recovery paths without looking; mark what required a hint.
60-minute interview outline
60-minute interview walkthrough
| Time | Focus | What to cover |
|---|---|---|
| 0–5 min | Introductions | Introduce yourself briefly and confirm the interview format. |
| 5–15 min | Scope and scale | Scope the cache , estimate memory and throughput, and agree on data loss and staleness. |
| 15–30 min | High-level design | Draw the SDK, three shards and cross-zone replicas. Trace a GET and explain how a topology change reaches clients. |
| 30–45 min | Deep dives | Use a hot key and a late refill to explain traffic and freshness. Then discuss node failover, zone loss and rebalancing. |
| 45–55 min | Failure and recovery | Explain , replica catch-up and how you keep misses from overwhelming the source. |
| 55–60 min | Wrap-up | Summarize the design and its main tradeoff. Leave time for questions. |
On this page
- Problem statement
- Functional requirements
- Non-functional requirements
- Back-of-the-envelope estimates
- Entities
- API design
- High-level design
- End-to-end flow
- High-level design component walkthrough
- Engineering control room
- Deep dives — decisions, failures and recovery
- Tradeoffs and alternatives
- Production scars & failure modes
- 75-second interview summary
- Explain it without looking
- Revision checklist
- 60-minute interview walkthrough