SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
  • Design a Chat App
  • Design a News Feed
  • Design a Notification System
  • Design a Web Crawler
  • Design Search Autocomplete
  • Design File Storage (Dropbox)
  • Design Video Streaming (YouTube/Netflix)
  • Design a Distributed Cache
  • Design a Leaderboard
  • Design a Job Scheduler
  • Design a Social Media Platform (Facebook)
System Design/Case Studies/Medium
Interview case study

Design a Distributed Cache

A cache across many machines: partitioning, eviction, replication and hot keys.

⏱ 32 min readMedium case studyIntermediate22 cross-questionsHas visualizer
Prompt60-sec answer45-min plan1 Clarify2 Estimate3 API + Data4 Design5 Deep dives6 Scale7 Wrap upCross-questionsVariationsScoringMistakesCheat-sheet

StartThe prompt and what is really being tested

The interviewer says

“Design a distributed cache, like Memcached or Redis Cluster.”

It is short on purpose. Your first job is to make it specific.

What they checkWhy it matters
Knowing what a cache is forA cache is allowed to lose data and to be a little stale. Saying this out loud, and designing around it, is what separates it from a key-value store.
Partitioning without a mass reshuffleHash mod N empties the cache when one node joins. You must explain consistent hashing or hash slots and what a new node costs.
Eviction and memoryA cache is always full. The interviewer wants to hear how you choose what to throw away, cheaply, and how expiry works.
Hot keys and stampedesThe cache fails in the interesting ways: one key melts one node, or a node dies and the database is flooded.
Consistency with the databaseStale data is allowed, but wrong forever is not. You need a clear rule for invalidation and a safety net (TTL).

TL;DRThe whole design in 60 seconds

A distributed cache is a fleet of in-memory machines that sit in front of a database. Keys are spread over the machines by consistent hashing (or hash slots), so adding a node moves only a small slice. The application uses it cache-aside: read the cache, on a miss read the database and fill the cache.

  • Scale: 1 million ops/s and a 10 TB working set need about 110 nodes of 100 GB. That is a few thousand ops/s per node, so memory sets the size, not CPU.
  • Routing: a smart client library (or a proxy tier, or cluster-aware clients with 16,384 hash slots) finds the node with no extra hop.
  • Eviction: each node keeps a hash table with LRU or LFU metadata. It evicts an approximate least-recently-used key, and expires keys lazily plus a small sampled sweep.
  • Hot keys: one key can saturate one node. Keep hot keys in the app server's own memory for a second or two, or spread them over several nodes with key suffixes.
  • Failure: the cache is not the source of truth. A primary and an async replica per shard give fast failover, and stampede protection (single-flight, jittered TTLs) keeps the database alive when a node is lost.
  • Consistency: delete the key after the database write, give every key a TTL as a safety net, and accept brief staleness.
💡How to use this page
Read the 60-second answer first. Then work through steps 1 to 7 in order, and try each step yourself before reading the model answer. Finish with the cross-questions: say your answer out loud, then open the model one.

PlanA 45-minute plan

4
3
4
8
15
8
3
Minutes per step (total 45). A guide, not a rule: move time to the part the interviewer cares about.
StepMinutesWhat to get done
1. Clarify4Cache-aside or built in, value size, scale, staleness allowed, persistence, what a cache failure may do.
2. Estimate3Working set in memory, node count, ops per node, and the hit ratio that protects the database.
3. API and data4get, set with TTL, delete, batch get. What one entry holds in memory.
4. High-level design8Clients, routing, shards with a replica, config service, and the miss path to the database.
5. Deep dives15Partitioning and rebalancing, eviction and memory, hot keys, failure and consistency.
6. Scale and failures8Node loss, avalanche, network, monitoring, security.
7. Wrap up3Recap, the trade-offs, and what you would add next.

Step 1Clarify requirementsabout 4 min

🤔
Pause. Try it yourself first
You have 60 seconds. Write five questions that would change the design. Hint: think about who talks to the cache, how stale a read may be, how big the data is, and what should happen when the cache is down.

Questions to ask, and why

AskWhy you ask itTypical answerHow it changes the design
Is this a cache in front of a database, or the main store for this data?A cache may lose data. A store may not. This one question separates the two designs.A cache. The database is the source of truth, and any key can be rebuilt from it.No need for durable writes or quorums. Replication is only there to make failover quick.
Who uses it, and through which API?Decides whether we build a client library, a proxy, or both.Many internal services, through a client library, in one region.A smart client does the routing. A proxy tier can be added for languages without a good client.
What operations, and what sizes?Value size changes memory layout and network cost.get, set with a TTL, delete, and batch get. Values up to 1 MB, about 1 KB on average.Small values: a hash table with slab-like memory pools. Cap the size and say so.
How much traffic and how much data?Sets the node count and shows whether CPU or memory is the limit.Peak 1 million ops/s, 90% reads, a working set of 10 TB.Memory is the limit. Roughly a hundred nodes, each with moderate traffic.
What latency do we need?A cache that is slow is not a cache.p99 under 2 ms inside the data centre.One network hop, no cross-zone calls on the hot path, short client timeouts.
How stale may a read be?Decides the invalidation scheme and the TTLs.A few seconds of staleness is fine, but not wrong data for hours.Cache-aside with delete on write, plus a TTL as a safety net.
What if the cache is unavailable?Defines whether the cache is a performance helper or a hard dependency.The product must keep working, slower. The database must not be crushed.Client timeouts, circuit breaker, stampede protection, and a limit on database traffic.
Must data survive a restart?Persistence adds cost and complexity.No. A cold start is acceptable if we can warm it.Memory only. Optional snapshots to speed up recovery, plus a warming plan.
Is it shared by many teams?Multi-tenancy needs isolation and quotas.Yes. One noisy team must not evict another team's data.Key prefixes per tenant, memory quotas, and per-tenant rate limits.
One region or several?Cross-region latency is far larger than the cache latency target.One region first. Each region has its own cache.No cross-region replication of cache data. Use an invalidation stream if needed later.

Write the scope on the board

Functional (must do)
  • •get(key) returns the value or a miss
  • •set(key, value, ttl) stores a value that expires
  • •delete(key) removes a value
  • •Batch get for many keys in one call
  • •Atomic counters or compare-and-set as an option
Non-functional (how well)
  • •Fast: p99 under 2 ms for get and set inside the data centre
  • •Scales out: add nodes online, with only a small slice of keys moving
  • •Available: losing a node must not stop the service or flood the database
  • •A cache, not a store: data may be lost, and slightly stale reads are allowed
  • •Hit ratio of 95% or better on the working set
Out of scope (say it)
  • •Durable storage and strong consistency (use the key-value store for that)
  • •Cross-region replication of cache contents
  • •Complex queries, secondary indexes and transactions
  • •Cache contents as the only copy of any data
🎤
Say it out loud
“Let me confirm the scope. This is a cache in front of a database, so the database is the source of truth and the cache may lose data. Many services use it through a client library, in one region. We need get, set with a TTL, delete and batch get, with values around 1 KB and up to 1 MB. Peak is about a million operations a second, 90% reads, over a 10 TB working set, with p99 under 2 ms. A few seconds of staleness is fine. If the cache is down the product must keep working, slower, without crushing the database. Does that match?”

Step 2Estimate the scaleabout 3 min

🤔
Pause. Try it yourself first
On paper: how many entries is 10 TB? How much memory goes on overhead? How many nodes at 100 GB each? How many operations per node? And what does the hit ratio do to the database?

Assumptions (say them first)

AssumptionValue
Working set (values)10 TB
Average value size1 KB
Per-key overhead (key, pointers, TTL, LRU data)about 64 bytes
Usable memory per node100 GB (on machines with more, headroom kept for the OS and fragmentation)
Peak client traffic1 million ops/s, 90% reads and 10% writes
Operations one node can serve (illustrative)about 100,000 per second
Copies1 primary and 1 replica per shard
Hit ratio target95%
Client app servers2,000, each keeping 5 connections to each node

The arithmetic, line by line

WhatMathsResult
Entries in the working set10 TB ÷ 1 KB = 10^13 ÷ 10^310 billion entries
Memory used by overhead10 billion × 64 B640 GB (about 6% more)
Memory for one copy10 TB + 0.64 TBabout 10.6 TB
Primary nodes10.64 TB ÷ 100 GB per nodeabout 106, round to 110
Nodes including replicas110 primaries × 2220 machines, 22 TB of RAM
Reads and writes per second1M × 90% and 1M × 10%900,000 reads and 100,000 writes
Operations per primary1M ÷ 110about 9,100 per second (9% of a node's limit)
Read bandwidth out of the cache900,000 × 1 KB900 MB/s, about 7.2 Gbit/s in total, 65 Mbit/s per node
Database load at 95% hits900,000 reads × (1 − 0.95)45,000 reads per second reach the database
Database load at 90% and at 99%900,000 × 0.10 and × 0.0190,000 and 9,000 reads per second
Value of each hit-ratio point900,000 × 1%9,000 database reads per second saved per point
Hash slots per node (Redis Cluster style)16,384 ÷ 110about 149 slots per primary
A hot key at 10% of reads900,000 × 10%90,000 ops/s on one node, 90% of its limit
Adding one node with hash mod N110 ÷ 11199.1% of keys move: nearly 890,000 reads/s become misses
Adding one node with consistent hashing1 ÷ 1110.9% of keys move, about 96 GB, and about 8,100 reads/s become misses
Connections2,000 servers × 110 nodes × 51.1 million connections, 10,000 per node
What the numbers tell us about the design
  • •Memory, not CPU, sets the size. 110 nodes at 9% of their operation limit means we buy RAM, and the cluster has room for traffic.
  • •Every hit-ratio point is worth 9,000 database reads per second. A drop from 95% to 90% doubles the database load.
  • •One hot key can use 90% of a node on its own, even though the average node is at 9%. Skew is the real risk.
  • •Hash mod N turns adding one node into a near-total cache flush. Consistent hashing or slots limit it to about 1% of keys.
  • •10,000 connections per node is normal, but it means connection handling must be cheap, and clients should reuse and pipeline.
🎤
Say it out loud
“10 TB of values at 1 KB is 10 billion entries. With about 64 bytes of overhead each, that is 640 GB more, so about 10.6 TB. At 100 GB a node, that is about 110 primaries and 110 replicas. A million operations a second over 110 nodes is about 9,000 per node, so memory is the limit and not CPU. At a 95% hit ratio the database sees 45,000 reads a second, and every point of hit ratio is worth 9,000 reads. All of these are assumptions. The point is that we need a hundred-odd nodes, that skew is the real risk, and that adding a node must move about 1% of keys, not 99%.”

Step 3Define the API and the data modelabout 4 min

🤔
Pause. Try it yourself first
Write the calls. What does set take besides a value? How do you read many keys at once without a call per key? What does the client library hide?

Endpoints

MethodPathRequestResponseNotes
GET/v1/cache/{key}none200 { value, ttl_remaining } or 404A miss is a normal answer, not an error. The client then reads the database.
PUT/v1/cache/{key}{ value, ttl, if_absent? }204Always send a TTL. if_absent is for locks and single-flight. Values over the size cap get 413.
DELETE/v1/cache/{key}none204Idempotent. Used after a database write.
POST/v1/cache/mget{ keys: [...] }200 { hits: {...}, misses: [...] }The client groups keys by node and sends one request to each node in parallel.
POST/v1/cache/{key}/incr{ by, ttl? }200 { value }Atomic on one node. Used for counters and rate limits.

Data model

Held per entry in memoryTypeNotes
keybytes, up to 250Includes a tenant prefix so teams cannot collide.
valuebytes, up to 1 MBOpaque to the cache. Compressed by the client if large.
expires_attimestampChecked on read (lazy expiry) and by a background sweep.
last-access infoa few bytesA timestamp or a small counter, for LRU or LFU decisions.
hash-table linkpointerThe bucket chain. This and the fields above are the per-entry overhead.
Cluster stateHoldsWhere
Ring or slot mapWhich node owns which keys, plus replicasEvery client, loaded from the config service and refreshed on change
MembershipWhich nodes are upConfig service plus gossip or a health checker
Replication streamWrites from a primary to its replicaA buffer on each primary
Hot-key statsSampled counts of the busiest keysEach node, reported to monitoring
Cache-aside, the code the application writes
value = cache.get(key)
if value is null:
    value = db.read(key)              // the source of truth
    cache.set(key, value, ttl = 300 + jitter)   // jitter: spread expiry times
return value

on write:
    db.write(key, newValue)           // 1. write the database first
    cache.delete(key)                 // 2. then delete the cache entry
📝Which store, and why
There is no database choice here. Each node is a hash table in memory with an eviction structure. The decisions are the memory layout and the eviction method. Memcached uses slab classes, which are fixed-size chunks that avoid fragmentation. Redis uses a general allocator and sampling. Keep the key space as a plain hash map for O(1) get and set, add a small amount of LRU or LFU metadata per entry, and keep expiry times in a heap or a timing wheel. Say that, and move on.
🎤
Say it out loud
“The API is get, set with a TTL, delete, batch get and an atomic increment. A miss is a normal result, and the application reads the database and fills the cache. On a write, the application writes the database first and then deletes the cache entry. Every set carries a TTL, with a little random jitter, so entries cannot all expire together. In memory each entry holds the key, value, expiry time, a little eviction metadata and a hash-table link, which is about 64 bytes of overhead.”

Step 4Draw the high-level designabout 8 min

🤔
Pause. Try it yourself first
Draw the app server, the cache nodes and the database. Where does routing happen? What sits next to each cache node? What happens on a miss?
Distributed cache: high-level design
🖥️App serverclient library + small local cache
→↓key → shard
Cache cluster (110 shards)
⚡Shard 1primary + replica
⚡Shard 2primary + replica
⚡Shard … 110primary + replica
→↓miss
🗄️Databasesource of truth
Routing and membership
🗺️Config servicering or slot map, versioned
🩺Health checksdetect a dead primary
🔁Failoverreplica becomes primary
Inside one node
🧮Hash tablekey → entry
📉Evictionapproximate LRU / LFU
⏰Expirylazy + sampled sweep
Protection
🧷Single-flightone rebuild per key
🔥Hot-key handlingL1 cache, copies
🚦Breaker + limitprotect the database
The client library routes each key to a shard. Each shard has a primary and an async replica. The database is only touched on a miss.
ComponentWhat it does
Client libraryHashes the key, finds the shard from its copy of the map, sends the request, and handles timeouts, retries, batching and a small local cache.
Shard (primary + replica)A primary serves reads and writes for a slice of the keys. An async replica takes over if the primary dies. Replicas can serve reads for non-critical keys.
Slot map or ringSays which shard owns which keys. Versioned, so a client can tell when its map is out of date.
Config serviceA small, reliable store (a consensus system) that holds the map and membership. It is not on the hot path: clients cache the map.
Health checking and failoverDetect a dead primary, promote its replica, publish a new map. Takes a few seconds.
Eviction and expiry (per node)Keep memory under the limit by dropping approximate least-recently-used keys, and remove expired keys.
Stampede and hot-key protectionSingle-flight on a miss, jittered TTLs, a local cache for hot keys, and copies of very hot keys.
DatabaseThe source of truth. Protected by a circuit breaker and a request limit, so a cold or failed cache cannot overload it.
Write path (follow one request)
  1. The application writes the new value to the database first, and waits for it to be committed.
  2. It then calls cache.delete(key) (not set), so the next read rebuilds from the database.
  3. The client library hashes the key and finds the shard that owns it from its slot map.
  4. It sends the delete to that shard's primary, with a short timeout.
  5. The primary removes the entry and streams the change to its replica asynchronously.
  6. If the delete fails, the client retries and records it. The TTL is the safety net if it never succeeds.
Read path (follow one request)
  1. The client library first looks in its small local cache (for keys marked hot).
  2. On a local miss, it hashes the key and finds the shard from its slot map.
  3. It sends get(key) to the primary with a short timeout (about 1 to 2 ms).
  4. The node looks up the key. If the entry exists and has not expired, it updates the access info and returns it.
  5. On a miss, the client takes a single-flight lock for the key, so only one caller reads the database.
  6. That caller reads the database, calls cache.set(key, value, ttl + jitter), and the waiting callers get the same value.
  7. If the shard is down or slow, a circuit breaker opens, and requests go to the database through a limiter.
🎤
Say it out loud
“Here is the picture. App servers use a client library that hashes the key to a shard from a cached slot map. Each shard has a primary and an async replica. A config service holds the map and membership but is off the hot path. On a miss, one caller per key goes to the database, using single-flight, and fills the cache with a TTL plus jitter. On a write, the application writes the database and then deletes the cache entry. Inside each node there is a hash table, approximate LRU eviction and expiry. A circuit breaker and a request limit protect the database when the cache is down.”

Step 5Deep dive into the hard partsabout 15 min

🧠The pattern for every deep dive
Problem → options → pick one → say why → say what it costs. Interviewers score the reasoning more than the choice.
5.1

Partitioning and rebalancing

The problem: 10 billion keys must be spread over 110 shards, found without a central lookup, and adding or removing a node must not empty the cache. A cold cache means the database takes the whole load.

OptionHow it worksGoodBad
hash(key) mod NDivide the hash by the node count and take the remainder.Trivial and even.A new node changes N, so about 99% of keys get a new owner and miss at once. Unusable at this size.
Consistent hashing with virtual nodesNodes and keys sit on a ring. Each machine owns many small tokens. A key goes to the next token clockwise.A new node takes about 1/N of the keys, from many nodes at once. Even load.The client needs the whole ring. Moving data between nodes is a separate job, or you accept misses.
Fixed hash slots (Redis Cluster style)Hash the key into one of 16,384 slots. A table maps slots to nodes. Moving capacity means moving slots.Easy to reason about and to move one slot at a time. Nodes can redirect with MOVED and ASK.Needs the table to be kept correct. Slot count limits the shard count (about 1,000 shards).
A proxy tier that routesClients talk to stateless proxies (twemproxy or mcrouter style), which hold the map and route.Thin, simple clients in any language. One place to change routing, pool connections and cut connection counts.An extra network hop on every request, and the proxies must be scaled and kept available.
Pick
Hash slots (or consistent hashing with virtual nodes) with a smart client, and a proxy tier only for clients that cannot do it

I would use fixed hash slots: every key maps to one of 16,384 slots, and each shard owns about 149 of them. A smart client library keeps the slot map, so there is no extra hop, and it learns of changes from MOVED replies and the config service. Consistent hashing with virtual nodes gives the same property (about 1/N of keys move). Both are far better than mod N. See Consistent Hashing.

When we add a node, we move slots to it a few at a time. For each slot the old owner answers keys it still has, and replies ASK for keys already moved, so the cluster keeps serving during the move. About 96 GB (0.9% of the data) travels, and we can copy it at a limited rate, roughly 200 MB/s, in about 8 minutes, so the new node starts warm instead of empty.

EventWhat happensKeys that become misses
Add a node with mod NAlmost every key changes ownerabout 99% (110 ÷ 111)
Add a node with slots or a ringOnly the slots given to the new node moveabout 0.9% (1 ÷ 111)
Add a node, copy slots firstData is streamed before the owner changesclose to 0%
A node dies, replica promotedReplica has almost all of its dataonly the last few writes
A node dies, no replicaIts slots are empty until refilledabout 0.9%, refilled from the database
⚠️Do the rebalance at a quiet time, slowly
Streaming 96 GB at full speed can starve live traffic on the sending nodes. Limit the copy rate, move one slot at a time, and never rebalance during an incident.
🎤
Say it out loud
“I would not use hash mod N, because adding one node changes about 99% of keys and the cache goes cold. I would use 16,384 hash slots spread over the shards, with a smart client that keeps the slot map. Adding a node moves a few slots at a time, so about 0.9% of the data moves, around 96 GB, and the cluster keeps serving using MOVED and ASK replies. If a client cannot do routing, I would put a thin proxy tier in front, at the cost of an extra hop.”
5.2

Eviction and memory

The problem: The cache is always full, so every insert means dropping something. The method must be O(1), cheap in memory, and good at keeping what will be read again. Expired keys must also be removed without scanning everything.

OptionHow it worksGoodBad
Exact LRU (hash map + linked list)On each access move the entry to the front. Evict from the tail.Exact. Simple to explain, O(1).Two pointers per entry (extra memory), and every read changes shared structures, which needs locking.
Approximate LRU with samplingKeep a last-access time per entry. To evict, sample a few random keys (say 5) and drop the oldest of them.No list, tiny metadata, no write on the read path other than a timestamp. Very close to true LRU.Not exact. Quality depends on the sample size.
LFU (least frequently used)Keep a small, decaying access counter per entry. Evict the lowest counts.Resists scans and one-off bursts that pollute LRU.Needs decay or old popular keys stay forever. Slow to adapt when popularity shifts.
TTL-only (no eviction)Rely on expiry to free memory. Reject writes when full.Predictable.When full, the cache stops accepting new data. Only good for a small, well-bounded set.
Pick
Approximate LRU by sampling, with LFU as an option for scan-heavy workloads, plus lazy and sampled expiry

At 10 billion entries, two list pointers per entry is 160 GB of extra memory, and a lock on every read. Sampling avoids both. Each entry keeps a small access time, and when memory is full we sample a handful of keys and evict the oldest. That is almost as good as exact LRU. See Cache Eviction Policies for the policies and LRU Cache Design for the exact structure.

Expiry uses two tricks together. Lazy: when a key is read and has expired, delete it and return a miss. Active: a background job samples keys that have a TTL, deletes the expired ones, and repeats if many were expired. A timing wheel or a min-heap of expiry times is an alternative that finds the next key to expire directly, at some memory cost.

Memory problemWhat it looks likeFix
FragmentationFree memory exists but is in small gapsSlab classes (fixed chunk sizes), a good allocator, or active defragmentation
Big keysOne 100 MB value blocks the node while it is read or deletedCap value size, split big values, delete lazily in the background
Eviction stormsA scan of rarely used keys pushes out the useful onesLFU, or admission control (only admit a key on its second request)
Memory accountingOverhead is bigger than expected, node runs out of RAMCount overhead per entry, keep headroom (about 10 to 20%), set a hard limit and an eviction policy
🎤
Say it out loud
“Each node is a hash table with a small piece of metadata per entry. For eviction I use sampling: when memory is full, sample a few keys and drop the least recently used of them. It is nearly as good as exact LRU, with no linked list and no lock on the read path, which saves 160 GB of pointers at 10 billion entries. Expiry is lazy, on read, plus a background job that samples keys with TTLs. For scan-heavy workloads I would switch to LFU, or admit a key only on its second request.”
5.3

Hot keys and skew

The problem: Traffic is not even. One celebrity profile, one flash-sale item or one config key can take 10% of all reads. At 90,000 ops/s it uses 90% of one node while the other 109 are nearly idle, and adding nodes does not help because a key lives on exactly one node.

OptionHow it worksGoodBad
Do nothing, buy a bigger nodeGive the hot node more CPU and network.No code change.Does not scale: one key is still bounded by one machine. Expensive.
Local cache in the app server (L1)The client library keeps hot keys in its own memory for a second or two.Removes the traffic before it reaches the network. Near-zero cost. Scales with app servers.Up to a TTL of staleness, and memory on every app server. Invalidation is hard.
Several copies of the hot keyStore the key as key#1 … key#k on different nodes. Readers pick one at random. Writers update all.Spreads reads over k nodes with no staleness beyond replication.Writes cost k times as much. You must know which keys are hot and keep the copy list.
Read from replicasAllow reads to go to the shard's replica as well as the primary.Doubles the read capacity of that shard, with no key changes.Replicas are slightly behind. Only two copies, so a limited gain.
Pick
Detect hot keys, then use a short-lived local cache first, and key copies for the few that stay hot

First find them. Each node can sample a small fraction of requests into a counter (a count-min sketch is a good fit, see Count-Min Sketch), and clients can count what they read. Report the top keys to monitoring and to the client library, which then marks them hot.

For a hot key, the app server serves it from its own memory for about 1 to 2 seconds. With 2,000 app servers, a key with 90,000 reads/s drops to about 2,000 per second (one refresh per server per second), a cut of about 98%. For keys too hot even for that, or too large for L1, keep 4 copies on different nodes, so each takes 22,500 ops/s. Try it in the playground below.

📝The numbers in this example
A key with 10% of 900,000 reads/s is 90,000 ops/s, 90% of one node. With a 1-second local cache on 2,000 servers, the cache sees at most 2,000 reads/s for it. With 4 copies, each node sees 22,500.
⚠️A hot key is also a hot write problem
Counters (likes, views) can be hot for writes. Spread them across sub-keys (counter#1 to counter#16) and add them up when reading, or batch increments in the client.
🎤
Say it out loud
“A hot key is a skew problem, so more nodes do not help: one key lives on one node. I detect hot keys by sampling requests with a small counter and reporting the top few. Then I serve them from the app server's own memory for a second or two. With 2,000 servers a key at 90,000 reads a second drops to about 2,000. For keys that stay too hot, I store four copies on different nodes with key suffixes, so each node takes a quarter. The cost is staleness of a second for the local cache, and four writes for the copies.”
5.4

Failure, stampedes and consistency with the database

The problem: A node can die, and then a slice of the keys misses together and the database takes the load. Separately, the cache can hold stale data after a write. Both must stay bounded, because the cache must make the system faster, never wrong forever or down.

OptionHow it worksGoodBad
Cache-aside with delete on writeWrite the database, then delete the cache entry. Readers refill on a miss.Simple. Cannot leave a wrong value in the cache for long.A small race can refill with stale data. Needs a TTL as a safety net.
Write-throughWrite the cache and the database together, in one code path.The cache is warm after a write.Two writes to keep in step. If one fails, they disagree. Caches data that may never be read.
Write-back (write-behind)Write the cache, and flush to the database later.Very fast writes.Data loss if the cache dies. Not suitable when the cache is not the source of truth.
Invalidation from the database logRead the database change log (CDC) and delete or update cache entries from it.Catches every write, including from other services. Fixes the race.More moving parts. A small delay between write and invalidation.
Pick
Cache-aside, delete after write, a TTL on everything, and single-flight with jitter to survive a lost node

The race to know: reader A misses and reads the old value from the database. A writer then updates the database and deletes the key. Reader A now writes the old value into the cache. It stays wrong until the TTL. This is rare, so we accept it, and the TTL (5 minutes, with jitter) bounds it. If it matters, add a version number to values, or delete again after a short delay, or use database change events (Change Data Capture (CDC)) to invalidate.

When a primary dies, its replica is promoted in a few seconds, and it already has nearly all the data, because replication is asynchronous but fast. We may lose the last few writes, which is fine for a cache. If there is no replica, about 0.9% of keys miss. The danger is the herd: 8,100 reads/s for those keys hit the database, and every popular key is requested by many callers at once. Single-flight lets one caller per key rebuild it, jitter spreads expiry times, and a circuit breaker and rate limit on the database protect it.

FailureWhat users seeWhat protects us
One primary diesA few seconds of errors or misses for 0.9% of keysReplica promoted, client retries, short timeouts
A whole cache tier is downEverything is a missCircuit breaker, request limit on the database, degraded mode (serve stale or reduced features)
Many keys expire togetherA spike of misses (avalanche)Jittered TTLs, staggered warming
One popular key expiresThousands of callers rebuild it (stampede)Single-flight, or serve stale while one caller refreshes
Key that never exists is requestedEvery request goes to the database (penetration)Cache the ‘not found’ answer briefly, or a Bloom filter in front
Single-flight on a miss (idea)
value = cache.get(key)
if value is null:
    if cache.set(key + ":lock", "1", ttl = 5s, if_absent = true):   // only one caller wins
        value = db.read(key)
        cache.set(key, value, ttl = 300 + jitter)
        cache.delete(key + ":lock")
    else:
        wait briefly, then cache.get(key)     // the winner is filling it
🎤
Say it out loud
“The cache is not the source of truth. On a write I update the database and delete the cache entry, and every entry has a TTL as a safety net, so stale data cannot live forever. There is a small race where a slow reader refills an old value, and the TTL bounds it. If a node dies, its replica takes over. If there is no replica, 0.9% of keys miss, so I use single-flight so one caller per key rebuilds it, jittered TTLs so they do not expire together, and a circuit breaker and rate limit in front of the database, so a cold cache cannot take it down.”
VisualizerHot keys and adding a node: where does the load land?Raise the traffic until one node turns red. Then add copies of the hot keys or turn on the local cache and watch the busiest node cool down. Below, see how many keys move when you add a node: hash mod N versus consistent hashing.
Local cache in each app server (hot keys only)
Load on each cache node. The line is one node's limit (100k ops/s). Red = the 5 hottest keys, cyan = all other keys.
Node 1
34k
Node 2
113k
Node 3
48k
Node 4
42k
Node 5
90k
Node 6
74k
Busiest node
113k
ops/s
Average node
67k
ops/s
Imbalance
1.69×
busiest ÷ average
Over the limit
1
nodes
One node is over its 100k ops/s limit, while the average node is only at 67k. The 5 hottest keys take 48% of all traffic, and the single hottest key alone takes 21%. Adding nodes does not help much, because a key lives on exactly one node. Try more copies of the hot keys, or turn on the local cache.
What does adding one node cost? (6 → 7 nodes)
hash(key) mod N
Almost every key changes node: 6 ÷ 7 = 85.7% of keys move.
Of 100 million keys, about 86 million are suddenly misses. The database takes the hit.
Consistent hashing
Only the new node's slice moves: 1 ÷ 7 = 14.3% of keys.
Of 100 million keys, about 14 million are misses, and they are taken a little from every node.

A simplified model with fixed numbers and no random values. 64 keys with a Zipf-like popularity (key number n gets a share proportional to 1 ÷ n). Each key has a fixed home node from an integer hash. Extra copies of a hot key go on the next nodes in order, as if the key were stored with the suffixes #1, #2 and so on. The 100k ops/s limit and the 100 million key count are illustrative assumptions, not measurements. A real cluster also spreads a node's copies across racks.

Step 6Scale, bottlenecks and failuresabout 8 min

🤔
Pause. Try it yourself first
If traffic doubles, what breaks first? If one shard dies, what does the database see? If a deploy restarts every cache node, then what?

What breaks first, and the fix

BottleneckFix
A hot key saturates one nodeDetect with sampling. Serve from a short local cache, keep several copies, or read from replicas.
The database is overloaded after a cold start or node lossSingle-flight, jittered TTLs, request limit and circuit breaker, and warm the cache before taking traffic.
Connection count (1.1 million in total)Pool and reuse connections, use a proxy tier to multiplex, and keep client timeouts short.
Network bandwidth on a busy nodeCompress large values in the client, spread hot keys, and use fewer, larger batches.
Memory fragmentation and big keysSlab classes or a good allocator, defragmentation, a value size cap, and background deletes.
Tail latency from batch gets across many nodesA batch of 100 keys on many nodes waits for the slowest one (about 63% of such batches see a 1-in-100 slow node). Send in parallel, use timeouts, and hedge slow requests.
Slot or ring map is out of date on some clientsVersion the map, return MOVED redirects, and refresh from the config service on any redirect.

What if a part fails?

FailureHow the design copes
A primary node diesHealth check fails, replica is promoted in seconds, the map is updated, and clients follow MOVED. Last few writes may be lost, which is acceptable.
A primary and its replica both dieTheir slots miss until reassigned. The database absorbs about 0.9% of keys, protected by single-flight and limits.
A whole zone is lostPrimaries and replicas are placed in different zones, so replicas take over. Capacity headroom must cover it.
A network partition isolates a primaryClients behind it time out and use the database. The replica side may be promoted, so the old primary must stop accepting writes after a lease ends (to avoid two primaries).
The config service is downClients keep using their cached map. Only topology changes stop, because the hot path does not need the service.
A bad deploy restarts all nodes at onceRoll out a few nodes at a time, drain first, and never restart a primary and its replica together.
What to monitor
  • •Hit ratio, per cluster and per tenant. A drop of a few points is the earliest warning for the database.
  • •Latency p50, p99 and p99.9 for get and set, per node, and the client-side timeout and retry rates
  • •Evictions per second and memory use: evictions with a low hit ratio mean the cache is too small
  • •Per-node and per-key load, with the top hot keys, and the imbalance between the busiest node and the average
  • •Replication lag, failovers, and the number of MOVED and ASK redirects
  • •Database load behind the cache, and the circuit breaker state
Security and abuse
  • •Authenticate clients and encrypt traffic with TLS. Keep the cache on a private network, never on the public internet.
  • •Separate tenants with key prefixes and permissions, and give each tenant a memory quota and a rate limit.
  • •Do not put secrets or raw sensitive data in values. If you must, encrypt them in the client with keys held in a key management service.
  • •Protect the admin commands (flush, config, key listing), because a flush-all command empties the whole cache.
  • •Limit key and value sizes, so one client cannot fill memory or block a node with a huge value.

Step 7Wrap upabout 3 min

A sharded in-memory cache: 16,384 hash slots over about 110 primaries, each with an async replica, routed by a smart client from a slot map held in a config service. Entries sit in a hash table with approximate LRU eviction and lazy plus sampled expiry. Hot keys are served from a short local cache or from several copies. The application uses cache-aside with delete on write and a TTL on every key, and single-flight, jitter and a circuit breaker keep the database safe when a node is lost.

Trade-offs you made

DecisionWhat we gainWhat it costs
A cache, not a store (async replication, no persistence)Fast, simple, cheap failover.Data can be lost and reads can be stale, so everything must be rebuildable.
Hash slots with a smart clientNo extra hop and about 1% of keys move when a node is added.Clients carry routing logic and must handle redirects and map updates.
Approximate LRU by samplingNo list pointers (160 GB saved) and no lock on reads.Slightly worse eviction than exact LRU.
Local cache and copies for hot keysA hot key stops overloading one node.Seconds of staleness, extra memory, and more writes for copies.
Delete on write plus a TTLSimple, and wrong data is bounded by the TTL.A small race can refill a stale value, and the database sees more misses.
Single-flight and jitterA lost node or a popular expiry does not flood the database.Waiting callers see a little extra latency.
If we had more time, we would…
  • •Automatic hot-key detection that rewrites routing for those keys without a deploy.
  • •Tiered storage: RAM for hot data and fast flash for the warm tail, to cut cost.
  • •Cross-region invalidation stream, so regional caches stay close to the database.
  • •Warm-start from snapshots and a warm-up job after a restart.
  • •Per-tenant admission control and eviction policy to stop noisy neighbours.
🎤
Say it out loud
“To recap: about 110 shards with hash slots and async replicas, a smart client, approximate LRU eviction, and TTLs on everything. Hot keys are served locally or from several copies. The application writes the database and deletes the cache entry, and single-flight, jitter and a circuit breaker protect the database when a node fails. The trade-off is that the cache can lose data and be briefly stale, which is the right choice for a cache. With more time I would add automatic hot-key handling and a warm-start path.”

Q&ACross-questions (22)

💡How to practise
Cover the answer. Say yours out loud in 30 to 60 seconds. Then open the model answer, the follow-up, and the weak answer to see what to avoid. Use Open all at the top for a quick read.
Warm-upProbingCurveballWarm-up = basics. Probing = tests depth. Curveball = changes the problem.

Cache basics and design

Show that you know what a cache is, and is not.

Eviction, memory and performance

Where interviewers check that you know how a cache node really works.

Hot keys, failures and stampedes

The part where the cache breaks. Know the names and the fixes.

Consistency and curveballs

Stale data, races and the questions that change the problem.

What ifIf the interviewer changes the problem

A change in requirements is a test of whether you understand why your design looks the way it does.

New requirementWhat changes in the design
Strong consistency is required, not just a cacheThat is a database. Use a replicated store with a consensus protocol, as in the key-value store design. Keep the cache only for data that can be stale.
Multi-region, with a cache in each regionEach region has its own cache, filled from its local database replica. Send invalidations through a stream (database change events) and accept short staleness between regions.
The data set is 100 times larger than RAM allowsAdd a second tier on fast flash for the warm tail, with RAM for the hot set. Use admission control so rarely used data stays out.
Values are very large (video chunks, big objects)Use a CDN or an object store cache, not RAM. Chunk the values and cache chunks, with a different eviction policy such as size-aware.
Hot keys are extremely hot (a viral event)Switch on local caches with short TTLs for those keys at once, add copies, and put a request coalescing layer in front. Pre-warm the key before an expected event.
Writes are much heavier than readsA cache helps less. Consider write-behind with a buffer, batching, or caching only derived read models. Check whether the cache is worth its cost.
Data must survive a cache restartAdd periodic snapshots and an append-only log, and replica warm-up. Accept a slower restart. Or use a store designed for durability.
Counters and rate limits live in the cacheUse atomic increments on one node per counter, sub-keys for very hot counters, and short TTLs. Accept that a node loss resets the counters.

ScoreHow answers are judged

AreaWeakGoodGreat
RequirementsStarts with ‘use Redis’. Does not ask about staleness or what happens when the cache is down.Asks about scale, size, staleness and failure behaviour.States early that it is a cache and not a store, and ties every later choice to that.
EstimationNo numbers, or a node count with no basis.Working set, overhead, node count, ops per node, hit ratio and database load.Shows that memory sets the size, that a hit-ratio point is worth 9,000 database reads a second, and sizes the cost of adding a node.
PartitioningHash mod N, or ‘the cache handles it’.Consistent hashing or slots, and what a new node costs.Compares slots, rings and proxies, explains MOVED and ASK, and gives the percentage of keys moved.
Eviction and memory‘LRU’ and nothing more.Explains LRU, LFU and TTL expiry.Explains sampled LRU, lazy plus active expiry, fragmentation and why exact LRU costs too much at this size.
Hot keys and failure‘Add more nodes’, or ignores node failure.Names stampede, penetration and avalanche, and gives a fix for each.Detects hot keys, uses L1 and copies with numbers, and protects the database with single-flight, jitter and a breaker.
CommunicationLists components without trade-offs.Follows the seven steps and explains choices.States the cost of every choice, checks in, and handles curveballs calmly.

AvoidCommon mistakes on this question

MistakeDo this instead
Treating the cache as a database, with quorums and durabilitySay it is a cache, the database is the truth, and use async replication only for fast failover.
Using hash mod N for partitioningUse slots or consistent hashing, and quote the number: about 1% of keys move, not 99%.
Ignoring hot keysSay that skew, not average load, breaks a node, and describe detection plus a local cache or copies.
No plan for a cold or failed cacheExplain single-flight, jittered TTLs, a circuit breaker and a request limit on the database.
No TTL on cached entriesGive every key a TTL as a safety net, with jitter, so wrong data cannot live forever.
Updating the cache on write instead of deletingWrite the database, then delete the key. Updating needs the right value in two places and races more.
Exact LRU with a linked list at huge scale, with no cost estimateShow the pointer overhead, and use sampling. Mention LFU for scan-heavy loads.
Putting the cache in front of everything, including data that is read onceCache only data with repeat reads, and use admission control so one-off keys do not pollute the cache.

Revise60-second revision sheet

  • ✔Cache vs store: a cache may lose data and be stale. The database is the truth. Async replication only for fast failover.
  • ✔Size: 10 TB + 640 GB overhead, 100 GB per node = about 110 primaries, plus replicas. Memory sets the size, not CPU.
  • ✔Database load: each hit-ratio point is worth 9,000 reads/s at 900,000 reads/s. 95% hits leaves 45,000 reads/s.
  • ✔Partitioning: 16,384 hash slots (or a ring with virtual nodes) and a smart client. Adding a node moves about 1/N of keys, not (N−1)/N.
  • ✔Eviction: approximate LRU by sampling (no list, no lock). LFU for scans. Expiry is lazy plus a sampled sweep.
  • ✔Hot keys: detect by sampling. Serve from a short local cache (1 to 2 s) or keep k copies with key suffixes.
  • ✔Stampede: single-flight, stale-while-revalidate, jittered TTLs. Penetration: cache ‘not found’ or use a Bloom filter.
  • ✔Consistency: write the database, then delete the key. TTL as a safety net. A rare race can refill an old value.
  • ✔Failure: replica promoted in seconds. Short client timeouts, a circuit breaker and a request limit protect the database.
  • ✔One line: “It is a cache, not a store: keep it fast, bounded and rebuildable, and never let its failure become the database's failure.”

Read these topics next

Consistent Hashing→

The ring and slots that stop a new node from flushing the cache.

Cache Eviction Policies→

LRU, LFU and the others, and how to choose.

LRU Cache Design→

The exact hash map plus linked list structure, and why sampling replaces it at scale.

Hot Keys→

Detecting and spreading the keys that overload one node.

Cache Stampede→

Single-flight and stale-while-revalidate in depth.

Cache Penetration and Cache Avalanche→

The other ways a cache fails and how to stop them.

Distributed Cache Architecture→

The concept page behind this design.

Design a Key-Value Store→

The durable, replicated cousin: when the data must not be lost.

← Previous
Design Video Streaming (YouTube/Netflix)
Next →
Design a Leaderboard