Why HTTP Caching Matters
Caching reduces server load, decreases latency, and saves bandwidth. A well-cached site can serve 90%+ of requests without hitting the origin server.
Cache-Control Header
The Cache-Control header is the primary mechanism for controlling caching:
max-age=3600— Cache for 1 hourno-cache— Cache but revalidate before each useno-store— Never cache (sensitive data)public— Any cache (CDN, proxy) can store thisprivate— Only the browser can cache thisimmutable— Resource will never change (great for hashed assets)
ETags and Conditional Requests
An ETag is a fingerprint of a resource. The flow:
- Server sends response with
ETag: "abc123" - On next request, client sends
If-None-Match: "abc123" - If unchanged, server returns 304 Not Modified (no body)
- If changed, server returns 200 with new content and new ETag
Last-Modified / If-Modified-Since
Similar to ETags but uses timestamps. Less precise but simpler.
Common Patterns
- Static assets (JS, CSS):
Cache-Control: public, max-age=31536000, immutable(1 year, use content-hashed filenames) - HTML pages:
Cache-Control: no-cache(revalidate but cache for offline) - API responses:
Cache-Control: private, max-age=60(cache for 1 minute, browser only) - User-specific data:
Cache-Control: private, no-store