CDN Caching Strategies
Implement CDN caching with Cache-Control headers, stale-while-revalidate, and cache invalidation patterns.
Overview
The Cache-Control header is the primary mechanism for controlling CDN caching. Key directives include max-age (how long to cache), s-maxage (CDN-specific TTL), stale-while-revalidate (serve stale content while refreshing in background), and stale-if-error (serve stale content on origin failure). These directives can be combined to create sophisticated caching strategies that balance freshness with performance.
Cache invalidation is the hardest problem in CDN caching. Strategies include versioned URLs (content hashing for static assets), surrogate keys (tag-based purging), and soft purging (marking content as stale without removing it). For dynamic content, edge computing (Cloudflare Workers, Vercel Edge Functions) allows you to implement custom caching logic at the CDN layer, including per-user caching, A/B testing, and geo-based content variation.
Who Is This For?
- Configure Cache-Control headers for static and dynamic content
- Implement stale-while-revalidate for near-instant page loads
- Set up cache invalidation for content updates
- Use edge caching for API responses with varying TTLs
Installation
npm install @cloudflare/workers-types Configuration
// Next.js API route with caching headers
export async function GET() {
const data = await fetchData()
return new Response(JSON.stringify(data), {
headers: {
"Cache-Control": "public, s-maxage=60, stale-while-revalidate=300",
"CDN-Cache-Control": "max-age=3600",
"Surrogate-Key": "posts homepage",
},
})
}
// Cloudflare Worker cache API
const cache = caches.default
const cachedResponse = await cache.match(request)
if (cachedResponse) return cachedResponse Explore AI Tools
Discover the best AI tools that complement your skills
Read AI & Design Articles
Tips and trends in the world of design and AI
Related Servers
Sentry Error Tracking
Monitor errors and performance issues in production with Sentry. AI agents can triage alerts and suggest fixes based on stack traces.
PostHog Product Analytics
Track product usage, manage feature flags, and analyze user behavior with PostHog, an open-source product analytics platform.
Database Query Builder
Generate and optimize SQL queries with AI assistance. Build complex queries, analyze execution plans, and improve database performance.