Purge the CDN cache after a deploy
A deploy that changes origin content does nothing for anyone behind a CDN until the edge cache is invalidated. Either content-hash your filenames so you never need a purge, or purge precisely.
Procedure
- Confirm the stale object is actually cached, and read its age:
curl -sI https://cdn.example.com/app.js | grep -iE 'age|cache-control|x-cache|etag'Age:greater than 0 means the edge served a cached copy;X-Cache: Hit(provider-specific) confirms it. - Prefer immutable, content-hashed assets so a new deploy is a new URL:
location /static/ { add_header Cache-Control "public, max-age=31536000, immutable"; }app.7f3a9c.jsneeds no purge; onlyindex.htmldoes. - Purge narrowly. Invalidate the changed paths, not the whole zone:
# Cloudflare curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE/purge_cache" \ -H "Authorization: Bearer $CF_TOKEN" -H 'Content-Type: application/json' \ -d '{"files":["https://cdn.example.com/index.html","https://cdn.example.com/styles.css"]}' - For a broad change, purge by tag or prefix rather than everything, and expect a cost/rate penalty for
wildcard purges:
aws cloudfront create-invalidation --distribution-id "$DIST" \ --paths '/index.html' '/assets/*' - After the purge, verify the edge serves the new bytes — check the ETag or a version marker, not just
the HTTP 200:
curl -sI https://cdn.example.com/index.html | grep -iE 'etag|x-cache|age' curl -s https://cdn.example.com/index.html | grep -o 'build-[0-9a-f]*' | head -1 - Confirm invalidation completed (CloudFront invalidations are asynchronous):
aws cloudfront get-invalidation --distribution-id "$DIST" --id "$INVALIDATION_ID" \ --query 'Invalidation.Status' # wait for "Completed" - Repeat the purge from a second edge location/region if the CDN is regional.
Pitfalls
- Purging before the origin deploy has propagated serves the old content again and re-caches it.
- A wildcard purges everything and can cost money and hit provider rate limits; scope it.
- HTML cached with a long TTL is the classic bug — always keep
index.htmlshort-TTL or unhashed-purged. Cache-Control: immutableon a non-hashed URL traps clients with the old file for a year.- Browsers cache too; a correct CDN purge still shows stale content until the client TTL expires.
- Purging through a different zone (www vs apex) leaves the other hostname stale.
- Verification by
curlfrom your location may hit a warm edge; usecurl -H 'Pragma: no-cache'or check theAgeheader.
Verification
curl -sI "https://cdn.example.com/index.html?cb=$(date +%s)" | grep -iE 'x-cache|age|etag'
aws cloudfront get-invalidation --distribution-id "$DIST" --id "$INV" --query 'Invalidation.Status'
Pass means Age is 0 / X-Cache: Miss and the invalidation reports Completed. Report: "purged
/index.html + /assets/*, invalidation Completed, edge now serves build-9f2c1."