Testing for Cache Stampedes: Cold Starts, Expiry Storms, and Request Coalescing
A warm cache hides what happens when many keys expire at once or a cache restarts. Test that transition and measure origin load as well as the hit rate.
A cache stampede happens when many requests miss the same data at the same moment and every one of them goes to the origin to rebuild it. The origin was sized for a 95 percent hit rate and now receives the full request rate for that key, or for every key that expired together. The usual load test never sees it, because the usual load test warms the cache in the first minutes and then holds a steady state.
The steady state answers one question: how does the system behave when the cache is full of the right things. The stampede question is about the transition. Test that transition on purpose, and measure the database or backing service rather than the cache’s own hit-rate counter.
Three ways a cache empties
The failure has distinct causes, and each needs its own scenario.
A cold start is the cache beginning empty: a deploy that replaces cache nodes, a restart, an eviction event, a new region going live. Every key is a miss until it has been fetched once, and the first seconds carry the whole request rate against the origin.
An expiry storm is many keys sharing the same time to live and the same creation time. If a batch job populates ten thousand entries with a 300-second TTL, all ten thousand expire inside the same second 300 seconds later. The cache was warm and then it was not, with no deploy involved.
A hot-key expiry is one popular key expiring under high concurrency. The key may be a home page fragment, a feature flag set, a pricing table, or a session lookup that every request touches. While one request rebuilds it, hundreds more arrive, see the miss, and start rebuilding too.
A fourth case belongs on the list for any system with request-time cache fill: a key that does not exist at all. Repeated lookups for missing records bypass the cache each time if absence is not cached, which is a stampede that never ends.
What the origin sees
Work out the arithmetic before building anything. Suppose a hot key receives 2,000 requests per second and takes 300 ms to rebuild from the database. During the rebuild window, about 600 requests arrive. If none of them coordinate, the origin receives 600 identical queries for one row of work. The query takes longer under that contention, which stretches the window, which admits more requests. This is a feedback loop, and it is the reason a stampede escalates instead of staying a short spike.
Those figures are an example, but the formula applies to your system: concurrent rebuilds equal request rate for the key times rebuild duration, until the first rebuild completes. Rebuild duration under contention is longer than rebuild duration measured alone, so measure it with the load applied.
Design the test around the transition
For a cold start, run the load at the planned rate and clear the cache, or point traffic at a freshly started cache, partway through the run rather than at the start. The line you need is a before, during and after view. Record origin query rate, origin connection use, origin p95 latency, and end-to-end latency, each as a time series with the clear-cache moment annotated. The recovery time, from the clear until origin load returns to its earlier level, is the headline number.
For an expiry storm, load the cache with a deliberately uniform TTL, then let the TTL pass under steady traffic. This needs a test that runs longer than the TTL, so shorten the TTL in the test environment only if the proportions stay representative. A 5-second TTL with 10,000 keys is a different load shape from a 300-second TTL with the same keys, because the refill rate per second changes. If you shorten it, say so in the report.
For a hot-key expiry, direct a large share of requests at one key, then expire that key by TTL or by explicit delete while the load runs. This is a skewed workload, and a uniform pick from a large parameter file will not produce it. The parameterized data and cache bias article explains how an over-broad data set accidentally lowers the hit rate in one direction, and how a narrow one raises it in the other. Here you want a weighted pick on purpose.
For the missing-key case, request identifiers that do not exist at a modest rate and watch whether each one reaches the origin. If it does, check whether the application caches negative results, and for how long.
Measure the origin as well as the hit rate
Hit rate is a ratio, and ratios hide volume. A cache at 98 percent hit rate with 100,000 requests per second sends 2,000 requests per second to the origin. The same cache at 90 percent, which sounds like a modest decline, sends 10,000: five times the work. In an incident the hit rate rarely falls to zero. It falls enough to push the origin past its capacity.
Add these origin-side signals to the dashboard before the test:
- Queries or calls per second reaching the backing store, grouped by statement or endpoint.
- Duplicate in-flight work: how many identical queries run at the same time. Some databases expose active queries, and an application-level counter around the rebuild function works everywhere.
- Connection pool wait time and active connections, since a stampede drains the pool before it drains CPU. The database bottlenecks article covers what to look at on the storage side.
- Latency for requests that did hit the cache during the event. If hot data slows too, the stampede has spread beyond the keys that missed.
The mitigations, and how to check each
A test is only useful if it can show a mitigation working or failing. These are the common ones.
Request coalescing, sometimes called single-flight, lets one request rebuild a key while concurrent requests for the same key wait for that result. A minimal version in application code looks like this:
const inflight = new Map();
async function getOrBuild(key, build) { const cached = await cache.get(key); if (cached !== undefined) return cached; if (inflight.has(key)) return inflight.get(key); // join the rebuild const p = build().then(async (v) => { await cache.set(key, v, ttlWithJitter()); return v; }).finally(() => inflight.delete(key)); inflight.set(key, p); return p;}Notice the limit. This map lives inside one process. With 20 application instances you can still have 20 concurrent rebuilds of one key, so a distributed lock or a cache-level lease may be needed for expensive work. Test with the real instance count, not a single node.
TTL jitter adds a random amount to each expiry so keys created together do not expire together. Verify it by plotting the refill rate over time after a bulk load. A flat refill rate means the jitter works. A sawtooth with a period equal to the TTL means it does not.
Stale-while-revalidate serves the old value for a short grace period while one request refreshes it. The test has to check both halves: users get fast responses during the refresh, and the refresh itself happens once rather than once per request.
Early or probabilistic refresh rebuilds a key shortly before it expires, with some randomness, so a hot key is replaced before it disappears. A test confirms that the miss rate for the hot key stays near zero across a TTL boundary.
Cache warming before a release, covered in the Roblox cache warming write-up, is a mitigation for cold starts. Check that the warm-up job itself does not become the stampede: a warming process that loads every key at once is a self-inflicted version of the problem.
Reading the result
A good cold-start run shows origin load rising, peaking below the origin’s saturation point, and falling back as the cache fills. A bad one shows the origin queue growing during the miss window, timeouts appearing in the application, and retries adding to the load. Retries deserve a count of their own, because they turn a short stampede into a sustained one.
Write the pass condition before the run. For example: with the cache cleared at the planned peak rate, origin CPU stays under a stated ceiling, the error rate stays within the budget, and the p95 returns to baseline within a stated number of minutes. If the system fails, the finding names the mechanism (no coalescing, aligned TTLs, uncached negatives) and the fix follows from it.
Running it with MaxoPerf
On MaxoPerf you can run the scripted load through the executor you already use and watch the run’s latency and error series live while a separate step clears the cache in your test environment. Failure criteria on error rate and latency turn the recovery condition into a pass or fail result, and the run comparison workflow lets you set a run with coalescing enabled against one without it.