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.

Distributed Cache

Design a shared cache that keeps popular data close to applications and continues working when a node fails.

Design○ Easy30 min study estimate

Before you begin: 1 prerequisite

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

RecordKey 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

EndpointResult
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

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

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

  2. Write: the application commits to the database, then publishes an invalidation. The cache is a temporary copy and can lag behind the database.

  3. Recovery: fence a failed owner, promote a replica and limit database fallback while the cache warms.

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

Which caching strategy fits?

StrategyHow it worksTradeoff
Cache-asideThe application reads the cache and fills misses from the database.Simple and flexible, but the application handles misses and invalidation.
Write-throughWrites update the cache as part of the write flow.Keeps frequently written values warm, but adds work and coupling to writes.
onlyEntries expire after a set time.Simple, but updates can remain stale until expiry.
Deep dive 1

Hot keys and cache stampedes

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

Staff lens — Per-process coalescing still allows one database fetch from each application instance.

What if one key becomes popular?

A popular key still hashes to one owner. First use local caching or read replicas if their freshness is acceptable. For a read-heavy key, create a small number of salted copies on different owners and distribute reads across them. Refresh or invalidate every copy after a change.

A cold key during a traffic spike

A viral product gets 200,000 reads per second. Four warmed copies can share reads when their owners have capacity. Distribution is approximate and depends on routing and placement.

If the database is overloaded

If a copy is missing, concurrent misses per application instance. Limit fallback across the fleet, and shed work when the database budget is exhausted.

Deep dive 2

Concurrency inside a cache node

Use an event loop to handle many connections and keep cache commands short.

Staff lens — Multiplexing handles many connections; it does not execute commands in parallel. Other threads may handle networking or background work.

How can one node serve many connections?

With non-blocking sockets, epoll or kqueue signals ready connections. A Redis-style event loop reads a request, executes a command on the owning thread and sends or queues the response. Serial command execution avoids locks around that thread-owned state.

Two clients become ready

Suppose 10,000 connections are open and only two send requests. The multiplexer reports the ready sockets. The loop processes their GET and SET commands in turn while idle connections wait.

When the event loop gets busy

A slow command or script holds up later commands on that owner. Watch event-loop latency and slow commands, bound expensive work and distribute independent keys across shards.

Redis event loop and latency ↗

Deep dive 3

Primary node failure

Promote a replica and give it a new ownership .

Staff lens — A replica can miss an acknowledged update, so promotion may lose a cache write.

What happens when an owner fails?

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.

Promote a replica

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.

When a recent write is missing

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.

Deep dive 4

Stale cache-fill race

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

Staff lens — A version floor helps after invalidation arrives. It cannot remove the delay before the event arrives.

How can old data return after an update?

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.

A slow refill races an update

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.

If invalidation is delayed

Use a transactional or to deliver invalidations after commit. A delayed event still leaves a stale-read window. Retain the version floor through eviction and failover, or quarantine uncertain entries and refills. Read from the database when the latest value is required.

Deep dive 5

AZ failure and miss storms

Restore coverage and protect the database while hit rate recovers.

Staff lens — A zone outage can make many keys cold at once, even when each key has only one refill.

What happens when a zone fails?

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.

Many keys become cold

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

When to shed work

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.

Deep dive 6

Rebalancing and topology changes

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

Staff lens — Moving ownership needs so old and new owners cannot both accept writes.

How do keys move when capacity changes?

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 .

Add a cache node

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.

If the move fails

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.

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

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.

Save & sync your Atlas progress

Keep your progress across devices.

Architecture diagram