Case studies

Design a distributed cache

A Memcached or Redis-like cache cluster. Partitioning with consistent hashing, routing, eviction, hot keys, and what happens to the database when a node dies.

Case study23 min read
Video walkthrough: not recorded yet. The lesson below is complete without it.

The problem

A product database serves 5,000 reads a second comfortably. The team puts one Memcached server in front of it, and the hit rate reaches 95%. Traffic grows twentyfold. Now the cache needs to hold a terabyte, which no single machine has in memory, and a single machine is also one reboot away from sending every read to the database at once.

Brad Fitzpatrick wrote Memcached for LiveJournal in 2003 for exactly this kind of load, and its answer to “more than one server” was simple: the servers know nothing about each other, and the client decides which server holds a key. That choice leaves all the hard questions with whoever designs the cluster. Which node owns a key? What happens to the other keys when a node is added? What does a dead node do to the database behind it? And why does one celebrity’s profile take a node down when the cluster is half idle? This case study designs that cluster. How an application should use a cache is covered in caching patterns.

Requirements

Functional

  • get, set with a TTL, and delete, by key.
  • Compare-and-set, so a client can update a value only if nobody else has changed it.
  • Evict automatically when memory is full.
  • Add and remove nodes while serving traffic.

Out of scope unless asked: durable persistence, rich data types and queries. This is a cache, so the source of truth is elsewhere.

Non-functional

  • Latency: under 1 ms at p99 inside a node, a few milliseconds as seen by the client.
  • Throughput: 1 million operations a second at peak, 90% reads.
  • Availability: losing a node must not lose more than its share of the data, and must not overload the database.
  • Consistency: stale reads are tolerated within the TTL. Any item may vanish at any time. A node must never return a value that was explicitly deleted, if we can prevent it.
  • Elasticity: changing the node count moves as few keys as possible.
  • Keys up to 250 bytes and values up to 1 MB, most far smaller.

Capacity estimates

Quantity Working Result
Data 2 billion items x 500 bytes (key, value, about 50 bytes of metadata) 1 TB
Nodes 1 TB / 50 GB usable on a 64 GB machine, plus headroom 20, so run 24
Load per node 1M operations / 24 about 42,000 per second
Network 1M x 500 bytes about 4 Gbit/s across the cluster
Database reads, normal 900,000 reads x 5% misses 45,000 per second
Database reads, one node lost 45,000 + 900,000 x 1/24 x 95% about 81,000 per second

Memory decides the node count. At 42,000 small operations a second, each node has plenty of CPU to spare.

The last row is the one that drives the design. Losing 4% of the cache nearly doubles the load on the database. Unless the database has that much headroom, the design needs replicas or some other way to cover a dead node.

API

Clients hold persistent TCP connections and speak a small command protocol:

get <key> [<key> ...]             value, flags and version for each hit
set <key> <value> <ttl> [nx]      stored | not stored
cas <key> <value> <ttl> <version> stored | changed | not found
delete <key>                      deleted | not found

nx stores only if the key is absent. cas stores only if the item’s version still matches the one returned by an earlier get. A multi-key get matters more than it looks: a page that needs 100 keys should make one request per node, in parallel, not 100 round trips. Clients pipeline requests on a connection, so one connection carries many requests in flight.

The cluster has a second, small API for operators: add a node, drain a node, and fetch the current cluster map.

Data model

Inside a node. A hash table maps each key to an item: key, value, flags, expiry time, a version for cas, and the pointers that place it in a recency list. Memory is managed in slabs, as Memcached does: memory is cut into pages, each page into fixed-size chunks, and items go into the smallest chunk class that fits. Freed chunks are always reusable by another item of that class, so a process that runs for months does not fragment. The cost is some wasted space inside each chunk.

Across the cluster. One small document describes the topology:

Field Example Notes
version 418 increases on every change
nodes id, address, state state is joining, serving, draining or dead
tokens 150 ring positions per node virtual nodes
replicas primary to replica mapping

Every router must use the same version of this map. Two clients with different maps send the same key to different nodes, and one of them reads a value the other has already replaced.

High-level architecture

Distributed cache reference architecture10 components: App servers, Cache proxy, Cache node A, Cache node B, Cache node C, Replica A, Replica B, Replica C, Config service, Database. Connections: App servers to Cache proxy; Cache proxy to Cache node A; Cache proxy to Cache node B; Cache proxy to Cache node C; Cache node A to Replica A; Cache node B to Replica B; Cache node C to Replica C; Config service to Cache proxy (new map version); Config service to Cache node C (health checks); App servers to Database (on a miss).App serverscache clientCache proxyhashes key onto the ringCache node AprimaryCache node BprimaryCache node CprimaryReplica Aasync copyReplica Basync copyReplica Casync copyConfig servicecluster map, health checksDatabasesource of truthnew map versionhealth checkson a miss
Distributed cache reference architecture

Read, hit. The app server asks its cache client for a key. The request goes to a proxy, which hashes the key, finds the owning node on the ring and forwards the request. The node looks the key up in its hash table, moves the item to the front of its recency list and returns it.

Read, miss. The node answers “miss”. The application reads the database, then sets the key with a TTL. The cache never talks to the database itself; that keeps it general.

Write. A set or delete goes to the primary for that key, which applies it and sends it to its replica asynchronously.

Membership. Each node holds a session with the config service (etcd or ZooKeeper), which also health-checks it. When a node dies or one is added, the config service publishes a new map version and every proxy switches to it.

Deep dives

Partitioning and routing

hash(key) mod N spreads keys evenly but remaps nearly every key when N changes. Going from 24 to 25 nodes would turn about 96% of reads into misses at the same moment. Consistent hashing places nodes and keys on a ring, and a key belongs to the first node clockwise from it. Adding a 25th node moves about one key in 25.

With one ring position per node, the arcs are uneven and a dead node hands its whole range to one neighbour. So each node takes many positions, called virtual nodes. Around 100 to 200 per node is common and keeps the load on each node within a few percent of the average.

Consistent hashing ring

Open full screen
CBADkeys sit inside,nodes on the ring

Keys per node (a fair share is 40)

  • A35
  • B20
  • C97
  • D8

Add or remove a node. Keys that change owner are outlined. Then raise the virtual nodes and compare how evenly the keys spread.

Nodes
4
Busiest node
97
Quietest node
8
Moved by last change
none yet
Would move with mod N
none yet

Add a node and compare “Moved by last change” with “Would move with mod N”, then raise the virtual nodes per server from 1 to 128 and watch the gap between the busiest and quietest node shrink.

Something has to hold the map and do the hashing. There are three choices.

Routing How it works Cost
Smart client A library in each app holds the map and connects to every node A library per language; connections multiply as app servers x nodes
Proxy Apps talk to a proxy as if it were one server One extra hop; another fleet to run
Server redirect Any node answers or replies “moved, ask node X” Clients still need to cache the map to avoid double hops

Twemproxy and mcrouter are proxies. Redis Cluster uses redirects with clients that cache the slot map. I would choose a proxy, run as a sidecar on each app host or as a small tier. With 2,000 app servers in five languages, one implementation of routing and one place to roll out a new map are worth a fraction of a millisecond.

Eviction and memory

When a node is full, each new item must push one out. Least recently used (LRU) is the default answer because recent access predicts future access well for most workloads. The policies are compared in eviction policies.

LRU cache walkthrough

Open full screen
Most recently usedNext to be evicted
  1. empty
  2. empty
  3. empty

A real LRU cache keeps this order in a doubly linked list and finds entries through a hash map, so reads, writes and evictions are all O(1).

Hits
0
Misses
0
Hit rate
n/a
In cache
0 of 3

What just happened

Nothing yet. Use the controls above.

    Fill the cache, read the oldest key again, then write a new key and see which one is evicted.

    Exact LRU keeps a linked list and moves an item to the head on every read. At 42,000 operations a second across many threads, that list becomes a lock everyone waits for. Real systems approximate. Memcached splits the list into hot, warm and cold segments and avoids bumping an item that was bumped recently. Redis keeps no list at all: it samples a few keys (five by default) and evicts the one idle longest. Redis also evicts nothing unless you set a policy, because its default maxmemory-policy is noeviction, under which writes fail when memory is full.

    Two more points are worth saying aloud. Eviction is local to a node (in Memcached, local to a slab class), so there is no cluster-wide “least recently used” item. And expiry is separate from eviction: an expired item is removed when someone next reads it, plus a background sweep that reclaims items nobody asks for.

    Hot keys and node failure

    Hot keys. One key maps to one node. If a single key takes 150,000 reads a second, that node saturates while the other 23 sit idle, and adding nodes changes nothing. Options, in the order I would reach for them:

    • Cache hot keys in the app server’s own memory for a second or two. The proxy can detect them by sampling.
    • Read hot keys from replicas as well as the primary.
    • Split the key into key#1 to key#8, written to all and read from one at random, which spreads it over several nodes.

    A node dies. There are three ways to respond.

    1. Remap. Remove the node from the ring. Its keys fall to its neighbours and miss until refilled. This is simple, and the estimates show it nearly doubles database load.
    2. Promote a replica. Each primary streams writes to a replica. Replication is asynchronous, so the last few writes may be lost, which a cache can accept. It doubles the memory bill.
    3. Spare pool. Keep a few idle nodes. Requests for a dead node’s keys go to the spares with a short TTL. Facebook’s 2013 paper on scaling Memcached describes this and calls the pool Gutter.

    Given the estimates, I would run one replica per primary. A team whose database has headroom might choose the spare pool and halve the memory cost.

    The stale rejoin. Remapping hides a correctness bug.

    How a cache node that rejoins can serve stale data4 components: App server, Cache node A, Cache node B, Database. Connections: App server to Cache node A; App server to Cache node B; App server to Database.App serverCache node Auser:42 plan=freeCache node BDatabaseplan=free

    Step 1 of 7

    The key user:42 hashes to node A, which holds the value plan=free. The database agrees. Everything is consistent.

    Read the steps as text
    1. The key user:42 hashes to node A, which holds the value plan=free. The database agrees. Everything is consistent.
    2. A switch fault cuts node A off for two minutes. The node is still running with its memory intact, but nothing can reach it, so it is removed from the ring and its keys now map to node B.
    3. A read for user:42 goes to node B and misses. The app loads the row from the database and stores it on node B. This is the expected cost of losing a node.
    4. The user upgrades. The app writes plan=pro to the database and deletes the cached key on node B. Node A never hears about the delete and still holds plan=free.
    5. The switch is fixed and node A rejoins the ring. The key user:42 maps to node A again. The next read is a hit, and the answer is plan=free, a value that was deleted two minutes ago.
    6. Nothing will correct this until the TTL expires, because the delete has already happened and will not be sent again. A paying user sees the free plan for as long as the TTL lasts.
    7. The fix is to flush a node before it rejoins, so it comes back empty and refills from the database. Replicas or a spare pool with short TTLs avoid remapping keys in the first place.
    How a cache node that rejoins can serve stale data

    The rule is that a node which has been out of the ring comes back empty.

    Warming up. A new or flushed node misses on everything. Move ring positions to it a few at a time, so the extra misses stay within what the database can absorb, and make sure the application coalesces concurrent misses for one key (see cache stampedes).

    Bottlenecks and failure modes

    • Map disagreement. A proxy that misses a map update routes some keys to the wrong node. Nodes should know the map version and reject requests routed with an old one.
    • Multi-get fan-out. A request for 100 keys touches most of the 24 nodes, so its latency is that of the slowest node. Keep related keys together where possible and set a tight per-node timeout.
    • Connection storms. When a proxy fleet restarts, thousands of connections open at once. Pool connections and ramp them up.
    • Large values. A few 1 MB values on a node hurt its tail latency and eat network. Cap value size and compress in the client.
    • Slab imbalance. If item sizes shift over time, one slab class can be starved while another holds idle memory. Memcached can move pages between classes; monitor evictions per class.
    • Config service down. Nodes and proxies keep serving on the last map. Membership cannot change until it returns, which is acceptable for minutes.

    Trade-offs

    Decision Chosen Alternative Why
    Partitioning Consistent hashing, 150 virtual nodes Fixed hash slots Minimal key movement with no slot table; slots give more explicit control
    Routing Proxy Smart client One implementation and fewer connections; costs a hop
    Node failure Async replica per primary Remap, or a spare pool Database cannot absorb 1.8x reads; costs double the memory
    Eviction Approximate LRU per node Exact LRU, or LFU No global lock on reads; slightly worse choice of victim
    Rejoin Flush before serving Keep contents Never serve values deleted elsewhere; costs a warm-up

    45-minute interview script

    A pacing guide. Interviewers differ, so treat the timings as a default and follow their lead.

    1. 0:00 to 5:00

      Requirements 5 min

      Confirm this is the cache cluster itself, not how an application uses a cache. Agree the operations, value sizes, that data may be lost at any time, and the latency target. Ask how much staleness is tolerable.

    2. 5:00 to 9:00

      Capacity estimates 4 min

      Derive node count from memory, then check throughput per node. Work out what one lost node does to database load. That number decides whether you replicate.

    3. 9:00 to 12:00

      API 3 min

      Get, set with TTL, delete, compare-and-set, and multi-get. Mention persistent connections and pipelining.

    4. 12:00 to 16:00

      Data model 4 min

      Per-node hash table plus recency list, how memory is allocated, and the cluster map with a version number.

    5. 16:00 to 24:00

      High-level design 8 min

      Draw app servers, the routing layer, cache nodes with replicas, the config service and the database behind it all. Narrate a hit, a miss and a membership change.

    6. 24:00 to 31:00

      Deep dive: partitioning and routing 7 min

      Why not mod N, consistent hashing with virtual nodes, and smart client against proxy against server redirects. State which you pick and what it costs.

    7. 31:00 to 36:00

      Deep dive: eviction and memory 5 min

      LRU per node, approximations that avoid lock contention, TTL expiry, and why slab allocation exists.

    8. 36:00 to 43:00

      Deep dive: hot keys and node failure 7 min

      One key that saturates a node, then the options when a node dies (remap, replica, spare pool), the stale rejoin problem and warming a cold node.

    9. 43:00 to 45:00

      Wrap-up 2 min

      Summarise the design, restate the node-loss number and what protects the database, and name what you would add next.

    Sketch this design on the whiteboard Run it as a timed mock

    Key takeaways

    • Memory decides the node count. Throughput per node is rarely the limit for small values.
    • Work out what losing one node does to the database. One node in 24 can nearly double database reads.
    • Consistent hashing with virtual nodes moves about 1/N of keys when a node joins or leaves, where mod N moves nearly all of them.
    • A smart client saves a hop. A proxy gives one place to manage topology and connections. Both must agree on one versioned cluster map.
    • Adding nodes does nothing for a single hot key. Use an in-process cache, replicas or key splitting.
    • A node that rejoins with its old contents serves stale data. Flush it before it takes traffic.

    Try it

    Check yourself

    1. A 24-node cache serves 900,000 reads a second at a 95% hit rate. One node is lost and its keys start missing. Roughly what happens to database read load?
    2. Why do clients place each cache node at many points on the hash ring and not just one?
    3. One key receives 150,000 reads a second, more than a single node can serve. Which change helps?
    4. A cache node drops off the network for two minutes and then returns with its memory intact. Why is that dangerous?
    5. What is the main cost of routing through a proxy tier instead of a smart client library?

    0 of 5 answered

    Flashcards

    These 6 cards are in your review deck. Tap a card to see the answer.

    What decides how many nodes a cache cluster needs?

    Usually memory. Divide the data size (items times average size including overhead) by usable memory per node, then add headroom. Check throughput per node afterwards.

    Three ways to route a key to the right cache node?

    A smart client that holds the cluster map, a proxy tier that clients treat as one server, or server-side redirects, where any node tells the client which node owns the key.

    Why does a cache use slab allocation?

    Items come and go constantly, and a general allocator would fragment memory. Fixed-size chunks grouped into size classes can always be reused by another item of that class.

    What are the options when a cache node fails?

    Remap its keys to the remaining nodes and take the misses, promote a replica, or send its keys to a small spare pool with short TTLs until it is replaced.

    How do you warm a new, empty cache node?

    Shift keys to it gradually so misses stay within what the database can absorb, or have it fill from a warm peer on a miss instead of from the database.

    How does Redis approximate LRU?

    It samples a few keys (five by default) and evicts the one idle longest among them. That avoids maintaining a global recency list on every read.

    Review the deck