CDN Configuration

A CDN only helps if it's configured correctly. Poor caching rules can serve stale content to users or bypass the cache entirely, negating the benefits. Understanding cache headers and invalidation strategies is essential for effective CDN usage.

Cache-Control Headers

The Cache-Control header tells CDNs (and browsers) how to cache responses. Different content needs different rules:

# Static assets with content hash in filename
Cache-Control: public, max-age=31536000, immutable

# Content that might change
Cache-Control: public, max-age=3600, must-revalidate

# Dynamic or personalized content
Cache-Control: no-store

# User-specific content
Cache-Control: private, max-age=3600

The public directive allows CDN caching. max-age specifies cache duration in seconds. immutable tells browsers the content will never change — don't even check.

The private directive prevents CDN caching but allows browser caching. Use this for user-specific content that shouldn't be shared between users.

Caching Strategy by Content Type

Different content deserves different cache durations:

Static assets with hashed filenames (like app.a1b2c3.js) can cache forever. The hash changes when content changes, so you never serve stale files. Set max-age=31536000 (one year).

Images without hashes might change occasionally. Cache for one day to one week depending on how often they update.

HTML pages often need fresh content. Use short cache times or no-store for dynamic pages. For static sites, moderate caching works.

API responses vary widely. Public, rarely-changing data can cache briefly. User-specific or real-time data shouldn't cache at all.

Cache Invalidation

When content changes, you need to remove old cached versions. This is famously one of the hardest problems in computer science.

Purge by URL removes specific cached objects. Most CDNs provide APIs or dashboards for this.

Purge by prefix or tag removes groups of related content. Useful when updating a section of your site.

Versioned filenames avoid invalidation entirely. If style.v1.css becomes style.v2.css, there's nothing to invalidate — it's a new URL. This is the most reliable approach for static assets.

Build tools like Webpack and Vite automatically add content hashes to filenames, making this strategy easy to implement.

See More

Further Reading

You need to be signed in to leave a comment and join the discussion