Design a Distributed Cache
Almost every system design answer says put a cache in front of it. This lesson designs that cache: an in-memory cluster that shards keys across nodes, evicts the right data, survives node failures and copes with the hot keys and stampedes that take real systems down. It covers the full 45-minute interview answer.
What you will learn
- Clarify the caching pattern first: cache-aside, read-through, write-through or write-behind.
- Shard with consistent hashing so adding or losing a node moves only a slice of keys.
- LRU with sampling is a cheap, good default; TTLs bound staleness.
- Replicate each shard to a standby and fail over automatically, accepting a few lost writes.
- Hot keys need local caching or key replication; stampedes need request coalescing and jittered expiry.
- Invalidate on write by deleting the key, and keep TTLs as the safety net.
In this lesson
- The question
- Step 1: Clarify the requirements
- Step 2: Back-of-the-envelope estimates
- Step 3: The interface
- Step 4: How applications use a cache
- Step 5: Sharding and routing
- Step 6: Memory and eviction
- Step 7: Replication and failover
- Step 8: Hot keys and stampedes
- Step 9: Keeping the cache honest
- Step 10: Regions, security and operations
- Step 11: The follow-up questions
- Recap
Short on time? Read the answer outline for design a Distributed Cache.
Practice this question with MaxThe question
Welcome to lesson five of the InterviewDryRun system design course. In almost every design so far, we have said: and put a cache in front of it. Today we open that box and design the cache itself: an in-memory store, spread across many machines, that answers in well under a millisecond.
A cache sounds simple: keep recent answers in memory so you do not have to compute or fetch them again. But at scale, a cache becomes one of the most critical parts of the system. When it is healthy, the database behind it sees a tiny fraction of the traffic. When it fails, or when one key gets very hot, the full load lands on a database that was never sized for it, and everything falls over at once. So the interview is really about two things: speed, and what happens when things go wrong.
Max asks
“Design a cache cluster like the popular in-memory stores: sharding, eviction, replication and hot keys.”
That is how Max, our AI interviewer, asks it. The question even lists the four topics it wants: sharding, eviction, replication and hot keys. That is a gift. Make sure each one gets its own clear part of your answer, and add the ones it did not mention, like stampedes and consistency with the database, because those are where real outages come from.
The plan: requirements, sizing and the interface. Then how applications use a cache, because that shapes everything. Then the cluster: sharding and routing, memory and eviction, replication and failover. Then the hard production problems: hot keys, stampedes and keeping the cache consistent with the database. And finally, the follow-up questions.
Step 1: Clarify the requirements
- 01get, set, deleteValues up to about 1 MB, most under 1 KB
- 02Time to liveEach key can expire after a set time
- 03Atomic countersIncrement without read-modify-write races
- 04Evict when fullDrop the least useful keys automatically
As always, start with what the cache must do. The core is three operations: get a value by key, set a value with an optional time to live, and delete a key.
Ask about value sizes. Typical cached values are small, a serialized user profile or a rendered page fragment, under a kilobyte, with a ceiling of about a megabyte. Ask whether we need a few richer operations. Atomic increments are almost always wanted, for counters and rate limiting. Lists and sets are nice to have; say you will support increments and keep the rest out of scope.
And the defining property of a cache: when it is full, it throws data away by itself. Unlike a database, losing data is allowed. That one fact simplifies a lot of the design, and you should say it explicitly: everything in the cache can be rebuilt from the source of truth.
- 01Very low latencyUnder 1 ms at the 99th percentile, in the same data centre
- 02High throughputMillions of operations a second across the cluster
- 03Scales outAdd nodes to add memory and throughput
- 04Survives node lossLosing one node must not overload the database
The qualities. Latency first: well under a millisecond, which means everything is in memory, and one network hop. And very high throughput, millions of operations a second, because the whole point is to absorb traffic that would otherwise hit the database.
It must scale out by adding nodes. And here is the subtle requirement. Although losing cached data is allowed, losing a large chunk at once is dangerous, because all those requests suddenly fall through to the database. So availability matters for a different reason than usual: not to protect the data, but to protect what sits behind the cache.
Step 2: Back-of-the-envelope estimates
Let us size it.
Say five million operations a second, mostly reads. The number that matters most is the hit ratio. At ninety-five percent, the database still sees two hundred and fifty thousand reads a second. At ninety-nine percent, only fifty thousand. So every point of hit ratio is a big change in database load. Say that: a cache's job is measured by its hit ratio.
Memory: say the working set, the data that is actually being used, is two terabytes. With sixty-four gigabytes of usable memory per node, that is about thirty-two nodes. Each then handles around a hundred and fifty thousand operations a second, which a single well-written server can do comfortably.
Add one replica per shard, for failover, and we are at about sixty-four nodes. So the cluster is tens of machines, and the main design problems are routing keys to the right node and surviving the loss of any of them.
And a quick check on the network, because caches often hit network limits before memory or CPU. A hundred and fifty thousand operations a second, at an average of one kilobyte, is about a hundred and fifty megabytes a second per node, more than a gigabit link can carry. So we need ten gigabit networking, and we should watch for large values, because a few big ones can saturate a node's network card while its CPU sits idle.
Step 3: The interface
get(key) → value | miss mget(keys[]) → values, one round trip set(key, value, ttl) set(key, value, ttl, ifVersion = 41) delete(key) incr(key, by = 1) → new value // keys are namespaced: "profile:v3:user:8812"
The interface is small, but a few details in it matter. Get, set with a time to live, delete and increment are the core. Add a multi-get, which fetches many keys in one round trip, because a single page often needs dozens of cached values, and dozens of sequential round trips would add up to real latency.
Add a conditional set, which only writes if the stored version matches, because we will need it later to avoid stale values. And make increment atomic on the server, so counters never lose updates when many app servers increment at once.
Finally, a convention rather than an operation: namespace every key, with the kind of data and a schema version, like profile, version three, user eight eight one two. When the format of cached profiles changes, you bump the version in the key, and every old entry simply stops being read and expires on its own. That avoids a dangerous moment where new code reads old-format values. Interviewers rarely ask about it, which is exactly why mentioning it stands out.
Step 4: How applications use a cache
| Pattern | Read | Write |
|---|---|---|
| Cache-aside | app checks cache, then database, then fills cache | app writes database, deletes cache key |
| Read-through | cache loads from database itself | same as cache-aside |
| Write-through | from cache | write cache and database together |
| Write-behind | from cache | write cache now, database later |
Before the cluster, be clear about how the application uses it, because interviewers often ask, and the answer changes how we handle consistency.
The most common pattern is cache-aside. On a read, the application checks the cache. On a miss, it reads the database and puts the result in the cache. On a write, it updates the database and deletes the cached key, so the next read fetches the fresh value. The cache knows nothing about the database. That simplicity is why it is the default.
Read-through moves the loading into the cache layer: the application only talks to the cache, and the cache fetches from the database on a miss. It is cleaner for applications, but the cache now needs to know about every data source.
Write-through writes to the cache and the database together, so the cache is always fresh, at the cost of slower writes. And write-behind writes to the cache immediately and to the database later, in batches. It is very fast, but if the cache node dies before flushing, writes are lost. So write-behind is only for data where that is acceptable, like counters or analytics.
For our design, say: the cluster supports any of these, but I will assume cache-aside, with deletes on write and a time to live on every key. That keeps the cache a pure, disposable copy, which is what makes the rest of the design simple.
value = cache.get(key)
if value is missing:
value = db.read(key)
cache.set(key, value, ttl = 10 minutes)
return value
on update:
db.write(key, newValue)
cache.delete(key) // not cache.setHere it is in a few lines. Notice the write path deletes the key instead of setting the new value. That is deliberate, and interviewers sometimes ask why. If two writers update the database and then each set the cache, they can set it in the opposite order, leaving the old value cached indefinitely. Deleting avoids most of that race, because the next reader always fetches whatever the database holds now.
Step 6: Memory and eviction
| Policy | Keeps | Weakness |
|---|---|---|
| LRU | recently used keys | one big scan pushes out hot keys |
| LFU | frequently used keys | old favourites linger |
| TTL only | whatever has not expired | memory fills before expiry |
| Random | nothing in particular | cheap, surprisingly decent |
Inside each node, everything lives in memory, in a hash table from key to value. The interesting part is what to throw away when memory is full.
The classic answer is least recently used. Keep keys in a linked list ordered by last access; on every read, move the key to the front; when full, evict from the back. It works well because recently used data tends to be used again. Its weakness: a one-off scan over many keys pushes out genuinely hot data.
Least frequently used keeps keys that are accessed often, which resists scans, but a key that was popular yesterday can linger long after nobody wants it. Practical versions decay the counts over time, which fixes that.
And there is a practical trick worth mentioning. Maintaining an exact list costs memory and locking on every read. Many real caches approximate it instead: sample a handful of random keys and evict the least recently used among them. With a sample of five or ten, the result is very close to true least recently used, at a fraction of the cost. That kind of detail tells the interviewer you have thought about the implementation, not just the textbook.
- 01Slab allocationSize classes avoid fragmentation
- 02Compress large valuesTrade CPU for memory
- 03Expire lazily and activelyOn read, plus a background sweep
- 04Keep headroomNever run a node at 100% memory
Memory management matters too. Values come in all sizes, and constant allocating and freeing fragments memory, so a node with sixty-four gigabytes might only fit fifty. Allocating from fixed size classes, slabs, keeps fragmentation low.
Expired keys must actually be removed. Check expiry when a key is read, which is free, and also run a background job that samples keys and deletes expired ones, so keys that are never read again do not sit in memory forever.
And never plan to run nodes at full memory. Keep headroom for replication buffers, traffic spikes and the extra copy of memory some systems need while taking a snapshot. Running at about seventy percent is a reasonable target.
Step 7: Replication and failover
Why replicate a cache at all, if the data can be rebuilt? Because of what we said at the start: if a node with one thirty-second of the keys dies, all of that traffic misses, and a few hundred thousand extra reads a second hit the database at once. Replication is about protecting the database from a sudden cold cache.
Each shard has a primary that takes writes, and a replica that receives a stream of every change. Replication is asynchronous, so writes stay fast. The replica can also serve reads, if the application can tolerate slightly stale values, which doubles read capacity.
A group of watchers checks the primaries. If a majority of them agree a primary is unreachable for a few seconds, they promote its replica and update the cluster config, and clients follow the new map. Requiring a majority prevents one watcher with a bad network link from causing an unnecessary failover.
Say the cost clearly: with asynchronous replication, the last few writes before the failure may be lost. For a cache, that is fine, because those values are still in the database. This is a nice contrast with the key-value store lesson, where losing writes was not acceptable. The same mechanism gets a different answer because the data has a different role.
Also mention persistence. Should a cache write to disk at all? Optionally, yes: a periodic snapshot lets a restarted node come back warm instead of empty, which again protects the database. But it is a convenience, not a durability guarantee, and the system must work if every snapshot is lost.
Step 8: Hot keys and stampedes
- 01The problemOne key, one shard, 500,000 reads a second
- 02Local cacheKeep the hottest keys in each app server for a few seconds
- 03Key copiesStore key#1 to key#8 on different shards; read one at random
- 04Detect itSample traffic to find hot keys automatically
Now the problems that cause real outages. First, the hot key. Sharding spreads keys evenly, but traffic is not even. A celebrity's profile, or a flash-sale product, can get half a million reads a second, and every one of them goes to the single shard that owns that key. Adding shards does not help, because one key lives on one shard.
The most effective fix is a small local cache inside each app server, holding the hottest few thousand keys for a few seconds. Hundreds of app servers each serve the hot key from their own memory, and the shard sees only one request per server every few seconds. The cost is a few seconds of staleness, which is almost always fine for hot, popular data.
Another fix is to store several copies of the hot key under different names, key one to key eight, which hash to different shards, and have readers pick one at random. Writes must update all copies. And either way, you need to know which keys are hot, so sample traffic in the client library or on the nodes and flag keys above a threshold automatically.
- 01The problemA hot key expires; 10,000 requests miss at once
- 02Request coalescingOne fetch per key; others wait for it
- 03Jittered TTLs10 minutes plus or minus 1, so keys expire apart
- 04Early refreshRefresh shortly before expiry, in the background
Second, the stampede, also called the thundering herd. A hot key expires. In the next ten milliseconds, ten thousand requests miss, and all ten thousand go to the database to rebuild the same value. The database slows, the rebuilds take longer, more requests pile up, and it spirals.
The fix is request coalescing. Only the first request that misses a key fetches it from the database; the others wait for that one result. This can be done in each app server, or across the cluster with a short lock key in the cache itself: whoever manages to create the lock fetches, and the others briefly wait or serve the old value.
Two cheaper protections help too. Add random jitter to expiry times, so keys written together do not all expire together. And for hot keys, refresh the value in the background shortly before it expires, so it never actually goes missing. With these three in place, a key expiring is a non-event.
There is a cousin of the stampede after a full cache restart, called a cold start. Every key misses at once. Protect against it by warming the cache before it takes traffic, from a snapshot or by replaying recent reads, and by bringing nodes back gradually rather than all at once.
Notice the common theme across hot keys, stampedes and cold starts. In each case the cache itself is fine, but a burst of identical requests overwhelms one point, either a shard or the database. So the general defence is the same: collapse identical work into one request, and spread unavoidable work out over time.
Step 9: Keeping the cache honest
Reader A: cache miss, reads db → old value Writer B: writes db new value, deletes cache key Reader A: sets cache = old value // stale! Fixes: short TTL on every key (bounds damage) versioned set: only if version is newer delete again a moment after writing (delayed double delete)
Last hard topic: consistency between the cache and the database. Even cache-aside with delete-on-write has a race, and interviewers love to ask about it. A reader misses, reads the old value from the database, and is slow. Meanwhile, a writer updates the database and deletes the key. Then the slow reader finally puts the old value into the cache. Now the cache holds a stale value until it expires.
How much does it matter? Ask the interviewer. For most data, the time to live bounds the damage: stale for at most ten minutes, then corrected. That is the first and most important answer: every key has a time to live, as a safety net for every bug and race we have not thought of.
If we need better, there are two common fixes. Store a version with each value, and only allow a set if its version is newer than the one in the cache. Or delete the key a second time a short while after the write, which cleans up after any slow reader. And for the most important data, invalidate from the database's change stream: a small service reads every committed change from the database's log and deletes the matching cache keys. That catches updates from every writer, even ones that forgot to delete.
Say one more principle. Never use the cache as the only place a piece of truth lives, unless you have designed it as a database. If losing the cache would lose information, you have built a database with weak durability, and you should say so and choose differently.
Step 10: Regions, security and operations
- 01One cluster per regionNever read a cache across an ocean
- 02Invalidate everywhereBroadcast deletes from the change stream to each region
- 03Lock it downPrivate network, auth, encryption in transit
- 04Big keysFind and split values over a megabyte
A few operational points round off the answer. First, regions. A cache read that crosses an ocean takes a hundred milliseconds, which defeats the purpose. So each region gets its own cache cluster, filled from its local database replica. They are independent copies, not one cache stretched across the world.
That raises invalidation: when data changes in one region, every region's cache must drop the key. The change stream we described earlier is the right tool: each region runs a small consumer that deletes keys as changes arrive. Until the delete arrives, a region may serve a slightly old value, bounded by the time to live as always.
Security is often forgotten for caches, because they live inside the network. But caches hold sessions, tokens and personal data. Keep them on a private network, require authentication, and encrypt traffic between app servers and cache nodes. An open cache port reachable from the internet is a classic, and very costly, mistake.
And watch for big keys. One value of tens of megabytes, say a huge list that keeps growing, blocks a node while it is read or written, and moving it during a resharding stalls everything behind it. Scan for large keys regularly, and split them into smaller pieces. A single oversized key can hurt latency for every other key on its node.
Step 11: The follow-up questions
Max asks
“You add four nodes to a busy cluster. What happens to the hit ratio while keys move?”
With slots, only the moved slots are affected, and the move copies keys before switching ownership, so most reads still hit. Add nodes one at a time, and move a few slots at a time, so the extra misses are spread out. The important point is that we never remap the whole key space, which with modulo hashing would have dropped the hit ratio to nearly zero.
Max asks
“The whole cache cluster is down. What happens?”
Every request goes to the database, which was sized for five percent of reads, so it will be overwhelmed. Protect it with load shedding and circuit breakers in the app: serve fewer pages, return defaults for non-essential data, and limit concurrent database reads. Then warm the cache gradually. The real answer is to avoid this state: spread shards and replicas across zones, so no single failure takes everything.
Max asks
“Would you cache in the app server's memory instead of a separate cluster?”
For small, hot, rarely changing data, yes, it is the fastest possible cache. But each server has its own copy, so memory is multiplied by the number of servers, hit ratios are lower because each server sees only its own traffic, and invalidation is harder. Use both: a small local cache for the hottest keys, in front of the shared cluster for everything else.
Max asks
“How would you know the cache is working well?”
Measure hit ratio per key prefix, latency at the ninety-ninth percentile, evictions per second, memory used, and the number of hot keys. A falling hit ratio or rising evictions mean the cache is too small. Rising latency usually means a hot key or a node in trouble. And watch database load next to it, because that is what the cache exists to protect.
Recap
- 010 to 5: requirementsget, set, delete, TTL; sub-millisecond; losing data is fine
- 025 to 10: estimates and patterns5 M ops a second, 2 TB; cache-aside with deletes
- 0310 to 20: the clusterSlots, smart client, LRU with sampling
- 0420 to 30: replicationAsync replica, quorum failover, snapshots
- 0530 to 45: production problemsHot keys, stampedes, stale values, cold start
Here is the forty-five minutes. Five minutes of requirements, landing on: fast, scalable, and data that can be thrown away. Five minutes of numbers and patterns: millions of operations, terabytes of memory, cache-aside with deletes.
Ten minutes on the cluster: slots or a hash ring, a smart client, and eviction with sampled least recently used. Ten minutes on replication and failover, with the clear point that we replicate to protect the database, not the data.
And fifteen minutes on what really breaks caches in production: hot keys, stampedes, stale values and cold starts. Interviewers remember candidates who talk about these without being asked, because those are the problems that wake people up at night.
It is one thing to know what a stampede is. It is another to explain the fix clearly while someone asks what happens if the lock holder dies. You can practice this exact question with Max, our AI interviewer, at interview dry run dot com. It is free to start, and you get a scored report with what to fix. The written lesson, with every diagram, is on the site too. See you in lesson six.
Now say it out loud
Watching an answer is not the same as giving one. Max asks this exact question, pushes back when an answer is vague and keeps time, then scores you per skill.
Practice with MaxFree: a 5-minute voice round and unlimited typed drills, with scored feedback. No card, and your camera is never recorded.