How-To Guide

How to Implement CDN Cache Purging

Purge a CDN cache correctly: target by tag or URL, prefer versioned URLs over purges, and bound the effect of a purge on origin load.

On this page

  1. Introduction
  2. Prefer versioned URLs over purging
  3. Purge by tag for a set of objects
  4. Purge by exact URL when the set is known
  5. Handle the load after a purge
  6. Test the purge window and refill
  7. Common pitfalls
  8. Conclusion

Introduction

A CDN serves cached responses from edge locations close to users, which is why it speeds up a site and absorbs load. When content changes, the cached copies must stop being served. The blunt tool is a purge, which removes a copy so the next request fetches a fresh one. The problem with purges is that they push load back to the origin, and a purge of a hot URL can produce a burst exactly when you also changed the content, which is often when the origin is busiest.

This tutorial covers the smarter approach of versioned URLs that need no purge, and the precise purge mechanisms, by URL and by cache tag, for when a URL must stay the same. It ends with tests and the post-purge load handling that keeps a purge from becoming a stampede.

Prefer versioned URLs over purging

The best purge is no purge. If a URL changes whenever its content changes, such as app.abc123.js with a content hash, then deploying new content simply serves a new URL. The old URL keeps its cached copy but is no longer referenced, and clients fetch the new URL once and cache it. No purge is needed, and there is no window where a request is uncached.

Use this for static assets and for anything where the URL may change. Give the asset an immutable Cache-Control so clients keep it for a long time, because the URL is the version. For API responses where the URL must stay stable, versioning the underlying data and changing the key is the equivalent: the URL is the same but the response varies with a version, and the cache can be keyed on it.

// build step: fingerprint the filename with a content hash
// app.js -> app.6f3a1b2c.js
// the HTML references the new name; the old URL is never requested again
// no purge needed, and the new URL is cacheable immutably
res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');

Purge by tag for a set of objects

When a URL must stay the same, purge precisely. Cache tags let you label a response with one or more keys in a header, and a purge targets all objects sharing a tag. Editing one product can purge every page that includes it: the product page, the category listing, the sitemap, and the search results, in one call, without listing each URL or clearing the whole cache.

Set the tags at the origin, choosing keys that reflect the entities a response depends on, such as product:42 and category:7. On an update, purge the entity’s tag, and every response that depends on it is cleared. This keeps the purge scoped and correct, and it adapts as new pages include the entity, because they set the same tag.

// origin: label the response with the entities it depends on
res.setHeader('Cache-Tag', 'product:42, category:7, sitemap');

// on an update to product 42, purge by tag instead of by URL
await cdn.purgeByTag('product:42');   // clears every response tagged with it

Purge by exact URL when the set is known

A URL purge is precise if you know the exact URL and its query string. Purge only the URLs a change affects, not a prefix or a wildcard that clears unrelated content. A wildcard purge clears a large swath and forces the origin to refill it, which is the expensive failure mode. Keep a mapping from an entity to its URLs so a write can purge exactly those.

Include the query string or the variant in the URL you purge. A cache keys on the full URL, so purging /product without the query string leaves /product?color=red cached. Enumerate the variants a response has, or use a tag so the variant question disappears and the purge targets the entity rather than each URL form.

# purge exactly the affected URLs, not a broad prefix
curl -s -X POST https://api.cdn.example/purge -H 'Authorization: Bearer $TOKEN' \
  -d '{"urls":["https://example.com/product/42","https://example.com/category/7"]}'
# avoid clearing /product/* which would push unrelated pages back to the origin

Handle the load after a purge

A purge makes the next request for that URL go to the origin. If the URL is popular, many requests arrive at once, right after the purge. Coalesce them at the origin with single-flight so one fetch fills the cache and the others wait for it, and consider warming the cache immediately after the purge by fetching the URL once yourself, before users do.

Warm the key as part of the update flow: after purging, request the URL from the origin so it is cached again before traffic arrives, or push the new content to the cache if the CDN supports it. This turns a purge from a burst into a controlled refill. Bound the staleness by also keeping an origin-side cache with its own TTL, so a purge that misses an edge is corrected when the origin cache expires.

async function purgeAndWarm(cdn, url) {
  await cdn.purge([url]);
  await fetch(url, { headers: { 'cache-control': 'no-cache' } }); // refill the edge
}
// the next user request hits a warm cache instead of the origin

Test the purge window and refill

Test that the old content is served before the purge and the new content after it, which proves the purge takes effect. Test that a tag purge clears every response that set the tag, including a page added after the tag scheme was defined, which proves the tags are set consistently. Test that the first request after the purge hits the origin once and the cache is refilled, so the second request is a hit.

# before purge: old body from the cache
curl -s https://cdn.example/product/42 | grep -q 'old'
curl -s -X POST https://api.cdn.example/purge -d '{"tags":["product:42"]}'
# after purge: new body, and the second request should be a cache hit
curl -s https://cdn.example/product/42 | grep -q 'new'
curl -sD - -o /dev/null https://cdn.example/product/42 | grep -i 'cf-cache-status\|x-cache'

Common pitfalls

Purging a whole prefix or wildcard when a few URLs changed, purging without the query string so a variant stays stale, no tag scheme so a set cannot be purged precisely, no coalescing or warming so the purge stampedes the origin, and purging at all when a versioned URL would have avoided it are the recurring mistakes. Versioned URLs, tag-based purges, exact URL purges that include variants, and post-purge warming address them.

Conclusion

CDN purging is powerful and easy to misuse. Prefer versioned URLs so a change needs no purge, and when the URL must stay, purge by tag for a set or by exact URL including variants, then warm the key so the next request hits a cache rather than the origin. Self-check by asserting old content before and new after a purge and that the first post-purge request refills the cache once. Then a content change is fast and does not become an origin spike.

Sources: Cloudflare: Cache purge and tags, MDN: HTTP caching, RFC 9111: HTTP Caching.

FAQ

Why is purging considered a last resort?
A purge clears the cached copy, so the next request hits the origin, and if the URL is hot, many requests arrive at once. Versioned URLs avoid this by serving a new URL immediately while the old stays cached, so no request is ever uncached. Purge only when the URL has to remain identical.
What is a surrogate key or cache tag?
A header that labels a response with one or more keys, so a purge can target all objects sharing a tag, such as all pages for one product, without listing each URL. It is how you purge a set precisely instead of clearing broad swaths of the cache.

Related Examples