Skip to content

Design a Distributed Cache

A system design interview walkthrough for a distributed cache, covering hash slots, resharding, replicas, hot keys, eviction and node-loss recovery.

Intermediate23 minUpdated 2 December 2026

Before this: Caching, Consistent Hashing

"Design a distributed cache" is a question about building the cache, not about using one. If you answer with "put Redis in front of the database and use cache-aside", you have described the caching lesson, which covers placement, write strategies and the stampede, penetration and avalanche failures. The interviewer wants the other half: how does the cache itself scale to many machines and survive losing some of them?

That turns the question into three smaller ones. How does a client find which node holds a key? What happens to the cache when you add or remove a node? And what do you do about the key that is too popular for any one machine? Candidates who answer these with numbers, rather than slogans, stand out.

We will design a cluster of in-memory nodes with a client library, then argue for the choices.

Clarify the requirements

Functional requirements:

  1. get(key), set(key, value, ttl) and delete(key), with values up to 1 MB and typically a few hundred bytes.
  2. Entries expire after a TTL, and when memory is full the cache evicts entries on its own.
  3. The cluster scales out by adding nodes, with no downtime.
  4. It survives the loss of a node without taking the database down.

Out of scope, said aloud: persistence guarantees (the cache is not the source of truth), complex data structures, multi-key transactions, cross-region replication.

Non-functional requirements:

  • Very fast: under 1 ms server-side, 2 to 3 ms including the network, p99.
  • High hit ratio: the database must see a small fraction of the read load, because the cache exists to shield it.
  • Available: a cache outage must not become a database outage, so the failure behavior is part of the requirements.
  • Elastic: adding capacity must not empty the cache.

Estimate the scale

Assume 400 million cached items averaging 500 bytes plus about 100 bytes of per-item overhead (key, TTL, bookkeeping), and a peak of 300,000 operations per second at 90% reads.

Working set: 400M × 600 B = 240 GB in memory.

Node count: a 64 GB machine should give the cache about 48 GB, leaving space for the OS and for memory fragmentation. 240 GB ÷ 48 GB = 5 nodes at 100% fill. Run at about 60% so growth and fragmentation do not cause evictions: 8 primary nodes, each holding 30 GB.

Throughput per node: 300,000 ÷ 8 = 37,500 operations per second, comfortably under what one command thread can serve (on the order of 100,000 simple operations per second).

Reads and writes: 270,000 reads and 30,000 writes per second at peak.

Database load, with and without the cache: at a 95% hit ratio the database sees 5% × 270,000 = 13,500 reads per second. With no cache it would see 270,000, twenty times more.

Network: 300,000 × 600 B = 180 MB/s, about 22 MB/s per node, which is trivial.

"Memory, not throughput, sets the node count: 240 GB of working set means eight nodes with room to spare. The more important number is the 20× between 13,500 and 270,000: lose the cache and the database cannot cope. So the design is judged by how it behaves when nodes fail and when it resizes, not by raw speed."

The capacity estimator reproduces the average rates (10,000 writes and 90,000 reads a second). Ignore its storage line: a cache holds a working set, not everything ever written.

API and data model

GET    /cache/{key}                      -> value | 404
PUT    /cache/{key}   ?ttl=300  <value>  -> 204
DELETE /cache/{key}                      -> 204
node:    hash table  key -> (value, expires_at, last_access, frequency)
cluster: 16,384 hash slots;  slot = CRC16(key) mod 16384
map:     slot -> primary node (+ replica);  versioned, held by every client and node

The slot is the unit of placement and of movement. Keys never map directly to nodes, only to slots, and slots map to nodes. That indirection is the answer to most of what follows.

High-level design

The slice to simulate is the read path: application servers read a replicated cache and fall back to the database on a miss.

Application servers read a replicated cache with LFU eviction and a TTL, and fall back to the database on a miss.clientsapp serverscache clusterdatabase
Application servers read a replicated cache with LFU eviction and a TTL, and fall back to the database on a miss.
  • The application's cache client maps each key to a slot and each slot to a node.
  • The cache holds hot entries in memory with a default TTL and evicts the least frequently used when full.
  • On a miss, the application reads the database and fills the cache.
Describe this diagram

Components

  • clients (Client)
  • app servers (Service)
  • cache cluster (Redis)
  • database (PostgreSQL)

Connections

  • clients sends to app servers
  • app servers sends to cache cluster
  • app servers sends to database

Run it, then try shrinking maxmemory to force evictions, setting the TTL very short or switching the eviction policy, and watch how many reads reach the database.

The read path: the client hashes the key to a slot, looks up the node in its slot map and sends one request. A hit returns in a millisecond. A miss returns nothing, the application reads the database and writes the value back with a TTL.

The write path: the application updates the database first, then deletes (or overwrites) the cache entry. The primary node replicates the change to its replica asynchronously.

The interesting problem: finding the key, and changing the cluster

Placement decides whether growing the cache is routine or an outage.

Approach A: hash(key) mod N

Pick the node by taking the key's hash modulo the number of nodes.

Good: trivial, no lookup table, perfectly even.

Bad: when N changes, almost every key moves. Going from 8 to 9 nodes, only about 1 key in 9 keeps its node, so roughly 89% of the cache becomes misses at once. The database suddenly sees close to the full 270,000 reads per second, which is the 20× event the whole design exists to prevent.

Approach B: a consistent-hash ring

Place nodes (with many virtual points each) on a ring and give each key to the next node clockwise. The consistent hashing lesson shows why only about 1/9 of the keys move when a ninth node joins.

Good: adding a node invalidates around 11% of keys instead of 89%. Each client can compute placement alone.

Bad: every client must hold the same ring, and clients with different views disagree about where a key lives, producing duplicate entries and stale reads. Moving ranges between nodes is awkward, and you cannot rebalance a single slice without changing virtual point counts.

Approach C: fixed hash slots with a versioned map

Divide the key space into a fixed number of slots, 16,384, and assign each slot to a node. To add a node, move a number of whole slots to it, one slot at a time, while the cluster keeps serving.

Good: adding the ninth node means moving about 16,384 ÷ 9 ≈ 1,800 slots, and each slot is migrated key by key. During a move, the old node answers for keys it still has and redirects the client for keys already moved (a MOVED or ASK reply). Clients update their map from the reply. The cache never goes cold all at once, and you control the pace.

Bad: a slot map has to be stored and agreed on. A small coordination mechanism (a gossip protocol or a coordination service) must keep it consistent, and clients need to handle redirects.

Conceptual diagramkeyCRC16 mod 16384slot 7,412slot map v42node 3
Diagram, as text
  • key leads to CRC16 mod 16384
  • CRC16 mod 16384 leads to slot 7,412
  • slot 7,412 leads to slot map v42
  • slot map v42 leads to node 3

The recommended answer is C. The sentence to say: "a fixed number of slots separates placement from membership, so growth is a controlled migration of slots, not a reshuffle of keys."

The second decision: replicas or none

A cache is not the source of truth, so a tempting claim is "if a node dies, the data is only a cache, so skip replicas." Do the arithmetic before agreeing.

With 8 nodes and no replicas, losing one node loses 1/8 of the keys. Those reads miss and go to the database: 12.5% × 270,000 = 33,750 extra reads per second on top of the usual 13,500, which is 47,250 per second, 3.5 times the normal database load, and every replacement entry must be recomputed. If the database sized for 13,500 falls over, the "cache problem" has become an outage.

With one asynchronous replica per primary, a node failure promotes the replica in seconds, and the cache keeps nearly all its content. The price is double the memory (16 nodes instead of 8), and a promoted replica can be missing the last few writes. For a cache, that is tolerable: a stale or missing entry self-corrects when its TTL passes, as long as writes also delete the cache entry rather than relying on replication alone.

So the position is: replicas for the tiers where a cold start would overload the database, none for caches in front of a database that can absorb a full miss. State the rule and show the number that triggers it.

Bottlenecks and failures

A hot key. Hashing spreads keys evenly, but one key can receive far more traffic than a node can serve. A single key at 80,000 reads per second pins one node near its limit, and adding nodes does not help, because the key is on exactly one. Fix it in the client: keep a small near cache in each application server with a TTL of one to a few seconds, so most reads never leave the process. For write-heavy hot keys, split the key into several copies (key#0 to key#7), write to all and read one at random.

Losing a node. Beyond promoting the replica, protect the database with request coalescing (one caller per missing key refills it, the others wait) as the caching lesson describes, and a circuit breaker so a cold cache cannot flood the database. The distributed key-value store page shows the same failure-handling ideas for a durable store.

Big values. A 1 MB value takes long to serialize and send, and a single-threaded node serves nothing else meanwhile. Cap the value size, compress, and keep large objects out of the cache.

Clients with different slot maps. During a resize, a client with an old map sends to the wrong node. The node answers with a redirect and the new map version, and the client retries once. Without redirects, you get misses that look like cache bugs.

Memory fragmentation and eviction. A node at 95% fill evicts constantly and loses its hit ratio. Alert at 80%, scale before the cliff, and use an approximate policy (sample a handful of keys and evict the worst) rather than an exact LRU list that costs memory on every key.

Trade-offs to name aloud

  • Slots over a ring: a small shared map to maintain, in exchange for controlled, incremental resizing.
  • Replicas: double the memory in exchange for surviving a node failure without a miss storm.
  • Asynchronous replication: a promoted replica may be a few writes behind, in exchange for no write latency penalty.
  • Near caches: a second or two of extra staleness for hot keys, in exchange for removing the hot node problem.
  • Delete on write over update on write: one more miss after each change, in exchange for far fewer race conditions.

What interviewers listen for

  • A working answer: nodes holding keys by hash, a TTL, an eviction policy and a fallback to the database on a miss.
  • A strong answer: shows why mod N fails with the 89% number, uses consistent hashing or slots, and sizes the cluster from memory.
  • A standout answer: also argues replicas from the database load during a node loss, handles hot keys with near caches, explains redirects during migration and protects the database from a cold node with coalescing and breakers.

Check your understanding

Common mistakes

Describing cache-aside and stopping. That is how to use a cache. Building one means placement, resizing, failure and hot keys.

Using modulo hashing and saying "consistent hashing" later. If your first design collapses on a resize, say so, or interviewers assume you do not see it.

No numbers for the database. A cache's value is the load it removes. State the hit ratio and what the database sees with and without it, or the whole design floats.

Forgetting what a node loss does. "It's just a cache" is the most common wrong answer. Work out the extra database reads from losing one node.

Treating all keys alike. Adding nodes never fixes one overloaded key. Say "near cache" or "key splitting" for hot keys.

Updating the cache and the database in either order without thinking. Updating the cache on write races with concurrent readers. Deleting after the database write leaves a smaller window.

Practice

Traffic is about to triple for a sale. You must grow the cache from 8 to 12 primaries during normal business hours without increasing database load noticeably. How?

Write your own answer first, on paper or in a note. Then compare.

Show a hint

Think about how many slots move, in what order, and what you do about the new nodes starting empty.

Show a strong answer

Compute the movement. With 12 nodes each should hold 16,384 ÷ 12 ≈ 1,365 slots, so the four new nodes take about 5,460 slots in total, a third of the data, and each existing node gives up a third of what it holds.

Migrate in small batches. Move 50 to 100 slots at a time (about 55 to 110 batches), and wait for the database's read rate and the cache's hit ratio to settle before the next batch. Redirects keep clients correct during each move.

Warm the new nodes. Migrate keys with their TTLs rather than leaving the slots empty, so a moved slot arrives warm, and the database does not see a hole where those slots were.

Do it early. The sale triples traffic, so finish the migration the day before while load is normal. Never resize at the peak.

The pattern worth keeping: grow in steps small enough that the downstream system (the database) never sees a step it cannot absorb.

The cache bill is too high. You want to cut memory by a third without lowering the hit ratio much. What do you try, in order?

Write your own answer first, on paper or in a note. Then compare.

Show a hint

Start with measurement. Which entries earn their memory?

Show a strong answer

Measure first. Sample the keyspace: the distribution of value sizes, TTLs, and how often each key is read. Usually a small fraction of keys serves most hits, and a large fraction is never read twice.

Shrink what is stored. Compress large values, drop fields no reader uses, and shorten key names. Per-item overhead of 100 bytes on 400 million items is 40 GB on its own.

Evict by frequency. An LFU policy keeps the keys that are actually reused and drops the one-hit entries that a recency policy keeps for no reason.

Shorten TTLs for cold data. Entries nobody has read for an hour do not need a six-hour TTL. Then check the hit ratio and the database load, not just memory.

The pattern worth keeping: find out which bytes earn their keep before buying or removing capacity.

Key takeaways

  • Build the cache, don't just use it: placement, resizing, failure and hot keys are the questions.
  • mod N moves about 89% of keys when going from 8 to 9 nodes. Use fixed slots or consistent hashing.
  • Fixed slots with redirects make growth a controlled migration.
  • Size nodes from memory, and judge the design by the database load it removes and what happens when a node dies.
  • Replicas are justified by the extra database load a node loss would cause.
  • Hot keys need near caches or key splitting, since more nodes do not help.

Further reading

  • R. Nishtala et al., "Scaling Memcache at Facebook", NSDI (2013): large-scale cache operation, including leases for stampedes and invalidation.
  • D. Karger et al., "Consistent Hashing and Random Trees", ACM STOC (1997): the original consistent hashing paper.
  • Redis documentation, "Redis cluster specification": hash slots, MOVED and ASK redirects and slot migration.
  • Redis documentation, "Key eviction": approximated LRU and LFU policies.

Check yourself

3 questions in this lesson. Answer each once to complete it.

Practice this

Lessons in this track