Design a Distributed Cache

How to design a cluster of in-memory cache nodes, covering eviction, key partitioning, replication and hot keys, and what interviewers ask about it.

Case study27 minLesson 4 of 7
On this page
  1. Clarify the problem
  2. Estimate the scale
  3. Define the API (optional)
  4. Model the data
  5. High-level design
  6. Deep dives
  7. Bottlenecks and failures
  8. What a strong answer sounds like
  9. Follow-up questions

A distributed cache is a cluster of servers that keep copies of frequently read data in memory, so that applications can read it in under a millisecond instead of querying a database. The question asks you to design the cache itself, not to use one, and it is hard because the data does not fit on one machine, nodes will fail, and a handful of very popular keys can overload a single node.

Unlike Design a Key-Value Store, a cache may lose data, because the source of truth is a database elsewhere, and that allows a design that trades durability for speed. The steps follow A Framework for Any Design, and using a cache from an application is covered in Caching.

Clarify the problem

The first five minutes
Interviewer

Design a distributed cache.

You

Is this a cache or a database? If every value can be rebuilt elsewhere, I can keep everything in memory and accept losing recent writes when a node fails.

Interviewer

It is a cache. The source of truth is elsewhere.

You

I will assume get, set with an optional time to live, and delete on string values. How large are the values, how many keys are there, and how much traffic?

Interviewer

Values average 500 bytes and are at most 1 MB. There are about 2 billion items. Traffic is 400,000 operations a second on average and a million at peak, and 90% of them are reads.

You

Then latency and availability matter most, and I will accept losing the last few milliseconds of writes in a failover.

  • Functional requirements: get(key), set(key, value, ttl) and delete(key). An expired key is never returned, and a node that is full evicts keys to make room.
  • Non-functional requirements: the 99th percentile of a get is under 1 ms inside one data center, the cluster keeps working when any one node dies, it can grow without downtime, and a failover may lose a few milliseconds of acknowledged writes.
  • Out of scope: lists, sets, counters, transactions, durable storage and replication across regions.

Estimate the scale

Each item takes about 600 bytes: a 50-byte key, a 500-byte value, and about 50 bytes of bookkeeping. A node has 64 GB of RAM, but only about 50 GB should hold items, because the allocator wastes space, connections need buffers and replication keeps a backlog. One node can serve about 100,000 simple operations a second.

Estimate: How many primaries

How many primary nodes do you need to hold every item in memory?

You know
  • 2 billion items
  • About 600 bytes per item, bookkeeping included
  • About 50 GB usable per node

Show the working
  1. 2 × 109 × 600 B = 1.2 × 1012 B = 1.2 TB
  2. 1.2 TB ÷ 50 GB = 24 primaries
  3. With one replica each: 48 nodes

Estimate 24 (anything from 10 to 60 is a good answer)

Memory decides the node count here, but traffic must also fit what one node can serve.

Estimate: Load on one primary at peak

Keys spread evenly over 24 primaries. How many operations per second does one primary serve at peak?

You know
  • 1 million operations a second at peak
  • 24 primaries
  • All reads and writes go to primaries

Show the working
  1. 1,000,000 ÷ 24 ≈ 41,700, call it 42,000 a second
  2. That is under half the 100,000 budget, so traffic fits

Estimate 42 thousand/s (anything from 15 thousand/s to 120 thousand/s is a good answer)

Writes are 10% of this, about 4,200 a second per primary. The spare capacity matters for hot keys and failover.

Your turn: Define the API

Write the three operations with their replies, including the reply for a key on another node.

Compare with a model answer

The operations are get, set with a TTL and optional conditions, and delete, sent over long-lived TCP connections rather than HTTP. The replies include a miss, "not stored", a size error, and a redirect that names the node that owns the key.

Define the API Optional

Optional in the interview. Sketch the API only if the interviewer asks, if an API choice shapes the design, or if time permits. Otherwise say "I'll skip the detailed API unless you want it" and go to the data model.

Cache protocol
GET key
  VALUE bytes            hit
  MISS lease=501         miss; you may fill it with lease 501
  WAIT                   someone else holds the lease; retry in about 20 ms
 
SET key value [TTL seconds] [NX | XX] [LEASE token]
  OK
  NOT_STORED             NX and the key exists, XX and it does not,
                         or the lease was cancelled by a delete
  TOO_LARGE              value over 1 MB
  OUT_OF_MEMORY          full, and the policy is not to evict
 
DEL key
  DELETED | NOT_FOUND    also cancels any open lease on the key
 
any command
  MOVED 9301 10.0.4.17:7000   slot 9301 lives on another node

The one decision worth arguing is the transport. A get takes microseconds on the server, so HTTP overhead would cost more than the work. The cache uses persistent TCP connections with a compact binary protocol, and it supports pipelining, which means a client can send 10 gets without waiting for the replies and pay for one round trip instead of ten.

Your turn: Model the data

What does one entry hold, and which data structures give O(1) lookup, O(1) eviction and cheap expiry? What does the cluster as a whole need to store?

Compare with a model answer

Each node holds a hash table and a recency ordering, and each entry carries an expiry time. The cluster needs a small map from slot to node.

Model the data

Inside one node, and the cluster map
entry                                        about 50 B of bookkeeping
  key          bytes   (up to 250 B)
  value        bytes   (up to 1 MB)
  expires_at   8 B     ms since epoch, 0 = never
  hash_next    8 B     next entry in the same bucket
  lru_prev     8 B     neighbours in the recency list
  lru_next     8 B
  sizes, flags ~10 B
 
cluster map                                  a few hundred KB
  slot 0..16383   -> shard id
  shard id        -> primary address, replica addresses
  epoch           -> bumped on every change

Every access is by exact key, so each node stores its entries in a hash table in RAM, with a doubly linked list running through the entries in order of recent use. This is the O(1) LRU cache from Designing Data Structures. The cluster map is tiny, but every client must agree on it, so it lives in a configuration service that uses consensus.

Your turn: High-level design

Sketch the cluster. How does an app server find the right node, where do the copies live, and what decides that a node is dead?

Compare with a model answer

A client library maps each key to a slot and each slot to a node, using a cached copy of the cluster map. Each shard is a primary plus one replica, and a configuration service watches health, promotes replicas and publishes new maps.

High-level design

There is no load balancer. The client library on each app server routes every request straight to the primary that owns the key.

The client library sends each key to its shard's primary, primaries copy writes to their replicas asynchronously, and the configuration service tracks health and publishes the cluster map.App servers to Cluster config (cluster map); App servers to Source database (read on miss); Cluster config to Shard A primary (health checks); App servers to Shard A primary; App servers to Shard B primary (get / set / del); App servers to Shard C primary; Shard A primary to Shard A replica, asynchronous; Shard B primary to Shard B replica (replicate), asynchronous; Shard C primary to Shard C replica, asynchronous.Cluster configApp serversSource databaseShard A primaryShard B primaryShard C primaryShard A replicaShard B replicaShard C replicacluster mapread on misshealth checksget / set / delreplicate

request and replyasynchronous message

The client library sends each key to its shard's primary, primaries copy writes to their replicas asynchronously, and the configuration service tracks health and publishes the cluster map.

The diagram shows three of the 24 shards. The tracer follows a hit, a miss filled under a lease, and the death of a primary.

A hit, a miss under a lease, then a primary diesUse the arrows or ← → keys
  1. A hit, a miss under a lease, then a primary dies, step 1App servers to Cluster config; App servers to Source database; Cluster config to Shard A primary; App servers to Shard A primary; App servers to Shard B primary; App servers to Shard C primary; Shard A primary to Shard A replica, asynchronous; Shard B primary to Shard B replica, asynchronous; Shard C primary to Shard C replica, asynchronous.Cluster configApp serversSource databaseShard A primaryShard B primaryhitShard C primaryShard A replicaShard B replicaShard C replica
    map epoch
    7
    db reads
    0

    1An app server wants user:42. The client hashes the key to slot 9,301, and its cached map says that slot belongs to shard B, which finds the entry, checks that it has not expired and replies in about 0.5 ms.

  2. A hit, a miss under a lease, then a primary dies, step 2App servers to Cluster config; App servers to Source database; Cluster config to Shard A primary; App servers to Shard A primary; App servers to Shard B primary; App servers to Shard C primary; Shard A primary to Shard A replica, asynchronous; Shard B primary to Shard B replica, asynchronous; Shard C primary to Shard C replica, asynchronous.Cluster configApp serversSource databaseShard A primarymiss, lease 501Shard B primaryShard C primaryShard A replicaShard B replicaShard C replica
    map epoch
    7
    db reads
    0

    2A get for product:7 misses on shard A. Shard A replies with lease 501, which means that only this caller may fill the key.

  3. A hit, a miss under a lease, then a primary dies, step 3App servers to Cluster config; App servers to Source database; Cluster config to Shard A primary; App servers to Shard A primary; App servers to Shard B primary; App servers to Shard C primary; Shard A primary to Shard A replica, asynchronous; Shard B primary to Shard B replica, asynchronous; Shard C primary to Shard C replica, asynchronous.Cluster configApp serversSource databaseShard A primaryWAITShard B primaryShard C primaryShard A replicaShard B replicaShard C replica
    map epoch
    7
    db reads
    0

    3A second app server asks for product:7 a millisecond later. The lease is still open, so shard A answers WAIT and no second database query is made.

  4. A hit, a miss under a lease, then a primary dies, step 4App servers to Cluster config; App servers to Source database; Cluster config to Shard A primary; App servers to Shard A primary; App servers to Shard B primary; App servers to Shard C primary; Shard A primary to Shard A replica, asynchronous; Shard B primary to Shard B replica, asynchronous; Shard C primary to Shard C replica, asynchronous.Cluster configApp serversSource databaseShard A primarystoredShard B primaryShard C primaryShard A replicaShard B replicaShard C replica
    map epoch
    7
    db reads
    1

    4The lease holder reads the database, which takes about 5 ms, and sends SET … TTL 300 LEASE 501. Shard A replies OK before its replica has the value, then streams the write on a few milliseconds later. The waiting app server retries and gets a hit.

  5. A hit, a miss under a lease, then a primary dies, step 5App servers to Cluster config; App servers to Source database; Cluster config to Shard A primary; App servers to Shard A primary; App servers to Shard B primary; App servers to Shard C primary; Shard A primary to Shard A replica, asynchronous; Shard B primary to Shard B replica, asynchronous; Shard C primary to Shard C replica, asynchronous.Cluster configApp serversSource databaseShard A primarydownShard B primaryShard C primaryShard A replica42 behindShard B replicaShard C replica
    map epoch
    7
    lost writes
    42

    5Shard A's primary dies. The writes it acknowledged in its last 10 ms never reached the replica, about 42 values at 4,200 writes a second.

  6. A hit, a miss under a lease, then a primary dies, step 6App servers to Cluster config; App servers to Source database; Cluster config to Shard A primary; App servers to Shard A primary; App servers to Shard B primary; App servers to Shard C primary; Shard A primary to Shard A replica, asynchronous; Shard B primary to Shard B replica, asynchronous; Shard C primary to Shard C replica, asynchronous.Cluster configApp serversSource database+37,500 reads/sShard A primarydownShard B primaryShard C primaryShard A replicaShard B replicaShard C replica
    map epoch
    7
    lost writes
    42

    6Until the replica takes over, calls to shard A time out and are treated as misses. At peak, 90% of about 41,700 operations a second are reads, so the database receives about 37,500 extra reads a second.

  7. A hit, a miss under a lease, then a primary dies, step 7App servers to Cluster config; App servers to Source database; Cluster config to Shard A primary; App servers to Shard A primary; App servers to Shard B primary; App servers to Shard C primary; Shard A primary to Shard A replica, asynchronous; Shard B primary to Shard B replica, asynchronous; Shard C primary to Shard C replica, asynchronous.Cluster configepoch 8App serversSource databaseShard A primarydownShard B primaryShard C primaryShard A replicanow primaryShard B replicaShard C replica
    map epoch
    8
    lost writes
    42

    7After a majority of the config service's members have failed health checks on shard A for 5 seconds, the service promotes the replica and raises the map epoch to 8.

  8. A hit, a miss under a lease, then a primary dies, step 8App servers to Cluster config; App servers to Source database; Cluster config to Shard A primary; App servers to Shard A primary; App servers to Shard B primary; App servers to Shard C primary; Shard A primary to Shard A replica, asynchronous; Shard B primary to Shard B replica, asynchronous; Shard C primary to Shard C replica, asynchronous.Cluster configApp serversSource databaseShard A primarydownShard B primaryShard C primaryShard A replicaShard B replicaShard C replica
    map epoch
    8
    lost writes
    42

    8The client fetches the epoch 8 map and sends shard A's keys to the new primary. The 42 lost values are now ordinary misses.

1 / 8

Deep dives

Memory, expiry and eviction inside one node

One node holds about 2 billion ÷ 24 ≈ 83 million entries. The hash table becomes a problem when it has to grow. Moving all 83 million entries to a table twice as large at about 50 ns each would block the node for about 4 seconds. The fix is to rehash incrementally: the node keeps the old and new tables at the same time, moves a few buckets on every operation, and looks in both tables until the old one is empty.

Keeping a timer for every key costs too much, so expiry combines two cheap mechanisms. With lazy expiry, every read checks expires_at and deletes the entry if it has passed, so no reader ever sees an expired value. Lazy expiry alone leaves keys that are never read again in memory. Sampled expiry fixes this: about 10 times a second the node picks 20 random keys that have a TTL and deletes the expired ones, and if more than a quarter of the sample was expired it repeats immediately. The primary decides when a key has expired and sends an explicit delete to its replica, so that both copies agree.

Eviction decides what to remove when memory is full. Exact LRU moves an entry to the front of the list on every read, which costs pointer writes on the hot path and 16 bytes per entry. Many caches therefore approximate it by sampling 5 to 10 random entries and evicting the one with the oldest last-used timestamp. The policy is set per cluster:

  • LRU evicts the key that has gone longest without a read. It works well for most workloads and is the usual default.
  • LFU evicts the key with the fewest reads over time. It protects steady favourites from being flushed out by a one-off scan, but it is slow to notice that a favourite has gone cold.

Partitioning keys across nodes

The simplest scheme is hash(key) mod 24. It breaks when the cluster changes size: going from 24 to 25 nodes remaps almost every key, so nearly the whole cache becomes misses at once and the database takes the full load. A hash ring built with consistent hashing avoids this, because adding a node moves only about 1 ÷ 25 = 4% of the keys, but a ring is awkward to rebalance by hand.

The design therefore uses fixed slots. Every key is hashed to one of 16,384 slots, and the cluster map assigns each slot to a shard, so each of the 24 shards owns about 683 slots. Adding a 25th shard moves about 655 slots, again 4% of the keys, one slot at a time. Once a slot has moved, the old node replies MOVED to clients that still use the old map.

The remaining decision is whether the map is applied by a client library in each app server or by a separate proxy tier.

Who decides which node gets a key
OptionGood atBad atPick it when
Smart client Usual defaultOne network hop and no extra tier to run.Every language needs a client library that caches the map and handles MOVED, and every app server connects to every primary.Most traffic comes from a few languages that you control. This is the usual default.
Proxy tierClients stay simple, and pooling gives each primary far fewer connections.Each request pays an extra hop of 0.2 to 0.5 ms, and the proxies must be run and scaled.There are many languages or legacy clients, or thousands of app servers.

Replication and what a failover loses

Each shard has a replica on a different rack. The primary acknowledges a write as soon as the value is in its own memory and then streams it to the replica, as described in Replication. This is asynchronous replication, and its consequence is that an acknowledged write can be lost if the primary dies before the replica receives it. At 10 ms of lag and 4,200 writes a second that is about 42 values, which become misses and are reloaded from the database, and that is acceptable for a cache.

A lost delete is more harmful than a lost write. An application updates the database and deletes the cached key, and then the primary dies before the replica sees the delete. The promoted replica now serves the old value until its TTL runs out, which is why every key should have a TTL, even a long one.

The configuration service runs on 3 or 5 nodes using consensus, and it declares a primary dead only when a majority of its members cannot reach it for 5 seconds. A primary that is cut off from the config service but still reachable by some clients would keep accepting writes while a new primary is also accepting them. A leadership lease prevents this, and it is a different thing from the fill lease in the API. A primary accepts writes only while its leadership lease is valid. The lease lasts 4 seconds and promotion waits 5 seconds, so the old primary stops writing before the new one starts.

Hot keys and cache stampedes

A hot key gets more traffic than the node holding it can serve. If a celebrity profile receives 150,000 reads a second and one shard handles about 100,000, adding nodes does not help, because the key lives on one node. There are two fixes:

  • A near cache keeps the value in each app server's memory for about 1 second. With 300 app servers, the shard sees at most 300 reads a second for that key, but readers can see a value up to 1 second old.
  • Copies under several keys store the value as profile:9#0 to profile:9#7, which hash to different slots, and each reader picks one at random. Each copy serves about 150,000 ÷ 8 ≈ 18,750 reads a second, but every write or delete must update all 8 copies.

A cache stampede is the related case in which a hot key expires and hundreds of app servers query the database for it at the same moment. The lease in the tracer prevents it. On a miss, the cache gives a fill lease to the first caller and tells the others to wait and retry, so only one database query is made. Leases also close a stale-write race. Suppose app 1 reads the old row, app 2 updates the row and deletes the key, and then app 1 tries to store the old value. The delete cancelled lease 501, so app 1's SET returns NOT_STORED. A lease expires after about 2 seconds, so a crashed holder does not block the key.

Bottlenecks and failures

At 10 times the load, the cluster holds 12 TB and serves 10 million operations a second, which needs about 240 primaries. Connections break first: 3,000 app servers each connecting to 240 primaries gives each primary 3,000 connections, so you add a proxy tier or connection pooling.

When this diesWhat happensWhat you do
A primaryIts 1/24 of the keys miss for about 5 seconds, and about 42 acknowledged writes are lost.The configuration service promotes the replica, and a circuit breaker limits the extra load on the database.
A replicaClients notice nothing, but the shard has no spare.Copy a snapshot to a new node, which takes under 7 minutes for 50 GB.
A primary and its replica togetherThat shard restarts with no data.Place the pair on different racks, and warm the new node gradually so the database is not flooded.
A network partitionA primary that is cut off may still accept writes from nearby clients.Its leadership lease expires within 4 seconds, before promotion at 5 seconds, and the writes it took after the cut are lost.

What a strong answer sounds like

LevelWhat the answer does
JuniorDescribes a hash map with LRU on each server and hash mod N routing.
Mid-levelSizes the cluster from memory, explains expiry, chooses slots and a smart client, and adds a replica for each shard.
SeniorAsks whether it is a cache or a database, says what an acknowledged write promises, handles split brain and lost deletes, uses leases against stampedes, and names the cost of each choice.
What does OK mean?Strong answer
Interviewer

A client gets OK on a set. Is the value safe?

You

It is safe only as long as that primary stays alive. If the primary crashes in the next few milliseconds, the value is lost, which is about 42 values per failover at our write rate. The database still has all of them, so I accept that. A lost delete is more dangerous, and the TTL on every key limits how long a stale value survives.

Follow-up questions

Should a node write its data to disk?

A node can write a periodic snapshot to disk so that, after a reboot, it loads 50 GB from disk instead of starting empty and sending every read to the database. This only speeds up a restart and is not durability, because writes made after the last snapshot are lost.

Why not serve reads from replicas?

It would double read capacity, but a replica lags by about 10 ms, so a client could miss its own write or read a value it just deleted. Because the primaries run at less than half of their budget, reads stay on them, except for hot keys that tolerate stale values.

How do you add a node without emptying the cache?

Assign the new shard a share of the slots and move them one at a time. While a slot is moving, only the keys in that slot are affected, and the old node answers MOVED once the slot has left.

What happens when clients keep asking for keys that do not exist?

Every such request misses in the cache and reaches the database, so a client that requests random missing keys can bypass the cache entirely. The usual fix is to store a short-lived marker for a missing key, with a TTL of a few seconds, so that repeated requests for it are answered from the cache.

Self-review: distributed cache0 of 13

After your attempt, tick what you really did. Be strict: "I thought about it" is not "I said it out loud".

Before drawing

Numbers and interfaces

Design and depth

Failure