← Back to Backend, page 1

backend-0019 · Hard senior

How do you handle cache invalidation across layers (browser, CDN, application cache), and when do you choose purging, versioned URLs or short TTLs?

Prefer designs where invalidation is not needed: immutable, versioned (content-hashed) URLs for assets, and short TTLs with revalidation for data. When content must change at a fixed URL, use explicit purging (by URL or by tag or surrogate key) at the CDN, plus stale-while-revalidate to hide revalidation cost. Choose the mix by how stale a response may be, how expensive the origin is, and how many layers hold copies.

Full answer

Layers

  • Browser cache, CDN or edge cache, reverse proxy, application cache (Redis), database buffers. Each layer has its own TTL, so the worst-case staleness is roughly the sum of what you allow on each path.

Strategies

  1. Versioned (fingerprinted) URLs: app.3f9a.js or /v42/config.json. A new version is a new URL, so the old copies are never wrong. Cache for a year. Best for static assets.
  2. TTL only: accept staleness up to max-age or s-maxage. Simple. Good for public listings and non-critical data.
  3. Revalidation: no-cache plus ETag. Always correct, costs a conditional request (304) per use. Pair with stale-while-revalidate and stale-if-error for speed and resilience.
  4. Purge: on change, call the CDN API to remove a URL, a prefix, or all objects with a tag (surrogate key, for example product-42). Fast but needs reliable event hooks, and purge propagation is not instant everywhere. Browser copies are not purged.
  5. Event-based invalidation for application caches: delete the key on write, or publish an invalidation message for local caches in many instances.

Design guidelines

  • Separate content by volatility (static assets, shared pages, personalised data).
  • Never cache personalised responses in shared caches (Cache-Control: private, correct Vary).
  • Keep keys predictable and tag related objects.
  • Measure hit ratio and stale reads, and always test the failure of invalidation (what is the maximum staleness if the purge fails?).
javascript
const crypto = require('node:crypto');

// 1. A content hash in the file name makes the URL change with the content.
const fingerprint = (name, content) => name.replace(/(\.\w+)$/, '.' + crypto.createHash('sha256').update(content).digest('hex').slice(0, 8) + '$1');
console.log('v1 file name :', fingerprint('app.js', 'console.log(1)'));
console.log('v2 file name :', fingerprint('app.js', 'console.log(2)'), '(new content, new URL, nothing to purge)');
console.log('same content :', fingerprint('app.js', 'console.log(1)') === fingerprint('app.js', 'console.log(1)'));

// 2. How a shared cache treats a response of a given age.
const parse = (header) => Object.fromEntries(header.split(',').map((p) => p.trim().split('=')).map(([k, v]) => [k.toLowerCase(), v === undefined ? true : Number(v)]));
function freshness(header, ageSeconds) {
  const cc = parse(header);
  const maxAge = cc['s-maxage'] ?? cc['max-age'] ?? 0;
  if (cc['no-store']) return 'never stored';
  if (cc['no-cache']) return 'stored, but must revalidate every time';
  if (ageSeconds < maxAge) return 'fresh: served from cache';
  if (cc['stale-while-revalidate'] && ageSeconds < maxAge + cc['stale-while-revalidate']) return 'stale: served now, refreshed in the background';
  return 'expired: the origin is asked again';
}
const policy = 'public, s-maxage=60, stale-while-revalidate=300';
for (const age of [10, 90, 400]) console.log(`age ${String(age).padEnd(3)} with "${policy}" ->`, freshness(policy, age));
console.log('no-cache      ->', freshness('no-cache', 5));
console.log('private, no-store ->', freshness('private, no-store', 5));

// 3. Purging by tag: which cached URLs carry the tag product-42?
const cdn = new Map([['/p/42', ['product-42']], ['/p/42/reviews', ['product-42', 'reviews']], ['/p/7', ['product-7']]]);
const purgeTag = (tag) => { const gone = [...cdn].filter(([, tags]) => tags.includes(tag)).map(([url]) => url); gone.forEach((u) => cdn.delete(u)); return gone; };
console.log('purge tag product-42 removes:', purgeTag('product-42').join(', '), '| left:', [...cdn.keys()].join(', '));

Small functions model fingerprinted names, the freshness decision of a shared cache, and tag-based purge. Real CDNs add their own rules and propagation delays. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): v1 file name : app.0a286891.js v2 file name : app.f2ae6bd0.js (new content, new URL, nothing to purge) same content : true age 10 with "public, s-maxage=60, stale-while-revalidate=300" -> fresh: served from cache age 90 with "public, s-maxage=60, stale-while-revalidate=300" -> stale: served now, refreshed in the background age 400 with "public, s-maxage=60, stale-while-revalidate=300" -> expired: the origin is asked again no-cache -> stored, but must revalidate every time private, no-store -> never stored purge tag product-42 removes: /p/42, /p/42/reviews | left: /p/7

Key points

  • Fingerprinted URLs avoid invalidation for static assets.
  • TTL, revalidation and purging trade freshness against load.
  • Surrogate keys let a CDN purge related objects together.
  • Browser caches cannot be purged, so choose max-age carefully.
  • Know the worst-case staleness across all layers.

Common mistakes

  • Purging as the only plan with no maximum staleness.
  • Long max-age on non-fingerprinted files.
  • Caching personalised pages in the CDN.
  • Forgetting the browser layer.
  • Never measuring the hit ratio.

Follow-ups

  • What is stale-if-error?
  • How do surrogate keys work?
  • How would you cache an API with per-user authorization?

Tips

  • List layers first.
  • Prefer versioned URLs.
  • Describe the worst-case staleness.