← Back to Backend, page 1

backend-0017 · Medium mid

How does HTTP caching work: what do Cache-Control, ETag, If-None-Match, Last-Modified and Vary do, and how do you cache static files versus API responses?

Cache-Control tells browsers and shared caches how long a response is fresh (max-age, s-maxage) and who may store it (public, private, no-store). When a response is stale, the cache revalidates: it sends the validator (If-None-Match with the ETag, or If-Modified-Since) and the server answers 304 Not Modified with no body if nothing changed. Vary says which request headers change the response. Fingerprinted static files get a very long max-age with immutable. APIs usually use no-cache (revalidate each time) or short lifetimes.

Full answer

Freshness

  • Cache-Control: max-age=N (seconds, browser and shared caches), s-maxage=N (shared caches such as a CDN). While fresh, the cache answers without contacting the server.
  • public allows shared caches. private means only the browser may store it (user-specific data). no-store means do not store at all (sensitive data). no-cache means store but revalidate before every use. immutable says the file never changes during its freshness.

Validation

  • The server sends ETag: "v7" (or Last-Modified). After the response is stale, the client asks GET with If-None-Match: "v7". If unchanged, the server answers 304 and no body, which saves bandwidth and time.

Vary

  • Vary: Accept-Encoding (or Accept-Language, Origin) tells caches to keep separate copies per header value. Vary: Cookie makes shared caching almost useless.

Patterns

  • Static assets with a content hash in the file name (app.3f9a.js): Cache-Control: public, max-age=31536000, immutable. To release, change the name.
  • HTML and API responses: Cache-Control: no-cache plus an ETag (always revalidate, usually a 304), or a short max-age with stale-while-revalidate.
  • Personal data: private, no-store.
  • Do not cache POST responses by default. Keep error responses short lived.
javascript
const http = require('node:http');
const crypto = require('node:crypto');

let requestsSeen = 0;
const price = { value: 100 };
const server = http.createServer((req, res) => {
  requestsSeen++;
  if (req.url === '/app.3f9a.js') {
    res.writeHead(200, { 'cache-control': 'public, max-age=31536000, immutable' }); return res.end('console.log("app")');
  }
  if (req.url === '/api/price') {
    const body = JSON.stringify(price);
    const etag = '"' + crypto.createHash('sha1').update(body).digest('hex').slice(0, 8) + '"';
    if (req.headers['if-none-match'] === etag) { res.writeHead(304, { etag }); return res.end(); }
    res.writeHead(200, { etag, 'cache-control': 'no-cache', vary: 'Accept-Encoding', 'content-type': 'application/json' }); return res.end(body);
  }
  res.writeHead(200, { 'cache-control': 'private, no-store' }); res.end('{"me":"asha"}');
});

// A very small browser cache.
const cache = new Map(); let clock = 0;
async function get(path) {
  const entry = cache.get(path);
  const url = `http://127.0.0.1:${server.address().port}${path}`;
  if (entry && entry.freshUntil > clock) return 'served from cache, no request';
  const r = await fetch(url, { headers: entry?.etag ? { 'if-none-match': entry.etag } : {} });
  if (r.status === 304) return 'revalidated: 304, body reused (' + entry.body + ' bytes saved)';
  const body = await r.text();
  const cc = r.headers.get('cache-control') || '';
  const maxAge = /max-age=(\d+)/.exec(cc)?.[1];
  if (!/no-store/.test(cc)) cache.set(path, { etag: r.headers.get('etag'), body: body.length, freshUntil: maxAge ? clock + Number(maxAge) : 0 });
  return `200 from server, cache-control: ${cc}`;
}

server.listen(0, '127.0.0.1', async () => {
  for (const path of ['/app.3f9a.js', '/app.3f9a.js', '/api/price', '/api/price', '/api/me', '/api/me']) console.log(path.padEnd(14), await get(path));
  price.value = 120;
  console.log('price changed  ', await get('/api/price'));
  clock += 86400 * 30;
  console.log('30 days later  ', await get('/app.3f9a.js'));
  console.log('requests that reached the server:', requestsSeen);
  server.close();
});

A small server and a simplified browser cache with a fake clock (real browsers add heuristics and more rules). The count of requests at the end shows what the cache saved. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): /app.3f9a.js 200 from server, cache-control: public, max-age=31536000, immutable /app.3f9a.js served from cache, no request /api/price 200 from server, cache-control: no-cache /api/price revalidated: 304, body reused (13 bytes saved) /api/me 200 from server, cache-control: private, no-store /api/me 200 from server, cache-control: private, no-store price changed 200 from server, cache-control: no-cache 30 days later served from cache, no request requests that reached the server: 6

Key points

  • max-age sets freshness; s-maxage targets shared caches.
  • ETag with If-None-Match gives cheap revalidation (304).
  • no-cache means revalidate; no-store means never keep.
  • Vary separates cached variants by request header.
  • Fingerprint static files and cache them for a year.

Common mistakes

  • Using no-cache when you meant no-store for secrets.
  • Long max-age on files without a content hash in the name.
  • Vary: Cookie on public pages.
  • Forgetting that a CDN follows s-maxage and Vary.
  • Weak or missing ETags on large API responses.

Follow-ups

  • What is stale-while-revalidate?
  • How does the Age header relate to max-age?
  • How do you cache an API response per user safely?

Tips

  • Separate freshness from validation.
  • Give the static file recipe.
  • Mention Vary.