← Back to blog
Three upright panels of violet-lit glass stand on a dark reflective floor around a small glowing sphere, with thin beams of light stopping at the outer panels, each holding a faint stored imprint.
API Design·November 23, 2026·10 min read

HTTP Caching Explained: Cache-Control, ETag and 304 Not Modified

Most caching bugs come from mixing up two questions: how long a cache may reuse a response, and how it cheaply checks once that time is up. Here is how Cache-Control, ETag, Vary and 304 Not Modified actually fit together.

Most HTTP caching bugs come from treating two separate questions as one: how long a cache may reuse a response without asking anyone (freshness), and how it checks cheaply once that time is up (validation). Cache-Control answers the first, ETag and Last-Modified answer the second, and almost every "why is my user seeing stale data" or "why does every page load hit the origin" ticket is one of those two answered wrong.

The single most common symptom: someone sets Cache-Control: no-cache expecting nothing to be stored, and is surprised to find the response sitting in a browser or CDN cache. no-cache never meant "don't cache". It means "store it, but revalidate before every reuse". The directive that means "don't store" is no-store. Once you see freshness and validation as two separate dials, that naming stops being a trap.

The two questions every cache asks

When a browser, CDN or reverse proxy holds a stored response and a new request comes in for the same URL, RFC 9111 has it work through roughly this:

  1. Is the stored response still fresh? Freshness lifetime comes from Cache-Control: max-age (or s-maxage for shared caches), falling back to Expires, falling back to a heuristic. If the response's age is under that lifetime, serve it. No network, no origin.
  2. If it is stale, can I validate it? If the stored response carries a validator (ETag or Last-Modified), send a conditional request. If the origin answers 304 Not Modified, the cache refreshes its metadata and serves the body it already had.
  3. Otherwise, fetch the whole thing again.

Step 1 saves a round trip. Step 2 saves bandwidth but still costs a round trip. Good caching policy is mostly deciding, per kind of resource, how much of each you want.

Freshness: what Cache-Control actually controls

Here are the directives worth knowing, and the one-line meaning that usually gets lost:

DirectiveWhat it actually meansTypical use
max-age=NFresh for N seconds from when the response was generatedAlmost everything cacheable
s-maxage=NOverrides max-age for shared caches (CDNs, proxies) onlyHTML that a CDN can hold longer than browsers
no-cacheMay store, must revalidate with the origin before each reuseHTML shells, API responses you want to be always current
no-storeMust not store at allBanking pages, one-time tokens, anything sensitive
privateOnly the end user's browser may store it, not shared cachesPer-user responses
publicShared caches may store it even when they otherwise would not (for example, a response to a request with Authorization)Rarely needed; max-age alone already allows shared caching
must-revalidateOnce stale, never serve it without a successful revalidationData where stale is worse than an error
immutableThe body will never change while fresh, so skip revalidation even on reloadFingerprinted static assets
stale-while-revalidate=NFor N seconds after going stale, serve stale and revalidate in the backgroundContent where slightly old is fine and latency matters
stale-if-error=NFor N seconds after going stale, serve stale if the origin errorsResilience during origin outages

immutable is defined in RFC 8246, and the two stale-* extensions come from RFC 5861. Browser support for the stale-* pair is uneven, but most major CDNs honor them, which is where they earn their keep.

Heuristic freshness: caching you never asked for

If a response has no Cache-Control freshness directive and no Expires, caches are still allowed to guess. RFC 9111 suggests a common approach: take a fraction (10% is the typical figure) of the time since Last-Modified. A file last modified 30 days ago can be treated as fresh for about three days with no instruction from you at all.

This is how teams end up with a JavaScript bundle that "won't update" despite never configuring caching. The fix is not to avoid caching, it is to always send an explicit Cache-Control so nothing is left to heuristics.

max-age beats Expires

Expires is an absolute date, which means it depends on clocks agreeing. When both are present, max-age wins. There is no reason to send Expires in new code except to satisfy ancient HTTP/1.0 caches, and the same goes for Pragma: no-cache.

Validation: ETag, Last-Modified and 304 Not Modified

When a stored response goes stale, validation lets the cache ask "has this changed?" instead of re-downloading it. There are two validators, defined in RFC 9110:

When a request carries both, the server must evaluate If-None-Match and ignore If-Modified-Since. ETags are the more precise tool; Last-Modified is the fallback.

The flow below shows both halves working together for a CDN in front of an origin. The first request is served from a fresh cache entry; later, after the entry goes stale, the CDN revalidates and the origin sends headers only.

Browser CDN cache Origin Entry fresh (age under max-age) GET /api/catalog 200 OK (HIT, no origin call) Later: entry stale, has ETag "v42" GET /api/catalog If-None-Match: "v42" 304 Not Modified (no body) refresh age, keep body 200 OK (stored body)

Strong vs weak ETags

An ETag is either strong ("v42") or weak (W/"v42"). A strong ETag promises byte-for-byte identity; a weak one promises only that the two representations are semantically equivalent. For If-None-Match, servers use weak comparison, so W/"v42" and "v42" match. Strong comparison matters for byte-range requests and for If-Match on writes.

This distinction bites in practice. nginx, for example, downgrades a strong ETag to weak when it gzips a response on the fly, because the compressed bytes differ from the original. That is correct behavior, but it surprises people who compare ETags with string equality in their own code. Strip the W/ prefix before comparing for cache validation.

A conditional GET handler that does it right

Here is a minimal Node handler for a JSON endpoint. It hashes the serialized body into an ETag, compares it against If-None-Match, and returns a bodyless 304 on a match:

import { createHash } from 'node:crypto'

function sendJson(req, res, data) {
  const body = JSON.stringify(data)
  const etag = '"' + createHash('sha256').update(body).digest('base64url').slice(0, 22) + '"'

  res.setHeader('ETag', etag)
  res.setHeader('Cache-Control', 'private, no-cache')
  res.setHeader('Vary', 'Authorization')

  const inm = req.headers['if-none-match']
  if (inm) {
    const tags = inm.split(',').map((t) => t.trim().replace(/^W\//, ''))
    if (tags.includes('*') || tags.includes(etag)) {
      res.statusCode = 304
      return res.end()
    }
  }

  res.setHeader('Content-Type', 'application/json')
  res.end(body)
}

Note what this does and does not save. The server still runs the query and serializes the result to compute the hash, so origin CPU is unchanged; the saving is bandwidth and client parse time. If you want to skip the work too, derive the ETag from something cheaper than the body, such as a row's updated_at plus its ID, or a version counter you bump on write. If you want a quick content-hash ETag to paste into a test response, the HTTP header builder generates strong or weak values and explains Cache-Control and Vary combinations alongside.

Vary: the part of the cache key nobody thinks about

By default a cache keys stored responses on method and URL. Vary tells it to add request headers to that key. Vary: Accept-Encoding means gzip and Brotli responses are stored separately, which is what you want. Vary: Authorization means each user's response is stored under its own key.

Two failure modes come up repeatedly:

For anything per-user, Cache-Control: private is the more robust guard: it keeps the response out of shared caches entirely, rather than trusting every cache in the chain to key correctly.

Recipes that hold up

Most applications need only a handful of policies:

ResourceCache-ControlValidatorWhy
Fingerprinted assets (app.3f9a1c.js)public, max-age=31536000, immutableOptionalA new build gets a new URL, so the old one can live forever
HTML pages and app shellsno-cacheETagAlways check, but a 304 makes the check cheap
Public API reads (catalog, docs)max-age=60, stale-while-revalidate=300ETagShort freshness, fast responses while refreshing
Per-user API readsprivate, no-cache plus Vary: AuthorizationETagNever in a shared cache, still revalidates cheaply
Secrets, tokens, payment pagesno-storeNoneNothing should be written to disk anywhere

The first two rows work as a pair. Long-lived fingerprinted assets are only safe because the HTML that references them is revalidated on every load; get the HTML policy wrong and users are stuck on an old shell that points at old bundles.

This whole toolkit is one of the quieter arguments in the REST vs RPC tradeoff: GET requests to stable URLs inherit every cache between client and server for free, while RPC-style POST endpoints get none of it unless you build your own.

Validators on writes: If-Match and lost updates

ETags are not only for reads. Sending If-Match: "v42" on a PUT or PATCH tells the server to apply the change only if the resource is still at version "v42". If someone else wrote in between, the server answers 412 Precondition Failed instead of silently overwriting their change.

This is optimistic concurrency control built into HTTP, and it pairs naturally with partial updates; it is the piece most JSON Patch and JSON Merge Patch implementations forget. Here strong comparison applies, so weak ETags cannot satisfy If-Match.

Mistakes worth checking for today

The takeaway

For every resource, answer two questions separately. How long may a cache reuse this without asking (max-age, s-maxage, immutable, or no-cache for "zero")? And once it is stale, how does it check cheaply (ETag, ideally derived from a version rather than the full body)? Add private or Vary wherever the response depends on who is asking, reserve no-store for things that must never touch disk, and verify the headers at the edge rather than trusting what you configured. Most caching bugs disappear once each response answers both questions explicitly.

#http-caching#cache-control#etag#conditional-requests#cdn#api-design
ShareXLinkedInHacker News

Try it

Free, in your browser, no sign-up.

New posts by email

One email when a new post goes up. No other mail; unsubscribe in one click.

We store your email only to send new posts. See the privacy policy.

Related reading

API Design
Retries Done Right: Exponential Backoff, Jitter and Retry-After
API Design
REST vs. RPC-Style API Design: The Tradeoffs Nobody Puts in the Style Guide
API Design
Designing Sane Pagination: Why Offset Breaks Under Writes and Keyset Fixes It