Caching interview question · Most asked
How does HTTP caching work (Cache-Control, ETag, CDNs)?
Summary
Cache-Control tells browsers and CDNs whether and how long to cache (public, max-age=300, private, no-store, s-maxage, stale-while-revalidate); validators (ETag, Last-Modified) let clients revalidate with conditional requests and receive 304 Not Modified; CDNs cache responses at edge locations close to users.
Longer Answer
Static assets with hashed filenames can be cached for a year with immutable. API responses that are personalized must be private or no-store. Vary tells caches which request headers change the response (e.g., Accept-Encoding). Purge or use short TTLs plus surrogate keys for content that changes.
Code Example
# Static, fingerprinted asset
Cache-Control: public, max-age=31536000, immutable
# Public API response, revalidate in the background
Cache-Control: public, max-age=60, stale-while-revalidate=300
ETag: "v42-9f8e"
# Personalized response
Cache-Control: private, no-store
Key Points
- Cache-Control directives
- ETag/Last-Modified + 304
- CDN edge caching
- private/no-store for personalized data
- Vary header
More most-asked Caching questions
- Explain the main caching patterns: cache-aside, read-through, write-through and write-behind.
- Why is cache invalidation hard, and what strategies help?
- What is a cache stampede (thundering herd) and how do you prevent it?
- Explain the difference between cache penetration, cache breakdown and cache avalanche.
- In cache-aside, why can a value be stale even though you delete the key on every write?
- How can a CDN leak one user's data to another, and how do you prevent it?
- Should you invalidate the cache before or after the database commit?
- How does stale-while-revalidate work, and when is it inappropriate?