Caching Strategies for Better Performance
Short answer: caching stores a copy of a result so the next request is served faster without redoing the work. Use long-lived caching for static files with hashed names, short or validated caching for HTML and APIs, and always plan how a cached item gets refreshed.
Where caching happens
| Layer | What it stores | Typical tool |
|---|---|---|
| Browser | Files on the visitor's device | HTTP cache headers |
| CDN / edge | Copies near the visitor | Cloudflare, CloudFront, Fastly |
| Reverse proxy | Full responses in front of your app | Nginx, Varnish |
| Application | Computed results in memory | Redis, Memcached, in-process maps |
| Database | Query plans and hot data | Built into the database |
HTTP caching with Cache-Control
| Directive | Meaning |
|---|---|
max-age=N | Reuse for N seconds without asking the server |
public / private | Shared caches may store it / only the user's browser may |
no-cache | Store it, but check with the server before each reuse |
no-store | Never store it (use for sensitive data) |
immutable | The file will never change; skip revalidation |
stale-while-revalidate=N | Serve the old copy immediately while fetching a fresh one in the background |
Note that no-cache does not mean "do not cache". It means "revalidate first".
Recommended settings by content type
| Content | Header |
|---|---|
| JS, CSS and images with hashed filenames | public, max-age=31536000, immutable |
| HTML pages | no-cache or a short max-age with stale-while-revalidate |
| Public API data that changes slowly | public, max-age=60 |
| Personal or account data | private, no-store |
Validation with ETag
When a cached copy expires, the browser can ask "has this changed?" by sending the stored ETag in an If-None-Match header. If nothing changed, the server replies 304 Not Modified with no body, saving bandwidth. See HTTP status codes.
Cache busting with hashed filenames
If you cache a file for a year, how do you ship a new version? Put a hash of its content in the file name (app.3f9a1c.js). When the code changes, the name changes, so browsers fetch the new file, while unchanged files stay cached. Build tools like Vite and webpack do this automatically.
Application and database caching
Cache the results of expensive work, such as a slow query or an external API call, in Redis or memory:
async function getProduct(id) {
const cached = await redis.get('product:' + id);
if (cached) return JSON.parse(cached);
const product = await db.products.findById(id);
await redis.set('product:' + id, JSON.stringify(product), 'EX', 300);
return product;
}
This is the cache-aside pattern: check the cache, fall back to the source on a miss, then store the result with an expiry. Indexing slow queries also helps; see database indexes.
Common strategies
| Strategy | How it works | Best for |
|---|---|---|
| Cache-aside | App reads cache, then source on a miss | Most applications |
| Write-through | Writes update cache and source together | Data read soon after writing |
| Time-based expiry (TTL) | Entries expire automatically | Data that can be slightly stale |
| Event-based invalidation | Delete entries when data changes | Data that must be fresh |
The hard part: invalidation
A cache is only useful if it is not wrong. Decide for each item how stale it may be, set an expiry, and delete or update entries when the underlying data changes. Purge CDN caches after deployments that change HTML.
Common pitfalls
- Caching personalized pages publicly, which can show one user's data to another.
- Long-term caching of files without hashed names.
- No expiry on in-memory caches, causing memory growth.
- A cache stampede: many requests rebuild the same expired item at once. Use locks or stale-while-revalidate.
Next steps
Apply caching as part of improving website load speed, and see the wider performance picture.
