HTTP Caching, Compression and CDNs
Use Cache-Control, content hashing, compression and CDNs so repeat visits are near-instant and servers stay cool.
Intermediate · about 3 hours · difficulty 3/5
Learn first: HTTP and HTTPS, Build Tools and Bundlers
The fastest request is the one never made. HTTP caching lets browsers and CDNs reuse responses, and it is mostly configuration you set once.
Cache-Control essentials
Cache-Control: public, max-age=31536000, immutablefor hashed static assets (app.3f9a1c.js, images with hashes). They never change; a new build produces new names.Cache-Control: no-cachefor HTML: the browser may store it but must revalidate, so users get new deployments immediately.no-storefor sensitive, personalised responses.- Validators:
ETagandLast-Modifiedlet the browser ask "has this changed?" and receive a tiny304 Not Modified. stale-while-revalidateserves a cached copy instantly while fetching a fresh one in the background.
CDNs
A Content Delivery Network caches your files in data centres near users, cutting latency. Hosts like Vercel, Netlify and Cloudflare include one. Understand cache invalidation on deploy and the difference between browser cache and edge cache (s-maxage).
Compression and protocols
Serve text assets with Brotli (or gzip) compression; it often shrinks JavaScript and CSS by 70% or more. HTTP/2 and HTTP/3 multiplex many requests over one connection, so bundling everything into one giant file is no longer necessary.
Application-level caching
Service workers (covered with PWAs) and data libraries like TanStack Query add caching layers under your control. Keep one clear owner per layer to avoid stale-data mysteries.
Good enough to move on
You can read the caching headers of any response in DevTools, configure long-lived caching for hashed assets and revalidation for HTML on your host, and explain why a deploy did or did not reach users.
Key concepts
- Cache-Control directives
- Immutable hashed assets vs HTML
- ETag and 304 revalidation
- stale-while-revalidate
- CDNs and edge caching
- Brotli and gzip compression
- HTTP/2 and HTTP/3
Mini project
Deploy a Vite build and configure headers so hashed assets are cached for a year and HTML revalidates; verify with DevTools that a second visit loads assets from cache and a new deploy is picked up.
Check yourself
What would go wrong if you set max-age=31536000 on index.html?