Thundering Herd: When Cache TTLs Die in Sync

Our database administrator was the first to see the graph and sent over the screenshot with the message "what is this, a comb?" The MySQL CPU graph really did look like a comb: every hour on the hour, to the second, a 95 percent tooth lasting 90 seconds. The 58.5 minutes in between were calm. There was no scheduled job running on the hour in the application. Traffic didn't rise at the top of the hour. And yet the database, like a wind-up clock, went through the same fit at every peak.

The answer lay in an innocent-looking side effect of the deploy we had done that morning. The deploy had restarted all application processes at 10:00. The cache was empty, and the first requests filled every cache key within the same few minutes. And every key had the same TTL: 3600 seconds. So thousands of keys born around 10:00 all died together around 11:00. They all wanted to be brought back to life at the same moment, and they all rushed to the database. The revived keys got the same TTL again, and their next appointment with death was set for 12:00. The herd would carry its own synchronization forever.

The Sneakier Herd Within the Herd

Looking closer, we saw that the problem had two layers. The first is the one I just described: thousands of different keys dying simultaneously. The second played out inside a single key, and it was more destructive. Our most popular key, the result of a query that fed the entire vehicle list screen, was read roughly 400 times a second. The moment that key died, it took 1.2 seconds for the first request to run the query and fill the cache. The 400-odd requests that arrived during those 1.2 seconds found nothing in the cache, and each one independently sent the same heavy query to the database. In other words, a single key dying meant 400 copies of the same query running at once. This is exactly what the literature calls a cache stampede, and regardless of TTL synchronization, it's the fate of every sufficiently popular key.

When the popular key dies, the cache stays empty for 1.2 seconds and 400-odd requests send the same heavy query to the database.
A cache stampede is the fate of every sufficiently popular key.

The First Remedy: Spreading Out the Appointments

The remedy for the first layer is embarrassingly simple: add randomness to the TTL. We dropped the 3600 constant; on every write, the TTL is picked at random from the range 3600 ± 15 percent. That way, keys born in the same minute die spread out between 54 and 69 minutes later, and the mass appointment with death disperses on its own. At the first top of the hour after a deploy, the comb tooth dropped from 95 percent to 40. Ranked by payoff per one-line change, this is near the top of my career.

The diagnosis itself is worth telling, because at first glance nobody blamed the cache. The hourly pattern first sent us looking for a scheduled job; there wasn't one. Then we blamed one of our customers' integrations; that wasn't it either. The key clue came from the database query logs: the queries running at the moment of the tooth were ordinary in kind but abnormal in number, and almost all of them were queries that should have been served from the cache. At that point the question changed. It was no longer "who is running these queries?" but "why aren't these queries in the cache?" Finding the right question took longer than finding the answer. It usually does.

A fixed TTL makes keys die at the same moment; 15 percent randomness spreads the deaths over 54-69 minutes and shrinks the CPU tooth.
A one-line change shrank the comb's teeth.

The Second Remedy: One Cook in the Kitchen

For the popular-key problem, we set up a single-flight lock. When a request finds the key empty, instead of rushing straight to the query, it first tries to acquire a short-lived lock specific to that key in Redis (SET NX, with a 5-second lifetime). The one request that gets the lock runs the query and fills the cache; the ones that don't fall into one of two paths. If we have a stale copy of the key, we serve it: a 30-second-old version of the vehicle list is always better than a 1.2-second wait and a crashed database. If there's no stale copy either, they poll the cache at short intervals. To make this possible, when a key is due to be deleted, we don't actually delete it; we keep it a while longer with an "expired" marker. It's a handmade version of the stale-while-revalidate pattern.

The single-flight lock has its own trap, so let me point it out before anyone falls in: what happens if the process holding the lock dies before it finishes the query? The lease duration is vital here. The lock drops on its own after 5 seconds, and the next request takes over the watch. In our first draft, we had acquired the lock with no expiry; a teammate's question in code review, "if this process dies right here, does everyone eat stale data forever?", saved us. In distributed locks, ownership is always a lease. A lock you own outright takes the system hostage once its owner dies.

Together, the two remedies erased the comb from the graph. The p99 latency at the top of the hour dropped from 4.2 seconds to 210 milliseconds, and the database's hourly CPU tooth fell from 95 percent to 12.

Let me note a third technique for popular keys: probabilistic early refresh. The idea is that instead of waiting for the key to die, one of the requests refreshes the cache in the background before it expires, with a small probability that grows as the end of the TTL approaches. That way, the popular key theoretically never dies; the refresh happens in the shadow of end-user requests. We use this only on the top 20 keys, because it's subtler than the lock mechanism and, if misconfigured, generates unnecessary refresh traffic. For the thousands of medium-temperature keys, the single-flight lock is both sufficient and easy to reason about. Rather than applying every technique to every key, tiering keys by temperature cuts the maintenance burden significantly.

A single-flight lock, a stale copy, a leased lock and probabilistic early refresh prevent a stampede on popular keys.
Tiering keys by temperature reduced the maintenance burden.

The Deploy Itself Is a Stampede Too

One scenario remained: the moment of the deploy itself. No matter how much jitter we add, when the processes restart, the cache is empty and the first few minutes are defenseless. We took two small measures for this. For the 20 most expensive keys, we added a warm-up step at the end of the deploy script: these keys are filled in the background before the application is opened to traffic. And we restart processes not all at once but in waves, two minutes apart, so the full caches of the old processes cover for the empty caches of the new ones. With these two measures, the error rate in the first 10 minutes after a deploy came close to zero.

After erasing the comb, we went looking for other symptoms of the same disease and found two more. The first was on the mobile side: whenever the server had a brief outage, thousands of mobile clients lost their connections at the same moment, and they all retried at the same fixed interval, once every 30 seconds. The first seconds after recovery were met by a synchronized wave of requests, and the server dropped back to its knees as soon as it got up. We added exponential backoff and random jitter to the retry interval, and the wave flattened out. The second was at midnight, 00:00: five separate nightly jobs, written by different teams at different times, were piling on top of each other even though nobody had coordinated them, simply because they had all picked the round hour. Replacing the zeros in the cron lines with random minutes split the midnight peak on the disk graph in two. Synchronization is an uninvited guest; it sneaks in anywhere you write down a fixed number.

The general principle this case taught me is this: when you give the same constant to thousands of actors in a system that seem independent of one another, you unknowingly turn them into an orchestra, and that orchestra always plays the worst piece together. TTLs, retry intervals, polling intervals, cron minutes: all of them are vulnerable to the same disease, and they all share the same vaccine, which is randomness. If your graphs have periodic teeth you can't explain, drop me a line. Once you recognize the comb pattern, you start seeing it everywhere.