CDN Cache Invalidation Strategies
Explore strategies for invalidating CDN caches including purge APIs, versioned URLs, surrogate keys, and instant purge vs. eventual consistency trade-offs.
Detailed Explanation
CDN Cache Invalidation
CDN cache invalidation is the process of removing or updating cached content before its max-age or s-maxage expires. The classic computer science quote applies: "There are only two hard things — cache invalidation and naming things."
Strategy 1: URL Versioning (Recommended)
Change the URL when content changes:
/assets/app-v2.3.1.js
/assets/app-BkQ3x9f2.js (content hash)
Pros: Instant, reliable, no purge needed Cons: Requires build tooling and HTML updates
This is the gold standard for static assets. The Cache-Control header can be maximally aggressive because the URL itself is the version.
Strategy 2: Purge API
Most CDNs offer an API to purge specific URLs or patterns:
# Cloudflare
curl -X POST "https://api.cloudflare.com/client/v4/zones/{zone}/purge_cache" \
-d '{"files":["https://example.com/api/products"]}'
# Fastly
curl -X PURGE "https://example.com/api/products"
Pros: Immediate invalidation, no URL changes needed Cons: API calls required, propagation delay (1–30 seconds)
Strategy 3: Surrogate Keys (Cache Tags)
Tag cached responses with logical identifiers:
Surrogate-Key: product-123 category-electronics
Then purge by tag:
curl -X POST "https://api.fastly.com/service/{id}/purge/product-123"
Pros: Purge all pages containing a specific product with one API call Cons: Not all CDNs support it (Fastly, Akamai do; Cloudflare uses Cache-Tag)
Strategy 4: Short s-maxage + SWR
Use short cache durations with stale-while-revalidate:
Cache-Control: s-maxage=60, stale-while-revalidate=86400
Pros: Self-healing, no purge infrastructure needed Cons: Content can be stale for up to 60 seconds
Choosing a Strategy
| Scenario | Best Strategy |
|---|---|
| Static assets (JS/CSS) | URL versioning |
| Blog posts / CMS content | Purge API on publish |
| Product catalog | Surrogate keys |
| API responses | Short s-maxage + SWR |
Use Case
A headless CMS powers a marketing site with 10,000 pages. When an editor publishes a change, the CMS webhook triggers a Fastly purge using surrogate keys: every page tagged with the modified content block is purged instantly. The Cache-Control header 's-maxage=86400, stale-while-revalidate=60' ensures aggressive CDN caching with a 1-minute SWR window, while the purge API handles immediate invalidation when content actually changes.