Caching Strategies
Caching is one of the most powerful performance tools available. Learn in-memory memoization, TTL and LRU caches, HTTP Cache-Control headers, stale-while-revalidate, and Service Worker caching strategies for offline-first apps.
How does caching work in web applications?
Caching stores responses so they don't have to be fetched or computed again. Browsers cache files according to HTTP headers like Cache-Control, CDNs cache at the edge near users, service workers can cache for offline use, and in your code you can memoise results in a Map. The hard part is invalidation: knowing when cached data is stale.
Cache-Control: public, max-age=31536000, immutable # hashed static files
Cache-Control: no-cache # HTML: revalidate every time
const cache = new Map();
async function getUser(id) {
if (!cache.has(id)) cache.set(id, fetch(`/api/users/${id}`).then(r => r.json()));
return cache.get(id);
}Cache-Control Header Cheat Sheet
| Resource Type | Cache-Control Header | Why |
|---|---|---|
| HTML pages | no-cache | Always revalidate — HTML must be fresh |
| Hashed JS/CSS bundles | public, max-age=31536000, immutable | 1-year cache — hash in filename = safe forever |
| Images / fonts (hashed) | public, max-age=31536000, immutable | Same — immutable assets |
| API responses (personal) | private, max-age=60 | User-specific, browser only, 60s fresh |
| API responses (public) | public, s-maxage=300, stale-while-revalidate=60 | CDN cache 5min, serve stale 60s while revalidating |
| Authentication tokens | no-store | Never cached anywhere |
| 404 / error pages | no-store | Don't cache error states |
Caching Layers
Memory
Browser HTTP
Service Worker
CDN
App Server (Redis)
DB Query Cache
DB Index
CDN Origin Shield
Common Pitfalls
Interactive Demo
Code Editor
<button id="go">Get user 1</button>
<pre id="out"></pre>Preview
Caching Strategies — step by step
HTTP Cache Headers
Cache-Control directives like max-age, no-cache, and no-store instruct browsers and intermediary proxies on how long to store a response. ETag and Last-Modified allow conditional requests that revalidate stale entries without re-downloading unchanged content.
🎯 Quick Check
Which caching strategy returns a cached response immediately while fetching an update in the background?
Caching in Web Apps: summary
Key points
- Give build files content hashes (
app.3f9a.js) so they can be cached forever safely. stale-while-revalidateserves cached data instantly while refreshing it in the background.- Libraries like TanStack Query handle client-side API caching and refetching.
Frequently asked questions
›Why are users seeing an old version of my site?
The HTML or unhashed files are cached too aggressively. Serve HTML with no-cache and use hashed file names for assets.