Course contents

17. Real-World System Design Lesson 4 of 20

Distributed Cache

Design a distributed cache: size it, shard keys over a hash ring, watch a node failure turn into database misses, then fix hot keys and failover with replicas.

20 minAdvanced9 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • A cache node is limited by memory (hit ratio) and by CPU/network (requests per second); scale out when either runs out.
  • Hash partitioning stores every key once, so node memories add up; consistent hashing keeps most keys in place when nodes change.
  • Losing a node turns its share of reads into misses; a cold node rejoining causes a second burst.
  • Hashing spreads keys, not load: a hot key stays on one node until you replicate or split it.
  • Replicas make failover cheap and absorb hot shards, at roughly double the memory and with possible staleness.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

A distributed cache is a set of in-memory nodes that together act as one large key-value cache. Each key belongs to one node (its owner), chosen by hashing the key; clients or a proxy compute the owner and talk to it directly. Optionally each node has replicas. Memcached clusters with client-side hashing, Redis Cluster (16,384 hash slots spread over primaries with replicas) and managed equivalents all follow this shape.

This lesson designs the cache tier itself: how big, how keys are spread, what happens when a node dies or comes back, and what to do about hot keys. The ring mechanics are in the Consistent Hashing lesson; the read pattern is cache aside or read-through.

Why it exists

One cache node hits two ceilings. Memory decides how many keys fit and therefore the hit ratio. Throughput (CPU, network, connections) decides how many requests per second it answers, regardless of hit ratio. A bigger machine raises both a little; spreading keys over many nodes raises both linearly. A distributed cache also limits the blast radius of a failure to one node's share of the keys.

How it works

Sizing. Start from the hot set and the request rate, both from your requirements:

Quantity Example (illustrative) Result
Hot set 200M keys × ~1 KB (key, value, overhead) ≈ 200 GB
Usable memory per node 64 GB × 75% (leave room for fragmentation, replication buffers, forks) 48 GB
Primaries for memory 200 ÷ 48 5
Primaries for throughput 500k ops/s ÷ a conservative per-node budget depends on value size and commands; measure
With one replica per shard 5 × 2 10 nodes

Take the larger of the memory and throughput counts, then add headroom so the database survives one node's share of misses.

Routing. The cache client (a library in each application instance, or a proxy such as mcrouter or twemproxy) hashes the key and picks the owner. Consistent hashing with virtual nodes, or a fixed number of hash slots assigned to nodes (Redis Cluster), means adding or removing a node moves only about 1/N of the keys. Client-side routing saves a hop; a proxy centralises topology changes and connection pooling.

Partitioning adds memory. Because a key lives only on its owner, three nodes hold three times as many distinct keys as one. In the simulation the hit ratio goes from about 55% (one node, 200 of 2,000 keys) to about 70% (three nodes, 600 keys) while traffic grows. Round-robin spreading would not do that: every node would cache the same popular keys.

Node failure. When a node dies, reads to it fail until the client or health checks notice. Then its keys map to other nodes, which do not have them: misses. Popular keys are re-cached within milliseconds; the long tail keeps missing because less total memory now holds the same key space. In the simulation the database read rate jumps by more than half right after the ejection and settles clearly higher.

Cold rejoin. A restarted in-memory node is empty. If it rejoins at full weight, its keys move back and miss a second time. Warm it first (replay recent keys, or copy from a replica), rejoin it gradually, or promote a replica instead.

Hot keys. A key always maps to one node, so a key that gets 40% of the traffic puts 40% of the load on one node however evenly the ring spreads keys. In the simulation the flash sale saturates node 2 while the others have spare capacity. Fixes: replicas of the hot shard serving reads, a small near cache (in-process, short TTL) for the hottest keys, or splitting a key into key#1…key#n copies and picking one at random on read (writes must update all copies).

Replicas. Each shard gets one or more copies. Redis replicates asynchronously from primary to replicas; reads can be served by replicas if slightly stale data is acceptable. When a primary dies, a replica that already holds the data takes over, so no key moves on the ring and the database barely notices. That is what the failover step shows.

When to use it

When the working set or request rate outgrows one cache node, when a cache node's failure must not send all reads to the database, or when many application instances must share cached state (sessions, rendered fragments, computed results, rate-limit counters).

When not to

  • A single node with a replica covers a surprising amount: if the hot set fits in one machine's memory and its throughput is enough, sharding adds operational cost for nothing.
  • Per-instance in-process caches are faster and simpler for small, mostly static data (configuration, feature flags) where each instance can afford its own copy.
  • A cache is not a database: if losing the data is unacceptable, keep the source of truth elsewhere.

Trade-offs

Choice You gain You pay
More, smaller nodes Smaller blast radius per failure; more aggregate throughput More connections and topology to manage
Client-side routing No extra hop Every client needs the topology and the same hash function
Proxy routing Central topology, pooled connections An extra hop and a tier to run
Replicas Cheap failover; read capacity for hot shards ~2× memory; asynchronous replicas can serve stale data
Reads from replicas Spreads hot shards Read-your-writes is no longer guaranteed
Near cache for hot keys Hot keys never leave the instance Staleness per instance; invalidation is harder

Alternatives

  • Single primary with replicas (no sharding) when one node's memory suffices.
  • In-process caches only, accepting duplicated memory and per-instance staleness.
  • A CDN or edge cache for public, cacheable HTTP responses: it is a distributed cache someone else runs.
  • A database with a large buffer pool or read replicas, if the access pattern is already served well enough by the database's own cache.

Failure modes

  • Miss burst on node loss (simulated): the database takes one node's share of misses at once. Keep headroom, or use replicas.
  • Cold rejoin: a second burst when an empty node takes its keys back (simulated).
  • Hot key saturating one node (simulated) while the cluster average looks fine. Monitor per-node load, not just totals.
  • Stampede on a hot key's expiry: many concurrent misses rebuild the same value. Use request coalescing, early refresh or TTL jitter (Cache Stampede).
  • Split topology: clients with different views of the ring send the same key to different nodes, producing inconsistent values. Distribute topology from one source and version it.
  • Eviction pressure: memory fills, the eviction policy throws out useful keys and the hit ratio drops silently. Alert on evictions and memory headroom.

In production

Watch per-node hit ratio, evictions, memory, CPU, network and connection counts, and the database read rate together: a falling hit ratio is an early warning for the database. Keep TTLs on every key so mistakes age out. Spread primaries and replicas across availability zones. Test node loss in staging and measure the database burst. Use pipelining or multi-get for fan-out reads, and keep values small; one huge value on a node can block it.

Common misconceptions

  • "Adding nodes fixes hot keys." It moves other keys around; the hot key stays on one node.
  • "A restarted cache node comes back with its data." An in-memory cache without persistence comes back empty.
  • "Consistent hashing means no misses when a node fails." It limits which keys move; those keys still miss.
  • "Replicas make the cache strongly consistent." Asynchronous replicas can lag; after failover some recent writes may be missing.

Interview angle

Size the tier from memory and throughput with numbers, explain client-side vs proxy routing, and why consistent hashing (or hash slots) beats hash mod N. Then expect: what happens when a node dies (miss burst, database headroom), how a node rejoins, how you handle a hot key, and what replicas cost. Naming the failure-time load on the database is what separates a strong answer. The URL Shortener case study shows a cache tier like this one in use.

Model assumptions

The simulation is a simplified model, not a benchmark. Reads arrive as a Poisson process over 2,000 keys with a Zipf(1) popularity (Zipf 1.6 during the flash sale). Each cache node is a read-through process with 4 workers and about 5 ms of work per request (lognormal, cv 0.3), and its memory is a separate LRU of 200 keys; a worker is held while the node waits for its memory and, on a miss, the database. The database has 3 connections and a 20 ms mean read (about 150 reads/s); a query waiting more than 200 ms for a connection fails. The ring uses 64 virtual nodes per cache node; node ids were chosen so node 2 owns the most popular keys. A crashed node comes back with empty memory. Health checks run every 500 ms (2 failures eject, 3 successes restore). Replication is approximated: the two copies of shard 2 each fill their own memory from the reads they serve (reads alternate between them), which stands in for a replica kept up to date by the primary; replication lag and promotion are not modelled. Numbers show behaviour and orders of magnitude only.

The lesson as textEvery step of the simulation, written out.
  1. 1. One cache node in front of a slow database

    The Product API reads product data by key. The database answers in about 20 ms and, in this model, manages about 150 reads per second. So we put a read-through cache in front: on a miss the cache node reads the database and keeps the value in memory.

    Requirements for the cache tier: sub-millisecond lookups, a hot set far larger than one machine’s memory, throughput beyond one machine’s CPU and network, and no thundering herd on the database when a node dies.

    At 150 reads per second, one node with room for 200 of the 2,000 keys answers a bit over half of them from memory; the database sees the rest. The node’s workers are about half busy.

    Scene: The Product API fleet reads through a cache client to one cache node with an LRU memory of 200 keys, which reads the product database on a miss. A bit over half the reads are hits; the cache node is about half busy and nothing fails.

    Key idea: A cache is sized by two limits: memory (how many keys fit, which sets the hit ratio) and throughput (how many requests one node can answer).

  2. 2. One node runs out of CPU and memory

    Traffic doubles to 300 reads per second. The single cache node cannot answer that many: its workers are always busy, its queue fills and it rejects requests.

    A bigger machine would buy time, but memory is a second ceiling. 200 keys is all this node can hold, so the hit ratio cannot improve however fast the node is. We need to spread both the keys and the requests over several nodes.

    Scene: At 300 reads per second the single cache node is saturated, with a full queue, and rejects some requests.

    Key idea: Scale a cache out when either its throughput or its memory is the limit; scaling up only moves both ceilings a little.

  3. 3. Three nodes, each owning part of the key space

    We add two cache nodes. The cache client in the API (a library such as a ketama-style Memcached client, or a proxy) hashes each key onto a ring with 64 virtual nodes per cache node, so a given key always goes to the same node. The [Consistent Hashing](/system-design/learn/scaling/consistent-hashing) lesson covers the ring itself.

    Because every key lives on exactly one node, the memories add up: 600 keys in total. Traffic keeps growing, to 400 reads per second, yet the rejections stop: each node handles only its share of the requests, and the hit ratio rises to about 70%, so a smaller fraction of reads reaches the database.

    Scene: Three cache nodes sit behind the cache client’s hash ring, each owning part of the keys and holding 200 of them. At 400 reads per second the hit ratio is about 70%, each node is at most half busy and nothing fails.

    Key idea: Partitioning a cache adds memory as well as throughput: every key is stored once, on its owner.

  4. 4. A node dies: its keys turn into misses

    One second in, cache node 2 crashes. It owns the most popular keys, about 40% of all reads. Until two health checks fail, reads routed to it fail outright.

    Then the ring sends its keys clockwise to nodes 1 and 3. Those nodes have never seen them, so they miss, and the database’s read rate jumps by more than half within a second of the ejection. The hottest moved keys are cached again almost at once; the long tail keeps missing, because two memories now hold the keys of three. The database settles clearly busier than before: it must have headroom for this, or the miss burst becomes an outage.

    Scene: Cache node 2 crashes. Its reads fail until health checks eject it, then its keys move to nodes 1 and 3 as misses. The database read rate jumps and stays higher than before.

    Key idea: Losing a cache node is a database event: its share of reads turns into misses all at once.

  5. 5. It comes back empty, and the keys move again

    Node 2 restarts one second in. A cache process keeps its data in memory, so it comes back empty. After three good health checks the ring gives its keys back, and on node 2 they are misses a second time: once when they left, once when they returned. Node 2’s hit ratio starts far below the others and climbs as its memory refills.

    That is why production clusters avoid rejoining a cold node straight into the ring at full weight: they warm it first, rejoin it gradually, or fail over to a replica that already holds the data.

    Scene: Cache node 2 recovers with empty memory. Once the ring routes its keys back, they miss again on node 2, whose hit ratio starts low and climbs as memory 2 refills.

    Key idea: Every ring change costs a burst of misses; a cold node rejoining costs a second one.

  6. 6. A flash sale: one shard gets most of the reads

    A product goes on sale. Reads rise to 1,100 per second and popularity becomes far more skewed: the top product alone is over 40% of all reads, and node 2 owns it. About two thirds of all traffic lands on node 2.

    These reads are cheap hits, but node 2’s CPU is the limit: it saturates and rejects requests while nodes 1 and 3 have plenty of spare capacity. Adding more nodes does not help, because a key always goes to one node.

    Scene: During a flash sale about two thirds of reads go to cache node 2, which saturates and rejects requests, while nodes 1 and 3 have spare capacity.

    Key idea: Hashing spreads keys, not load: a hot key pins its traffic to one node.

  7. 7. Two copies of the hot shard

    Shard 2 now runs as two copies, a primary and a replica, and reads are spread over both. The ring is unchanged (it still sees one "node 2"), so no key moves.

    Each copy takes half of the shard’s reads and is a bit over half busy; the rejections stop. Other fixes for hot keys: a small near cache inside each API instance for the hottest keys, or splitting one key into several (product:42#1…#4) and picking one at random.

    Scene: Shard 2 is now a primary and a replica behind a small balancer; each takes half of the shard’s reads and is a bit over half busy. Nothing is rejected.

    Key idea: Replicate the shard (or the key) that is hot; adding shards does not split a single key.

  8. 8. The primary dies, the replica is already warm

    The sale is over: back to 400 reads per second with normal popularity. One second in, shard 2’s primary crashes, the same failure as before.

    This time the shard’s other copy already holds the same hot keys. Once the health checks route around the primary, the replica answers its reads as hits. No key moves on the ring, the database barely notices, and only the reads caught in the detection window fail.

    Scene: Shard 2’s primary crashes. After a short detection window the replica serves the shard’s reads from its warm memory; the database load hardly changes.

    Key idea: Replicas turn a node failure from a miss storm into a short failover.

  9. 9. The cache tier, and what it trades

    The primary is back. The design: a cache client that hashes keys onto a ring of cache nodes; each node owns a slice of the keys, so memory and throughput add up; replicas for shards that are hot or critical; health checks that eject dead nodes.

    What it trades: replicas double memory cost; asynchronous replication means a failover can serve slightly stale values; every ring change still costs misses, so the database must keep headroom for at least one node’s share; and invalidation is still yours (TTL plus delete-on-write).

    Scene: All cache nodes are healthy: nodes 1 and 3, and shard 2 with a primary and a replica, behind the cache client’s ring. Nothing fails.

    Key idea: A distributed cache is partitioning plus replication for memory: size the database for the day a shard goes cold.