Distributed caches
One cache server is not enough. Learn how to spread keys over many, what each lost node costs you, and how to keep the copies honest.
Updated since you finished it. We changed this lesson after you marked it done. Your progress is kept.
What broke
On 22 February 2022, just after 6 a.m. Pacific time, Slack users started to have trouble connecting. Responders found very high load on one part of the database. 1
Slack kept hot data in Memcached, in front of its sharded database. Mcrouter sent each key to a cache node by consistent hashing. A control plane called Mcrib replaced any missing cache node with an empty spare. A node that came back after some time away was flushed. 1
That morning, a routine upgrade restarted the Consul agents on 25% of the servers. Each time a cache node's agent restarted, the node left service discovery. Mcrib swapped in an empty spare, and the cache hit rate dropped. 1
One query made this much worse. When a client started, it loaded the members of every group direct message the user was in. That data was sharded by user, so "even one channel missing from cache" meant a query on every shard. Database load grew "superlinearly" as misses grew. Most of those queries timed out, so the cache could not fill again. 1
Pausing the upgrade early on did not help. Slack had to limit how many clients could start. It also changed the query to read only the missing data. 1 Mcrib worked as designed. It was so fast at replacing nodes that the cache emptied faster than it could refill. 1
The idea in simple words
A distributed cache is many cache servers that act like one big cache. You need one when a single server cannot hold the data your app reads, cannot serve the request rate, or would hurt too much if it died.
This lesson builds on caching and stampedes and sharding. Here you add four new questions:
- Where does each key live, and what happens when nodes come and go?
- What gets thrown out when memory is full?
- What about one key that is far too busy?
- How do you keep the cache in step with the database?
The key idea. Your database is sized for the misses, not for the full traffic. The hit rate is a capacity number. Anything that empties part of the cache (a lost node, a deploy, a new region) sends a sudden wave of load to your database.
How it works
Why one node is not enough
In 2013, Facebook ran hundreds of Memcached servers in each cluster, to take load off its databases. One popular page fetched 521 different cached items on average. 2 So one request can touch many cache servers. Once you have many nodes, every app server needs a rule that maps a key to a node.
Three ways to spread keys
A library in each client. The app hashes the key itself, usually with consistent hashing. There is no extra hop. But every client, in every language, must use the same hash and the same server list.
A proxy. The app talks to a router, and the router picks the node. Mcrouter is "a memcached protocol router". Its README says it handles "almost 5 billion requests per second at peak". 3 Its HashRoute picks a node from the key hash, with Ch3 as the default hash. 4 Twemproxy does the same job for Memcached and Redis. It keeps the number of connections to cache servers low. Its default ketama mode is consistent hashing. 5
Redis Cluster. The servers own the map. Each key goes to one of 16,384 hash slots, and each primary owns some slots. Clients cache the slot map. If a client asks the wrong node, it gets a MOVED reply with the right one. 6 There are no proxies. 6 For details, see Redis in depth.
Adding or losing a node
When Redis Cluster moves a slot, it moves the keys to the new node with MIGRATE. 6 The data stays warm.
A plain Memcached pool keeps no copies. A new node on the ring takes over about 1/(N + 1) of the keys, and those keys simply miss. A dead or replaced node loses all its keys. With 10 nodes, and keys and traffic spread evenly, losing one costs you about a tenth of your hits. That is what happened to Slack, one node at a time. 1
Facebook chose not to rehash a dead server's keys over the others. One key can be 20% of a server's requests, so the server that takes it over may fall over too. Instead, failed requests go to a small spare pool called Gutter, about 1% of the servers. Its entries expire quickly. 2 This cut client-visible failures by 99%. 2
Eviction and sizing
When memory is full, the cache must evict something. The main policies in Redis are: 7
- LRU (
allkeys-lru) drops the key used least recently. It is the suggested default when some keys are read far more than others. - LFU (
allkeys-lfu) drops the key used least often. Its counters decay, by default every minute, so old favourites can leave. - TTL-based (
volatile-ttl) drops keys with the shortest time left to live.
Redis does not track exact LRU. It samples a few keys at random and drops the ones unused the longest. maxmemory-samples sets how many. 7
Size the cache from your working set: the data you read in a day or a week, not all the data you have. Facebook's paper shows the daily and weekly working sets of two families of keys. 2 Then check the result. Hit rate is keyspace_hits / (keyspace_hits + keyspace_misses). If it is low and evicted_keys is high, the right keys are being thrown out too often. 7
Hot keys
One hot key can get more traffic than its node can serve, however many nodes you add. First, find it. Count requests per key in the client or proxy, on a sample of traffic.
Then pick a fix:
- A near cache. Keep the hottest keys in each app server's memory. Redis can help: with tracking on, the server remembers which keys a client read. It sends an invalidation message when one of them changes. If that message can beat a read's reply, store a "caching-in-progress" placeholder first. 8 Flush the local cache if that connection drops. Put a maximum TTL on every local key. 8
- Copies of the key. Facebook copies some keys to several servers in a pool. In its example, each request needs all 100 keys. Splitting them over two servers still sends every request to both. Copying them halves the load on each. Every write must then delete every copy. 2
- Split the key. For a hot counter, split it into many keys, as in the sharding lesson.
Keeping the cache in step with the database
Facebook updates the database, then deletes the key from the cache. It deletes, not updates, because a delete is idempotent. 2 Deleting still leaves a race. Step through it.
- Reader A asks the cache for key k and misses. The cache gives A a lease: a token that A must show when it puts a value back.
- A reads the database and gets v1. Then A is slow for a moment, for example because of a long pause or a slow network.
- Writer B updates the database to v2 and deletes k from the cache. The delete also cancels A's lease, L1.
- A finally sends set k = v1. Without leases the cache accepts it. Now the cache holds old data. It stays until the TTL ends or the next write deletes it.
- With leases, the cache checks L1, sees it was cancelled, and rejects the set. The next reader misses and loads v2.
Facebook calls this a "stale set". Its fix is a lease: a 64-bit token the cache gives a client on a miss. The client must show the token to set the value. A delete cancels the token, so a late set with an old value is rejected. 2
Across regions. To reach other clusters, Facebook does not rely on web servers to send deletes. A daemon called mcsqueal reads the SQL each database commits and sends the deletes to the caches. 2 Because deletes live in the database log, lost ones can be replayed. Mcsqueal also runs on the replica databases in other regions. Each one sends a delete only when the change reaches its own database. So a reader there is less likely to put old data back in the cache. 2
Cold start and warm-up
A new or rebuilt cache cluster has a very poor hit rate. Facebook lets a cold cluster read misses from a warm cluster, not the database. That brings it back to full capacity "in a few hours instead of a few days". 2 To avoid a race, deletes in the cold cluster block new adds for two seconds. 2 Mcrouter offers this as WarmUpRoute. Gets try the cold node first and fall back to the warm one. 4
If you have no warm copy, let traffic in slowly, as Slack did. 1
Trade-offs
| Option | Extra hop? | When a node changes | Watch out for |
|---|---|---|---|
| Hashing in each client | No | Keys on the moved arc miss. | Every client must agree on the hash and the server list. |
| Proxy (mcrouter, twemproxy) | Yes | Keys on the moved arc miss, unless you add warm-up or copies. | The proxy is one more thing to run and scale. |
| Redis Cluster | No Clients may get a redirect. | Keys move with their slot. | Multi-key commands need all keys in one slot. |
| Near cache | No network at all. | Not affected. | Stale local copies if invalidations are lost. |
| Copies of hot keys | Depends on the router. | Other copies keep serving. | Every write must delete every copy. |
Simple rule: start with a proxy or a cluster client and LRU. Add near caches and copies only for the keys you have measured as hot.
At work: how a senior uses this
- Ask: "If we lose one cache node, or a whole cluster, how much extra load hits the database?" Then test it.
- Make misses cheap. A large part of Slack's problem was a miss that queried every shard. 1
- Limit how fast nodes are replaced or flushed. Fast churn empties the cache faster than misses refill it.
- Chart hit rate, evictions and the top keys per node, next to database load.
- Write down which data may be stale and for how long. That decides between delete, leases and near caches.
- Plan warm-up before a migration, a new region or a full restart.
With AI
What to ask the agent
"Here is our cache-aside code. Find every place that sets a cache value after a database read. Show me the race with a concurrent write, and add a version check."
"Write a script that replays 1 hour of our key access log against an LRU cache of 4, 8 and 16 GB. Print the hit rate for each size."
"Add a near cache for these 20 keys with a 5-second maximum TTL, Redis client tracking, and a flush when the tracking connection drops."
What to check yourself
- Writes delete the cache key after the database commit.
- Every local copy has a maximum TTL and a memory limit.
- The replay test uses real, skewed traffic. Uniform fake keys hide hot keys.
- There is a limit on how many clients can start at once, for the day the cache is empty.
Check yourself
Your progress is saved only in this browser. Export it to keep it safe.
You have finished 5 lessons. Your progress lives only in this browser. Export a copy so you don’t lose it.
Go deeper
Show 8 sources and related lessons
- Laura Nolan (Slack Engineering), “Slack’s Incident on 2-22-22” (2022) (opens in a new tab)
A real cache cascade. Empty Memcached nodes, a query that hits every shard, and how Slack throttled its way back. - Nishtala et al., “Scaling Memcache at Facebook”, NSDI 2013 (USENIX) (opens in a new tab)
Look-aside caching, leases (3.2.1), replication in pools (3.2.3), Gutter (3.3), cross-region deletes (4.1, 5) and cold cluster warmup (4.3). - mcrouter README (GitHub, meta/mcrouter) (opens in a new tab)
What the Memcached router does, with its feature list and scale. - mcrouter wiki, “List of Route Handles” (opens in a new tab)
The building blocks of mcrouter's config, including HashRoute and WarmUpRoute. - twemproxy (nutcracker) README (GitHub, twitter/twemproxy) (opens in a new tab)
A small proxy for Memcached and Redis, with its key distribution modes. - Redis documentation, “Redis cluster specification” (opens in a new tab)
Hash slots, MOVED and ASK redirects, and how slots move between nodes. - Redis documentation, “Key eviction” (opens in a new tab)
Every eviction policy, how LRU and LFU are approximated, and how to read your hit rate. - Redis documentation, “Client-side caching reference” (opens in a new tab)
Server-assisted local caches, invalidation messages, and the race you must handle.
Real incident: Slack, 22 Feb 2022: Slack: emptied cache nodes turned each miss into a query on every database shard
Case studies: Meta: Scaling memcache to billions of requests a second · Meta: TAO: a graph cache in front of sharded MySQL · Slack: Flannel: an edge cache so huge teams can start fast
Related: Caching and cache stampedes · Sharding and consistent hashing · Redis in depth · CDNs and HTTP caching · Load shedding and graceful degradation
Before this: Caching and cache stampedes and Sharding and consistent hashing. Next: Redis in depth, CDN and HTTP caching and Load shedding.