patternModeratepending
HTTP caching headers — Cache-Control, ETag, and CDN strategies
Viewed 0 times
Cache-ControlETagimmutablestale-while-revalidateCDN cache304 Not Modifiedcontent hash
browsernodejslinux
Problem
Static assets aren't cached, causing redundant downloads. Or assets are cached too aggressively, and users don't see updates. CDN serves stale content after deployments.
Solution
(1) Immutable assets (hashed filenames: app.a1b2c3.js): Cache-Control: public, max-age=31536000, immutable. (2) HTML and API responses: Cache-Control: no-cache (always revalidate) or max-age=0, must-revalidate. (3) ETag for conditional requests: server sends ETag header, browser sends If-None-Match. Server returns 304 if unchanged. (4) CDN: use Surrogate-Control or CDN-specific headers for edge caching separate from browser caching. (5) Cache busting: use content hashes in filenames (webpack/vite do this automatically). Never rely on query strings (?v=2) — some CDNs ignore query strings. (6) stale-while-revalidate: serve stale content immediately while fetching fresh in background. (7) Vary header: cache different versions based on Accept-Encoding, Accept-Language, etc.
Why
Proper caching eliminates redundant network requests. The key insight: cache immutable assets forever (they have unique names), and always revalidate mutable resources (HTML, API responses).
Revisions (0)
No revisions yet.