System Design Atlas
LOCAL GUEST MODERead and practice without an account.

Your saved topics and reading progress stay in this browser. Sign in to sync supported profile and progress data.

Design a Distributed Cache

One zone goes down and miss traffic jumps.

○ EasySystem 022 min1 prerequisite
My progress
Topic tools

Layout updated

Explore the design, then rehearse the decisions without looking.

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 ownerMinimal 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 / inputResponse 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

  1. Reach the right Application and cache client SDK
  2. Route requestsPartition mapping held by the SDK
  3. Store cached values primaries and cross-zone replicas
  4. 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.

Distributed cache architecture
G app->sdk 1. GET / PUT / DELETE sdk->route 2. Hash key to partition route->p1 3. Route shard 1 p1->r1 4. Replicate updates p1->r1b 5. Replicate updates route->p2 6. Route shard 2 p2->r2 7. Replicate updates p2->r2b 8. Replicate updates route->p3 9. Route shard 3 p3->r3 10. Replicate updates p3->r3b 11. Replicate updates control->meta 12. Commit topology meta->control 13. Load committed state control->sdk 14. Publish topology control->p1 15. Manage ownership app Application services edge sdk Cache client SDK edge route Partition mapping compute control Control plane · membership and health compute meta Durable topology store state · durable p1 Shard 1 primary · AZ A state · memory r1 Shard 1 replica · AZ B state · memory p2 Shard 2 primary · AZ B state · memory r2 Shard 2 replica · AZ A state · memory p3 Shard 3 primary · AZ C state · memory r3 Shard 3 replica · AZ A state · memory r1b Shard 1 replica · AZ C state · memory r2b Shard 2 replica · AZ C state · memory r3b Shard 3 replica · AZ B state · memory
  • Edge
  • Compute
  • State

━━ Synchronous┄┄ Asynchronous···· Recovery / control▧ Fault

Select a component or follow a numbered connection.

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.

with
G a->k1 Clockwise k1->b b->k2 k2->a2 a2->c c->k3 k3->k4 k4->a Wrap to 0 a A₁ · 0 k1 K1 · 15 b B · 32 k2 K2 · 43 a2 A₂ · 52 c C · 67 k3 K3 · 76 k4 K4 · 90

━━ Synchronous┄┄ Asynchronous···· Recovery / control▧ Fault

Select a component or follow a numbered connection.

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.

Application integration · cache-aside
G app->cache 1. Check cached key app->db 2. Fetch on miss app->cache 3. Fill with TTL app->db 4. Commit source update app->cache 5. Invalidate after commit app Application services edge cache Distributed cache state · memory db Application source DB state · durable
  • Edge
  • State

━━ Synchronous┄┄ Asynchronous···· Recovery / control▧ Fault

Select a component or follow a numbered connection.

Each arrow is one interaction. Request, background and recovery branches are not one linear transaction.

Read the 5 flow steps

End-to-end flow

  1. 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.

  2. 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.

  3. 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.

  4. 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

Client / user

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

Gateway / routing

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

Coordination / ownership

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

Coordination / ownership

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

Relational database

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

Cache / in-memory index

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

Cache / in-memory index

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

Cache / in-memory index

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

Cache / in-memory index

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

Cache / in-memory index

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

Cache / in-memory index

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

Cache / in-memory index

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

Cache / in-memory index

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

Cache / in-memory index

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

Execution state

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

Execution state

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;

Execution state

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: ;

Execution state

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: ;

Execution state

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: ;

Execution state

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: ;

Execution state

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: ;

Execution state

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

Client / user

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

Cache / in-memory index

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

Relational database

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.

Deep dive 1

Hot keys and cache stampedes

Spread reads for a popular key and share the work of refilling it.

Read the explanation and worked example
How it works

If product:42 expires, hundreds of requests can miss together. them so one request fetches the value and the others wait briefly for that result. Give different keys slightly different TTLs to avoid mass expiry.

Walk through an example

When product:42 expires during a sale, one request fetches it while others share the result. To serve stale while refreshing, keep a separate soft expiry and a hard limit on how old a usable value can be.

Failure and recovery

If refresh fails, serve stale only within that limit. Otherwise return an error or shed work when the origin budget is exhausted.

Why this helps

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.

What you give up

Read copies and local caches can serve older values. Add them only where the freshness budget allows it.

Deep dive 2

Primary node failure

Promote a replica and give it a new ownership .

Read the explanation and worked example
How it works

When the A primary stops responding, the checks health and revokes its authority before activating the best available replica. A primary can mutate data only while its is valid. Wait for the old to expire if it cannot be revoked safely.

Walk through an example

The B replica becomes primary at 12. A client with 11 refreshes the topology and retries within its deadline. Merely publishing 12 would not stop an isolated -11 server from accepting writes.

Failure and recovery

Rebuild the missing replica. If the promoted node lacks a recent entry, report a miss and allow bounded refill. For freshness-sensitive keys, do not serve an older replica value as current.

Why this helps

The can restore requests quickly using a copy already in memory.

What you give up

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.

Deep dive 3

Stale cache-fill race

For keys that need fresher results, reject a refill older than the most recent invalidation.

Read the explanation and worked example
How it works

1. Reader A misses cache and reads DB version 4. 2. Writer B updates DB to version 5. 3. Writer B invalidates cache. 4. Reader A completes late and writes version 4 into cache.

Walk through an example

At step 3, invalidate with minimum version 5. The atomically deletes older data and remembers 5, even while the key is empty. At step 4 it compares the incoming version with the floor and rejects 4.

Failure and recovery

A delayed event can still leave a freshness window. Keep floors across failover or quarantine uncertain entries and refills until caught up. Reads requiring the latest committed value should use the authoritative source.

Why this helps

A delete removes the current entry but cannot stop a reader already holding an older value.

What you give up

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.

Deep dive 4

AZ failure and miss storms

Restore coverage and protect the database while hit rate recovers.

Read the explanation and worked example
How it works

Promote affected replicas in surviving zones. Reserve enough CPU, network and memory for redistributed traffic. Warm the hottest keys first under a budget rather than reloading everything.

Walk through an example

After A disappears, successful cache requests may recover before hit rate does. Share same-key misses and cap total fetch concurrency across keys.

Failure and recovery

Use and a circuit breaker when origin errors or latency rise. Serve stale only where allowed. Watch hit rate, origin traffic and replica catch-up before increasing warmup.

Why this helps

One fetch per key still overloads the database if many different keys go cold at once.

What you give up

Reserve capacity for a zone outage and accept slower warmup to keep the origin healthy.

Deep dive 5

Rebalancing and topology changes

Warm the new owner, then switch the at a new .

Read the explanation and worked example
How it works

When a node joins, compute its ranges. Copy or warm their entries and catch up writes. Fence the old owner before handing write authority to the new one, then publish the .

Walk through an example

A virtual node inserted between two existing tokens takes only the interval from its predecessor to itself. Clients holding the old map refresh on a stale-owner response.

Failure and recovery

If warmup fails before handoff, leave the old owner active. Once the new owner is active, another move needs another . Throttle data movement to protect cache latency.

Why this helps

Only affected key ranges move. Most clients keep using their existing placement.

What you give up

A ring makes range movement intuitive. Fixed logical partitions offer explicit placement and migration control, with a larger ownership map to maintain.

Tradeoffs and alternatives

DecisionTradeoff / alternative and recovery implication
SDK vs proxyThe 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 partitionsVirtual tokens spread ownership and limit movement. Fixed partitions make reassignment explicit and easier to schedule.
Async vs sync replicationAsync keeps writes fast but may lose an acknowledged update. Sync waits for replicas and can reject writes during a partition.
Cache-aside vs write-throughCache-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 consistencyRequire a valid for writes. Where acceptable, reads can use stale copies within an explicit freshness budget.

Production scars & failure modes

Failure investigation

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 / failureImpactRecovery mechanismAlternative / tradeoff
Primary unreachable temporarily unavailableFence old owner, promote a replica and refresh client placement.Replication lag can lose recent cache updates.
Zone outageLower cache capacity and hit rateUse surviving replicas, then warm under bounded origin load.A request budget protects the database even if more callers see errors.
loses Unsafe to change ownershipKeep routing to -valid owners. Stop mutations where safe authority cannot be proved.Prefer a brief outage over two writable primaries.
Memory pressureLive entries evictedEnforce 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

TimeFocusWhat to cover
0–5 minIntroductionsIntroduce yourself briefly and confirm the interview format.
5–15 minScope and scaleScope the cache , estimate memory and throughput, and agree on data loss and staleness.
15–30 minHigh-level designDraw the SDK, three shards and cross-zone replicas. Trace a GET and explain how a topology change reaches clients.
30–45 minDeep divesUse a hot key and a late refill to explain traffic and freshness. Then discuss node failover, zone loss and rebalancing.
45–55 minFailure and recoveryExplain , replica catch-up and how you keep misses from overwhelming the source.
55–60 minWrap-upSummarize the design and its main tradeoff. Leave time for questions.
On this page
  1. Problem statement
  2. Functional requirements
  3. Non-functional requirements
  4. Back-of-the-envelope estimates
  5. Entities
  6. API design
  7. High-level design
  8. End-to-end flow
  9. High-level design component walkthrough
  10. Engineering control room
  11. Deep dives — decisions, failures and recovery
  12. Tradeoffs and alternatives
  13. Production scars & failure modes
  14. 75-second interview summary
  15. Explain it without looking
  16. Revision checklist
  17. 60-minute interview walkthrough

Save & sync your Atlas progress

Sync your profile and topic progress across browsers, then return to the same study desk.

Google sign-in will appear here after its Azure provider is configured.

Architecture diagram