Edge Caching and Surrogate-Key Invalidation for Headless CMS
Achieve fast global API responses using Cache-Control directives, stale-while-revalidate, and granular surrogate-key purging.
Why Content APIs Need Multi-Layer Caching
Fetching structured entries across multiple regions without edge caching forces requests to traverse long network paths to an origin cluster. Even a fast origin adds noticeable Time to First Byte (TTFB) latency for distant users and exposes compute layers to traffic spikes.
Content delivery APIs exhibit high read-to-write ratios, making them ideal for CDN edge caching. Serving published JSON from regional Points of Presence keeps API latency under 50 milliseconds globally while shielding origin databases during product launches.
- Keep public published reads strictly separate from uncached preview queries
- Normalize query parameter ordering so identical queries share one cache key
- Use long CDN s-maxage values paired with event-driven invalidation
- Enable Brotli or gzip compression on JSON API responses
Cache-Control, s-maxage, and Stale-While-Revalidate
HTTP Cache-Control headers distinguish browser caching from shared CDN edge caching. Setting max-age=60, s-maxage=3600 lets browsers revalidate quickly while allowing the CDN to serve cached payloads for an hour—or indefinitely until purged.
Adding stale-while-revalidate lets the edge return an instant slightly stale payload while refreshing the cache asynchronously in the background. Pairing this with stale-if-error protects uptime by continuing to serve cached content if an origin ever experiences brief maintenance.
- Set s-maxage higher than browser max-age when edge purges are automated
- Apply stale-while-revalidate to smooth out origin refresh latency spikes
- Attach Cache-Control: private, no-store on all authenticated preview responses
Granular Surrogate-Key Invalidation
Purging an entire CDN zone whenever one typo is fixed causes unnecessary cache stampedes and origin load. Conversely, relying solely on short TTLs leaves editors waiting minutes to verify urgent corrections live.
Surrogate keys (also called cache tags) bridge both worlds. Every API response emits a Surrogate-Key header listing the entry IDs, content types, and locale codes included in that payload; when an entry updates, a single targeted purge invalidates only dependent responses.
Preventing Cache Stampedes and Key Fragmentation
When a popular homepage cache key expires under heavy load, hundreds of concurrent requests can miss simultaneously and hammer the origin. Request collapsing (origin shielding) at the CDN ensures only one upstream request fetches the fresh payload while peers wait briefly.
Avoid polluting cache keys with unnecessary headers like full User-Agent strings or tracking cookies. Strip irrelevant query parameters such as utm_source before caching content pages or API lookups.
CDN Caching Strategy Comparison for Headless Delivery
| Strategy | Freshness Speed | Origin Protection | Operational Complexity |
|---|---|---|---|
| Short TTL (30–60s) | Delayed up to TTL | Moderate on viral spikes | Very low; no purge webhooks |
| Full-Site Purge on Publish | Immediate | Poor during frequent edits | Low; risks cache stampede |
| Surrogate-Key Targeted Purge | Sub-second targeted refresh | Very high; unaffected keys stay warm | Moderate; requires tag emission |
| ISR + Stale-While-Revalidate | Async refresh after first hit | Very high; non-blocking updates | Moderate; framework support |
| Static Prebuild Only | Tied to CI build duration | Maximum; zero runtime origin reads | Low for small sites; slow at 10k+ pages |
Surrogate-key invalidation paired with stale-while-revalidate delivers both instant editorial updates and high cache hit ratios.
Worked Illustration: Tagging Nested Navigation and Hero Entries
Consider a localized product page rendering a shared GlobalNav entry, a ProductHero entry, and two CustomerQuote entries.
- During API serialization, collect the unique identifiers of every resolved entry: nav_main, hero_dxp, quote_14, quote_29.
- Emit response header Surrogate-Key: nav_main hero_dxp quote_14 quote_29 locale_en_us and Cache-Control: public, max-age=60, s-maxage=86400, stale-while-revalidate=300.
- When an editor updates quote_14, the CMS publish webhook invokes the CDN purge endpoint for tag quote_14 only.
- Unrelated pages remain warmly cached while the product page refreshes silently on the next request.
Illustration Outcome: Global cache hit ratios stay above 95% while single-entry updates propagate worldwide within seconds.
Edge Caching & Invalidation Checklist
- Verify draft/preview endpoints return Cache-Control: private, no-store.
- Sort query parameters alphabetically on client requests to maximize cache hits.
- Strip marketing tracking parameters (utm_*, fbclid) from CDN cache keys.
- Emit entry-level Surrogate-Key or Cache-Tag headers on every published API response.
- Enable CDN request collapsing / origin shield on high-traffic endpoints.
- Include stale-if-error directives to maintain availability during upstream hiccups.
Frequently Asked Questions
Can CDN caching break authenticated or personalized responses?
Yes, if private responses are accidentally marked public. Keep personalized or draft queries scoped to private/no-store or vary strictly on normalized edge cohort keys.
How many surrogate keys can a single response safely carry?
Most CDNs limit header size (often 8 KB to 16 KB). For list pages referencing hundreds of items, tag by collection or content-type key in addition to top featured IDs.
What is the difference between soft purge and hard purge?
Hard purge deletes the object immediately, forcing the next visitor to wait for origin fetch. Soft purge marks it stale so stale-while-revalidate serves instantly during background refresh.
Should GraphQL endpoints still use CDN caching if Next.js or another framework caches pages?
Yes. Edge-caching the content API protects origin stability during full site rebuilds, mobile app traffic, and incremental revalidation bursts.
Primary Standards & Specifications
- IETF RFC 9111 — HTTP Caching (Cache-Control, s-maxage, Freshness)
- IETF RFC 5861 — HTTP Cache-Control Extensions for Stale Content (stale-while-revalidate, stale-if-error)
- W3C / Fastly Surrogate-Control Header Patterns for Edge Invalidation