Performance & Security

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 TypeCache-Control HeaderWhy
HTML pagesno-cacheAlways revalidate — HTML must be fresh
Hashed JS/CSS bundlespublic, max-age=31536000, immutable1-year cache — hash in filename = safe forever
Images / fonts (hashed)public, max-age=31536000, immutableSame — immutable assets
API responses (personal)private, max-age=60User-specific, browser only, 60s fresh
API responses (public)public, s-maxage=300, stale-while-revalidate=60CDN cache 5min, serve stale 60s while revalidating
Authentication tokensno-storeNever cached anywhere
404 / error pagesno-storeDon't cache error states

Caching Layers

Memory

Speed: < 1ms
Examples: JS variable, Map, WeakMap
Use when: Same-session reuse

Browser HTTP

Speed: ~1ms
Examples: Cache-Control headers, ETag
Use when: Cross-page reuse, reloads

Service Worker

Speed: ~2ms
Examples: Cache Storage API
Use when: Offline, custom strategies

CDN

Speed: ~20ms
Examples: Cloudflare, CloudFront, Fastly
Use when: Global users, static assets

App Server (Redis)

Speed: ~1ms
Examples: Redis, Memcached
Use when: DB query results, sessions

DB Query Cache

Speed: ~5ms
Examples: MySQL query cache, pg indexes
Use when: Repeated identical queries

DB Index

Speed: ~5ms
Examples: B-tree, hash indexes
Use when: Fast lookup by field

CDN Origin Shield

Speed: ~50ms
Examples: Regional CDN POP
Use when: Reduce origin load

Common Pitfalls

Caching user-specific data in CDN without private flag — users see each other's data
Use Cache-Control: private for personal data. CDN should only cache public/anonymous content.
Not cache-busting static assets — users get stale JS/CSS after deploy for hours
Include content hash in filenames (main.a3f8c1.js). This makes files safely immutable + auto-cache-busted.
Caching error responses — a 500 error gets cached and repeats for all users
Never cache error status codes. Check for errors before caching: if (res.ok) cache.set(key, data).
Growing in-memory cache infinitely — memory leak over time in long-running processes
Always set a max size (LRU) or TTL expiration. Monitor cache size in production.

Interactive Demo

Code Editor

<button id="go">Get user 1</button>
<pre id="out"></pre>

Preview

Caching Strategies — step by step

1 / 4
1

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.

1 of 4
💡Use Versioned Asset URLs for Permanent Caching
Append a content hash to asset filenames (bundle.a1b2c3d4.js). Set Cache-Control: max-age=31536000, immutable on these responses. Since the URL changes whenever content changes, you get unlimited caching without ever serving stale files to users.

🎯 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-revalidate serves 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.