Cache Purge Testing: How to Test a CDN Flush Before Production
Test a cache purge under load before you run one in production: warm the cache, fire the purge mid-run, and measure origin RPS, hit ratio and recovery.
A cache purge test fires a purge in the middle of steady load against a warm cache and measures what the origin does next. You record hit ratio, origin requests per second, time to first byte (TTFB) and errors until each returns to baseline. Run it on a staging zone or a scoped purge before you touch production. The purge command succeeds. The refill that follows it causes the damage.
Most outages tied to cache flushes follow one pattern. Someone invalidated a large set of objects at a busy hour, the edge started missing, and the origin received traffic it was never sized for. A cache warming failure is the cold-start version of the same story. This test shows you the size of the surge before production does.
Prerequisites
- A staging CDN zone or distribution with the same cache rules as production. If you have none, a low-traffic path you are allowed to purge.
- A purge API token and the provider’s purge rate limit.
- A load script (k6, JMeter or another executor) that sends a realistic URL mix.
- Origin-side metrics: request rate, CPU, error count. The load tool sees the edge, not the origin.
- A response header that reports cache status, such as
X-CacheorCF-Cache-Status. The name depends on the provider. - Agreement from on-call, and from the provider if your contract requires notice.
What a purge does to your traffic
A purge removes an object from every edge that held it, or marks it stale. The next request to each edge is a miss and goes to the origin. While that first fetch is in flight, every other request for the same object is also a miss unless the CDN collapses them into one.
That gives you two multipliers. The first is the number of edges or edge tiers that miss independently. The second is the number of concurrent users per edge during the fetch window. The window lasts as long as the origin takes to answer. A slow origin stretches the window, which admits more concurrent misses, which slows the origin further. The stampede article walks through that loop for application caches. A CDN purge is the same loop with more layers in front.
Purge types and their blast radius
Providers name these differently. Four types cover most of them.
| Purge type | What it invalidates | Blast radius | Test it with |
|---|---|---|---|
| Single URL | One object, often every variant of it | Small, unless the URL is your busiest asset | The hottest URL in your traffic mix |
| Tag or surrogate key | Every object carrying a label | Depends on how many objects share the tag | The largest tag in production |
| Prefix or wildcard | Every URL under a path | Often larger than the author expects | A prefix that covers a full section |
| Full flush | The whole zone or distribution | The entire cache refills from origin | Staging only, until the numbers pass |
Two details change the result. Some providers delete the object and others mark it stale. A stale object is revalidated with a conditional request, which costs the origin far less than a full download. A URL purge also drops every cache-key variant of that URL (compressed and uncompressed, different query strings), so one call removes several entries. Read your provider’s documentation, then confirm the behaviour with the cache status header after a purge.
Propagation time is part of the test
A purge is not instant. The API call returns and the invalidation spreads to the edges over a period that varies by provider and purge type. During that period some edges serve the old object and others have dropped it. Users see stale content, and the origin sees a ramp instead of a spike.
Measure it. During the test, poll the purged URL from several locations once per second. Log the cache status header and a version marker from the body. The time from the API call to the last stale response is the propagation time for that purge type. Do not copy a number from a vendor page into your runbook. Record your own.
Soften the surge with collapsing, a shield and stale serving
Three features set the size of the origin spike. Test each one on and off so you know what each is worth.
- Request collapsing (also called coalescing) sends one origin request per object while other requests for the same object wait for the response. It removes the per-user multiplier.
- An origin shield is a middle cache tier. Every edge misses to the shield, and the shield fetches from the origin once. It removes the per-edge multiplier. The academy page on origin shield and offload testing shows how to verify it.
- Stale-while-revalidate and stale-if-error let the edge serve the expired copy while one request refreshes it, and keep serving the old copy when the origin returns errors. Users see fast responses during the refill. These directives apply to expiry and revalidation. A hard purge deletes the object and leaves nothing to serve stale, so ask your provider about a soft purge that marks objects stale.
App caches flush the same way
The same test covers Redis, Memcached and in-process caches. A FLUSHALL empties every key at once, and the first request for each key goes to the database. The database is the origin here. Watch query rate, connection pool wait and query latency. The database bottlenecks article lists the storage-side signals. If your cache supports deleting by key pattern or namespace, test that path as well. It is the one you want to use.
How to run a cache purge test
- Choose the environment. Use the staging zone, or a scoped purge on a low-traffic path. Check the purge API rate limit so the test does not exhaust your budget. Tell on-call.
- Pick one purge per type. Use real production objects: the hottest URL, the largest tag, a prefix that covers a section.
- Build a realistic traffic mix. Match production URL diversity and weighting. A narrow mix gives a hit ratio that is wrong before the purge starts. The CDN and WAF article explains how to keep test traffic from being blocked or distorted at the edge.
- Warm the cache. Run load until the hit ratio is stable at its production level. Record baselines for hit ratio, origin requests per second, p95 TTFB and error rate.
- Hold steady load at the planned peak rate. Use the rate of the hour you plan to purge in, not the daily average.
- Fire the purge once, mid-run. Use a one-shot scenario or thread that waits until minute N, calls the purge API once and stops. Log the exact timestamp.
- Keep the load running through recovery. Continue until every signal is within 10 percent of baseline, or until a time limit you set in advance.
- Repeat for each purge type. Start every run from a freshly warmed cache.
- Repeat the riskiest purge with the shield and collapsing toggled. Run it once off and once on to see what each is worth.
This k6 fragment holds the load in one scenario and fires the purge once at minute 5 in another:
import http from 'k6/http';
export const options = { scenarios: { traffic: { executor: 'constant-arrival-rate', rate: 200, timeUnit: '1s', duration: '15m', preAllocatedVUs: 200, exec: 'browse' }, purge: { executor: 'per-vu-iterations', vus: 1, iterations: 1, startTime: '5m', exec: 'purgeOnce' }, },};
export function browse() { const r = http.get(`${__ENV.BASE_URL}/products/${Math.ceil(Math.random() * 500)}`); // log cache status so hit ratio is computed per second console.log(`${Date.now()} ${r.headers['X-Cache'] || 'none'}`);}
export function purgeOnce() { console.log(`PURGE_AT ${Date.now()}`); http.post(__ENV.PURGE_URL, JSON.stringify({ tags: ['catalogue'] }), { headers: { Authorization: `Bearer ${__ENV.PURGE_TOKEN}`, 'Content-Type': 'application/json' } });}The header name and the purge endpoint differ by provider, so substitute your own. In JMeter, a separate thread group with one thread, one loop and a start delay of 300 seconds does the same job. Store the purge token as a secret, never in the script.
What to measure and what counts as a pass
Record each of these as a time series with the purge timestamp marked:
- Hit ratio. Count it from the cache status header per second. A provider dashboard averages over minutes and hides the dip.
- Origin requests per second. Take it from the origin’s own logs or metrics. Add duplicate in-flight requests for one object if you see them.
- TTFB at p50 and p95. The p95 shows the users who landed on a miss.
- Error rate and status codes. Count 5xx, timeouts and 429s separately. Retries add load, so count them too.
- Time to recover. The span from the purge call until hit ratio and origin load return to your tolerance.
Write the pass criteria before the run. For example: origin CPU stays below 70 percent, p95 TTFB stays below 1.5 seconds, the error rate stays inside budget, and hit ratio returns to 90 percent of baseline within 5 minutes. The numbers are yours to set. Set them before you see the result, so the result does not argue you into a pass.
Worked example with hypothetical numbers
These figures are invented to show the arithmetic. They are not a benchmark.
A catalogue site serves 2,000 requests per second at a 96 percent hit ratio, so the origin sees about 80 requests per second. The origin is comfortable up to around 400. The team plans a tag purge of the catalogue tag, which covers most pages.
The test warms the cache, holds 2,000 requests per second and fires the purge at minute 5. Hit ratio drops to 40 percent at its lowest point. The origin then sees 60 percent of 2,000, about 1,200 requests per second against a capacity of 400. Origin latency climbs, p95 TTFB goes from 90 ms to several seconds, and 5xx errors appear. Recovery is slow because the overloaded origin refills the cache slowly.
The team enables request collapsing and the origin shield and repeats the run. Hit ratio at the low point is 55 percent, but misses for one object reach the origin once instead of once per user. Origin load peaks near 300 requests per second and recovers in two minutes. That meets the criteria. The team then splits the single tag into per-section tags and purges one section at a time, which keeps the peak under 150.
The test supports a concrete decision: purge by section, keep the shield on, and never run the full flush above a stated traffic rate.
Safety rules for the real purge
- Run the full flush on a staging zone first. Purge production only after the numbers pass at the traffic of the hour you plan to use.
- Purge off-peak when you have the choice. Purge in small scoped steps when you do not.
- Respect the purge API rate limit. A loop over thousands of URLs hits the limit and leaves you half-purged.
- Tell on-call and the provider before a large test. Agree a stop condition, such as an error rate at which the run is cancelled.
- Never point the test purge at a production zone because staging is inconvenient. A purge test issues real invalidations.
Troubleshooting
- Hit ratio never drops after the purge. The purge did not match your cache keys. Check the cache status header on the purged URL, and confirm the purge covers every key variant (query string, compression, host).
- Hit ratio drops but the origin shows no spike. Your load tool measures the edge and your origin metrics sit behind a shield or an app cache. Add metrics at the origin and at the shield.
- The purge API returns 429. You hit the rate limit. Batch URLs into one call, use a tag purge, or space the calls out.
- Stale content persists for minutes. Propagation is slower than expected, or an intermediate cache ignores the purge. Poll from several locations and find the layer that still serves the old object.
- Hit ratio looks wrong before the purge. The traffic mix is too narrow or too uniform. Rebuild it from production logs.
- The origin falls over in the first run. Stop the run at your stop condition. Enable the shield or collapsing, lower the load, and repeat to find the safe rate.
Run it in MaxoPerf
MaxoPerf runs the traffic side. You bring the k6, JMeter or other script, set the load profile, and read latency, throughput and error series live in the run. Your own script makes the purge call, as in the fragment above, because the platform does not drive a CDN purge API for you. Add failure criteria on error rate and latency so a run that breaches your pass conditions is marked failed. Use the run comparison workflow to set the shielded run against the unshielded one. Origin-side metrics come from your own monitoring. The academy page on cache invalidation and purge testing lays out the matching test patterns.
Questions this article answers
How do you test a cache purge?
Warm the cache, run steady load at your production rate, and fire the purge once partway through the run. Record hit ratio, origin requests per second, TTFB and error rate as time series, then measure how long each takes to return to baseline. Run it against a staging zone or a scoped purge, not a production full flush.
What happens to the origin after a CDN purge?
Every edge that held the purged object now misses on its next request and fetches from the origin. If the object is popular, many edges and many concurrent users hit the origin at once, which is the thundering herd. Request collapsing and an origin shield reduce it by turning many misses into one origin fetch per object.
How long does a CDN purge take to propagate?
It depends on the provider and the purge type, and it ranges from about a second to several minutes. Do not rely on a published figure. Measure it by polling the purged URL from several locations and recording when the cache status header flips from hit to miss everywhere.
Is a tag purge safer than a full cache flush?
Usually, because it invalidates only the objects that share a tag, so the origin sees a bounded refill instead of the whole catalogue. The blast radius still depends on how many objects carry the tag. Test the largest tag you have, not a small one.
Does flushing Redis or Memcached cause the same problem?
Yes. An application cache flush empties every key at once, so the first requests for each key all go to the database. The mechanics match a CDN purge, with the database as the origin, and the same test applies: steady load, flush mid-run, measure database load and recovery.