advanced
Caching
Use HTTP cache headers, CDN policy, service workers, and application caches without serving stale or user-specific data incorrectly.
Frontend caching spans HTTP cache headers, CDN edge caches, service workers, and in-memory client caches. Correct caching speeds repeat visits but can serve stale or personalized content incorrectly.
| Layer | Typical policy | |-------|----------------| | Hashed static assets | `Cache-Control: public, max-age=31536000, immutable` | | HTML documents | Short TTL or `no-cache` with validation | | API JSON | Usually private; ETag when safe | | Service worker | Versioned precache; network-first for HTML |
Browser → CDN (HIT) → Origin (MISS only)
Use **cache busting** via content hashes in filenames, not query-string tricks alone. For authenticated pages, mark responses `private` and vary on cookies or auth headers deliberately.
On interviews: `max-age` vs `s-maxage`; stale-while-revalidate; CDN cache keys; why you must not cache personalized HTML at the edge.
Common pitfalls: caching HTML with user-specific data; long TTL on unhashed JS; service worker serving outdated API responses after deploy.
The trade-off is speed versus freshness and correctness for logged-in users.
Checklist:
- Immutable hashed assets at CDN.
- Validate HTML and API cacheability.
- Document purge strategy on deploy.
- Test auth flows with CDN enabled.