Tech News, Tech & Coding · Free Online Tools

IT Question Answer
Tools
Back to Performance
Caching Strategies for Better Performance

Caching Strategies for Better Performance

PerformanceBy Muhammad Fareed
performancecachingstrategiesbetter

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

LayerWhat it storesTypical tool
BrowserFiles on the visitor's deviceHTTP cache headers
CDN / edgeCopies near the visitorCloudflare, CloudFront, Fastly
Reverse proxyFull responses in front of your appNginx, Varnish
ApplicationComputed results in memoryRedis, Memcached, in-process maps
DatabaseQuery plans and hot dataBuilt into the database

HTTP caching with Cache-Control

DirectiveMeaning
max-age=NReuse for N seconds without asking the server
public / privateShared caches may store it / only the user's browser may
no-cacheStore it, but check with the server before each reuse
no-storeNever store it (use for sensitive data)
immutableThe file will never change; skip revalidation
stale-while-revalidate=NServe 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

ContentHeader
JS, CSS and images with hashed filenamespublic, max-age=31536000, immutable
HTML pagesno-cache or a short max-age with stale-while-revalidate
Public API data that changes slowlypublic, max-age=60
Personal or account dataprivate, 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

StrategyHow it worksBest for
Cache-asideApp reads cache, then source on a missMost applications
Write-throughWrites update cache and source togetherData read soon after writing
Time-based expiry (TTL)Entries expire automaticallyData that can be slightly stale
Event-based invalidationDelete entries when data changesData 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.