advanced
Caching and compression
Design HTTP caching with Cache-Control, validators, surrogate caches, Vary, invalidation, gzip/Brotli, and payload trade-offs.
HTTP caching uses freshness (`Cache-Control: max-age`, `s-maxage` for shared caches) and validators (`ETag`, `Last-Modified`). Conditional requests (`If-None-Match`) return 304 when content is unchanged, saving bandwidth.
`Vary` tells caches which request headers affect the response — critical for `Accept-Encoding` and authenticated variants. `stale-while-revalidate` and `stale-if-error` soften CDN behavior during origin issues.
Compression (gzip, Brotli) trades CPU for bytes. Compress text (JSON, HTML, CSS); skip already compressed formats (JPEG, brotli/gzip assets).
Cache-Control: public, max-age=60, s-maxage=300, stale-while-revalidate=30
Content-Encoding: br
Vary: Accept-Encoding
On interviews: design cache keys for personalized vs public content; explain cache poisoning risks with incorrect `Vary`; when to compress at app vs reverse proxy.
Common pitfalls: caching private user data as public; ETags on dynamic secrets; compressing small responses where overhead wins.
The trade-off is balancing simplicity, performance, safety, and operability — name which axis you optimized and what cost you accepted.
Checklist:
- Separate browser private cache from CDN shared cache.
- Pair TTL with validators for large payloads.
- Set Vary for encoding and auth variants.
- Compress at the edge when CPU is cheaper than egress.