Distributed Cache
Design a shared cache that keeps popular data close to applications and continues working when a node fails.
Problem statement
Keep frequently read data in memory across machines, so applications can answer quickly without sending every request to the database.
Functional requirements
- Get, put and delete cached values
- Expire entries using a
- Distribute keys across cache nodes
- Recover from node failures using replicas
Non-functional requirements
- Low-latency reads with high availability
- Horizontal scaling and recovery across zones
- Bounded origin load during cache failures
- Eventual consistency, with a defined freshness budget
Scale assumptions
- 100M keys × 1 KB ≈ 100 GB Three copies need about 300 GB before overhead.
- 1M requests/s at peak, mostly reads Plan for hot keys and reserve capacity for failures.
Entities
| Record | Key fields |
|---|---|
| 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
| Endpoint | Result |
|---|---|
GET(key) | Value or cache miss |
PUT(key, value, ttl) | Store a temporary copy |
DELETE(key) | Remove a cached copy |
CAS(key, version, value, ttl) | Update only if the version matches |
High-level design
How to group the architecture
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 floors reject older fills after invalidation reaches the owner. Delayed invalidation can still serve stale data.
- 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
Read: the client routes the key to its cache owner. On a miss, the application shares a database fetch and fills the cache with a .
Write: the application commits to the database, then publishes an invalidation. The cache is a temporary copy and can lag behind the database.
Recovery: fence a failed owner, promote a replica and limit database fallback while the cache warms.
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
Which caching strategy fits?
| Strategy | How it works | Tradeoff |
|---|---|---|
| Cache-aside | The application reads the cache and fills misses from the database. | Simple and flexible, but the application handles misses and invalidation. |
| Write-through | Writes update the cache as part of the write flow. | Keeps frequently written values warm, but adds work and coupling to writes. |
| only | Entries expire after a set time. | Simple, but updates can remain stale until expiry. |
90-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.
Redraw the system from memory
Draw the client, owner, replicas and source database. Trace a hit, a miss and an invalidation.
Why can adding shards fail to fix a hot key?
Reveal answer
All requests for that key still reach its owner. Use read copies or a local cache when the freshness budget permits.
Can invalidation alone stop an old database read from filling the cache?
Reveal answer
No. Compare the source version against a retained version floor atomically at the owner.
What protects the database after a cache outage?
Reveal answer
misses per key and limit fleet-wide fallback concurrency. Shed excess work when the budget is exhausted.
Rehearsal checklist
- Trace a cache hit and a miss.
- Explain key placement and hot-key handling.
- State the freshness guarantee and failover tradeoff.
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. |