CachingCDN CachingMedium⏱️ ~2 min

How CDN Cache Keys and Freshness Control Work

Definition
CDN cache keys determine whether two requests can share the same cached response. The cache key combines scheme, host, path, query parameters, and selected headers to create unique entries.

How Cache Keys Work

The base key combines scheme (http/https), host, path, and normalized query parameters. CDNs add selected HTTP headers via the Vary response header to create variants. Example: https://example.com/product?id=123 with Vary: Accept-Encoding stores separate gzip and brotli compressed versions. Every additional dimension multiplies variants and fragments cache memory, directly reducing hit ratio.

Freshness Control

The Cache-Control: s-maxage directive tells shared caches (CDNs) how long to consider objects fresh, independent of browser max-age. Typical values: 60s for dynamic content, 31536000s (1 year) for immutable assets. Stale while revalidate allows serving slightly stale content while refreshing in background, keeping p99 latency flat (20-50ms) during origin refreshes.

Revalidation

When cache entries expire, CDNs use conditional requests with If-None-Match (ETag) or If-Modified-Since (timestamp). If content unchanged, origin returns 304 Not Modified (few bytes vs full response), extending freshness without retransmitting data. This reduces bandwidth by 90%+ for stable content.

💡 Key Takeaways
Cache key combines scheme, host, path, query params, and Vary headers. Each dimension multiplies variants and reduces hit ratio.
s-maxage controls CDN freshness: 60s for dynamic, 31536000s (1 year) for immutable assets. Independent of browser max-age.
Stale while revalidate serves slightly stale content while refreshing in background, keeping p99 at 20-50ms during origin refresh.
Conditional requests with If-None-Match/If-Modified-Since reduce bandwidth 90%+ when content unchanged (304 response).
📌 Interview Tips
1Explain Vary header impact: Vary: Accept-Encoding creates 2 variants (gzip, brotli). Vary: Accept-Language without normalization creates dozens.
2s-maxage vs max-age: s-maxage=3600 means CDN caches 1 hour regardless of browser max-age=0.
3Conditional request: cache expired, CDN sends If-None-Match: "abc", origin returns 304, CDN extends freshness without retransmitting.
← Back to CDN Caching Overview