HTTP Caching, CDNs and Client Caches
Use Cache-Control, ETags and CDNs so browsers and edge servers do the work instead of your origin.
Intermediate · about 4 hours · difficulty 3/5
Learn first: HTTP in Depth, Server-Side Caching with Redis
The fastest request is one that never reaches your server. HTTP has a built-in caching model that browsers, proxies and CDNs understand; your job is to send the right headers.
Cache-Control
Cache-Control: public, max-age=31536000, immutablefor fingerprinted static assets (app.3f9a1c.js).Cache-Control: private, max-age=60for per-user responses that only the browser may cache.Cache-Control: no-storefor sensitive data that must never be cached.s-maxagesets a different lifetime for shared caches like CDNs;stale-while-revalidateserves slightly old content while fetching fresh content in the background.
Validation
With an ETag (a version fingerprint) or Last-Modified, clients send If-None-Match or If-Modified-Since and your server can reply 304 Not Modified with no body, saving bandwidth.
CDNs
A Content Delivery Network (Cloudflare, Fastly, CloudFront, Akamai) caches responses at edge locations close to users, absorbing traffic spikes and reducing latency. Beyond static files, CDNs can cache API responses, terminate TLS, block attacks and run edge functions. Plan for purging when content changes.
Client-side caching
Browsers also cache in memory and on disk, and apps use Service Workers, localStorage or client libraries (React Query, SWR) to cache API data. The backend's headers and ETags make those clients efficient.
Pitfalls
- Caching authenticated responses on a shared CDN without varying on the right headers, leaking one user's data to another.
- Forgetting the
Varyheader when responses differ byAccept-Encodingor language.
You are ready to move on when your static assets are served from a CDN with long-lived immutable caching and an API endpoint returns ETags that produce 304 responses.
Key concepts
- Cache-Control directives
- ETag and 304 Not Modified
- Vary header
- CDNs and edge caching
- Cache purging
- stale-while-revalidate
- Client-side caching
Mini project
Put a free CDN in front of your app, configure immutable caching for static assets and short shared caching for a public API endpoint, and verify cache hits using response headers.
Check yourself
Why is putting 'Cache-Control: public' on a response that includes the logged-in user's name dangerous behind a CDN?
Free resources
- MDN: HTTP caching (MDN)
- What is a CDN? (Cloudflare)
- Prevent unnecessary network requests with the HTTP Cache (web.dev)