The CDN Engineer maximises cache hit rates and minimises origin load through correct Cache-Control headers and smart invalidation. The goal is a cache hit rate above 90% for static assets and above 50% for dynamic content where possible. Every cache miss means an origin request - which adds latency and cost.
Cache-Control Strategy
# Asset types and their correct Cache-Control headers
# Static assets with content hashing (JS, CSS, fonts) - cache forever
# The hash in the filename ensures cache busting on deploy
Cache-Control: public, max-age=31536000, immutable
# Example: /assets/main.8f3a2b1c.js
# HTML pages - always revalidate, but allow stale serving
Cache-Control: public, max-age=0, s-maxage=60, stale-while-revalidate=86400
# CDN caches for 60s; serves stale for up to 24h while revalidating in background
# API responses (authenticated) - never cache at CDN
Cache-Control: private, no-store
# API responses (public, rarely changing - e.g. product catalogue)
Cache-Control: public, max-age=300, s-maxage=3600
# Browser caches 5m; CDN caches 1h
# Images without content hashing
Cache-Control: public, max-age=86400, stale-while-revalidate=604800
# Cache 1 day; revalidate in background for up to 7 days
Cloudflare Workers (Edge Functions)
// Edge function - runs in 275+ locations worldwide, < 5ms overhead
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const url = new URL(request.url);
// A/B test at the edge - no origin request needed
if (url.pathname === '/') {
const variant = Math.random() < 0.5 ? 'control' : 'variant';
const response = await fetch(request);
const newResponse = new Response(response.body, response);
newResponse.headers.set('Set-Cookie', `ab_variant=${variant}; Path=/; Max-Age=86400`);
return newResponse;
}
// Geo-routing - serve region-specific content
const country = request.cf?.country ?? 'US';
if (country === 'DE') {
return fetch(`https://eu.api.example.com${url.pathname}${url.search}`);
}
return fetch(request);
}
};
Cache Invalidation Patterns
- Content-based hashing (best) - filename includes hash of content. Cache never needs invalidation. Works for JS, CSS, fonts.
- Deploy-time purge - purge all cached HTML after deploy. Cloudflare:
cf.purge_everything. CloudFront: create invalidation for/*. - Surrogate keys / Cache Tags - tag cached responses with resource IDs. Purge by tag when resource changes. Cloudflare Enterprise / Fastly feature.
- Purge by URL - purge specific URLs after content updates. Works but doesn't handle CDN edge cases (query strings, variations).