Skip to content
FrontDepth, Home

Networking

HTTP caching

How browsers and CDNs decide whether to reuse a response — from Cache-Control, freshness and 304 revalidation to hashed assets, stale-while-revalidate, Vary, personalised data in shared caches and purging a CDN.

JuniorMiddleSeniorUpdated 16 November 2026

Reading level

Shows sections up to the selected level.

Before you start

No prerequisites.

This topic starts at Junior level.

JuniorConcept

What HTTP caching is and where caches live

An HTTP cache stores responses and reuses them for later requests, so the response does not have to travel from the origin server again. A cache hit can save a whole round trip, take load off the origin and make a repeat visit feel instant, especially for CSS and scripts. A wrong cache hit shows users old or someone else's data, so caching is as much about correctness as about speed.

Where caches live

  • Private cache — belongs to one client, usually the browser's HTTP cache. It may store personalised responses, because only that user will see them.
  • Shared cache — sits between clients and the origin and serves many users: a CDN, a reverse proxy (nginx, Varnish) or a corporate proxy. It must never hand one user's personal response to another user.

A request for /app.js can pass through both: the browser checks its own cache, then the CDN checks its cache, and only a miss in both reaches the origin.

The cache key

A cache looks responses up by a cache key. RFC 9111 says it contains at least the request method and the target URI; most caches store only GET responses, so in practice the key is the full URL, query string included. The Vary response header adds request headers to the key (more on that in the senior sections). Anything else the response depends on — a cookie, the user's country — is not in the key unless you put it there.

Fresh or stale

The server describes reuse with the Cache-Control response header:

Text
HTTP/1.1 200 OK
Content-Type: text/css
Cache-Control: max-age=3600
ETag: "5f2a-19c"

For the next hour this response is fresh: the cache may reuse it without asking anyone. After that it is stale. A stale response is not thrown away; the cache asks the origin whether it is still valid (a conditional request), and the origin answers 304 Not Modified without a body, or sends a new 200.

Key points

  • Caching is on by default: a response without Cache-Control can still be cached heuristically, so always say explicitly what you want.
  • Freshness decides whether to ask; validation decides whether to download again.
  • The key decides which stored response is used. Most caching bugs are a key that misses something the response depends on.
JuniorConcept

Freshness: max-age, Expires, Age and heuristics

A cached response is fresh while its age is less than its freshness lifetime. RFC 9111 takes the lifetime from the first rule that matches:

  1. In a shared cache, s-maxage=N from Cache-Control.
  2. max-age=N from Cache-Control.
  3. Expires minus Date (two absolute dates).
  4. Otherwise there is no explicit lifetime, and the cache may use a heuristic.
Text
Cache-Control: max-age=60, s-maxage=600
Expires: Mon, 16 Nov 2026 12:00:00 GMT
Date: Mon, 16 Nov 2026 10:00:00 GMT

A CDN keeps this response for 600 seconds, a browser for 60, and both ignore Expires, because max-age (or s-maxage in a shared cache) wins. Expires comes from HTTP/1.0; an absolute date depends on correct clocks, which is why max-age replaced it. An invalid Expires, such as the common Expires: 0, must be treated as a time in the past: already stale.

Age

When a CDN serves a response it has held for a while, it sends an Age header with the seconds since the response was generated or last validated at the origin:

Text
Cache-Control: max-age=600
Age: 540

The browser counts that time too: this response is fresh in the browser for only 60 more seconds, not 600. The full RFC formula also accounts for the Date header and the network delay; "Age plus time in my cache" is the useful approximation. This is why a CDN with a long max-age can make content look older than you expect.

Heuristic freshness

If a response has no max-age, s-maxage or Expires, a cache may guess. The RFC suggests a fraction of the time since Last-Modified, typically 10%: a file last modified 10 days ago may be reused for about a day without asking. Heuristics apply only to status codes defined as heuristically cacheable (200, 203, 204, 206, 300, 301, 308, 404, 405, 410, 414 and 501) or to responses marked public.

A real bug this causes: an API endpoint or HTML page sent without Cache-Control but with Last-Modified from a static file server, and users keep seeing yesterday's version after a deploy. The fix is to always send Cache-Control explicitly — even if the answer is no-cache.

Quick rules

  • Prefer max-age; Expires is only a fallback for very old caches.
  • Use s-maxage when the CDN may keep something longer than browsers.
  • "Fresh" means "may be reused without contacting the origin", nothing more.
MiddleConcept

no-cache, no-store, must-revalidate, private, public

The response directives that cause the most confusion, as RFC 9111 defines them:

  • no-cache — the response may be stored, but it must not be reused without validating it with the origin first. It does not mean "don't cache". With an ETag, each reuse costs a small conditional request that usually ends in 304.
  • no-store — no cache, private or shared, may store the request or the response. Use it for responses that must never be written anywhere: a bank statement, a one-time token. It does not delete a copy stored earlier under the same URL.
  • must-revalidate — the response may be reused while fresh; once stale, it must be validated before reuse and may never be served stale (if the origin is unreachable, the cache returns an error such as 504). It overrides permissions like stale-while-revalidate.
  • private — only a private (browser) cache may store it. Use it for personalised responses: after login, a cart, account pages.
  • public — a shared cache may store it even where it otherwise could not, most notably for a request with an Authorization header. You rarely need it; adding it "to make caching work" can make a CDN share authenticated responses.
  • s-maxage=N — the lifetime for shared caches only; private caches ignore it. Like public, it also lets a shared cache reuse responses to requests with Authorization.

When directives conflict (for example max-age=600, no-cache), the RFC says to honour the most restrictive one.

Common combinations

Text
Cache-Control: no-cache
Cache-Control: no-cache, private
Cache-Control: no-store
Cache-Control: max-age=31536000, immutable

The first suits public HTML: always check, download only when changed. The second is MDN's default for personalised pages: the browser may keep the page, the CDN may not, and every reuse is validated. The third is for truly sensitive data; it also costs you the back/forward cache in many browsers, so do not use it by reflex. The fourth is for files whose URL changes when their content changes.

max-age=0, must-revalidate behaves like no-cache; it exists because old HTTP/1.0 caches did not understand no-cache. The "kitchen sink" no-store, no-cache, max-age=0, must-revalidate, proxy-revalidate is cargo cult: no-store alone already forbids storing.

Request directives

Cache-Control also exists on requests. A normal reload sends Cache-Control: max-age=0 plus conditional headers, so caches validate; a forced reload sends no-cache without conditions, so the origin sends a full 200. In code, fetch(url, { cache: "no-cache" }) validates and fetch(url, { cache: "reload" }) bypasses the cache.

MiddleWeb platform

Revalidation: ETag, Last-Modified and 304

When a stored response is stale (or marked no-cache), the cache does not download it blindly. It sends a conditional request with the validators it stored, and the origin decides whether anything changed.

Text
GET /index.html HTTP/1.1
Host: shop.example
If-None-Match: "33a64df5"
If-Modified-Since: Mon, 16 Nov 2026 08:00:00 GMT
Text
HTTP/1.1 304 Not Modified
Cache-Control: no-cache
ETag: "33a64df5"
Date: Mon, 16 Nov 2026 10:00:00 GMT

A 304 has no body. The cache updates the stored headers from it (new Date, Cache-Control, ETag) and serves the body it already has. The request still costs a round trip, but only a few hundred bytes instead of the whole resource.

Two validators

  • ETag / If-None-Match — an opaque version identifier chosen by the server, often a content hash. W/"…" marks a weak ETag: "semantically the same" rather than byte-for-byte identical. If a request carries both conditions, If-None-Match takes precedence.
  • Last-Modified / If-Modified-Since — a date with one-second resolution. Two changes within the same second, or a file whose timestamp changes on every deploy, make it unreliable.

Send an ETag when you can, and Last-Modified as well if you have it.

What you see in practice

  • In Chrome DevTools a fresh hit is a 200 with "(disk cache)" or "(memory cache)" in the Size column; no request went out. A revalidation is a real request with status 304.
  • fetch() hides revalidation: when the browser adds the conditional headers itself and gets a 304, your code receives the cached response with status 200. If you set If-None-Match yourself, the browser leaves its cache out of it and your code sees the 304.
JavaScript
const response = await fetch("/api/catalog", { cache: "no-cache" });
console.log(response.status); // 200

The log says 200 even when the network answer was a 304.

Bugs worth knowing

  • ETags that differ per server. If every machine behind a load balancer computes its own ETag for the same file (for example from inode numbers), validation fails whenever the request lands on another machine, and every check becomes a full download.
  • Validators on dynamic HTML. An ETag computed after rendering still saves bandwidth, but the server does the full work for every request. Cheaper ETags come from a version number or updatedAt of the data.
  • Validation is not freshness. no-cache with a good ETag is fast, but it is still one round trip per reuse; for files that never change, use long lifetimes instead.
MiddleExample

A practical setup: hashed assets, short-lived HTML, APIs

Most web apps need only a few header sets. The idea behind them: a URL that never changes its content can be cached forever, and a URL that does change must be checked.

Hashed assets: cache forever

Bundlers put a content hash in file names: /assets/index-e41d07.js. When the code changes, the hash and therefore the URL change, so an old URL is never reused for new content ("cache busting"):

Text
Cache-Control: public, max-age=31536000, immutable

One year is the conventional "forever". immutable tells the browser not to revalidate the file while it is fresh, even on reload; per MDN's compatibility data Firefox and Safari support it, while Chrome does not implement the directive (sending it there is harmless). public is not required here — MDN uses it in its example, but advises adding it only when you need it.

HTML: always check

The HTML document is the entry point that names the current hashed files, and its URL cannot be versioned. It must be revalidated so users get the new asset list right after a deploy:

Text
Cache-Control: no-cache
ETag: "AAPuIbAOdvAGEETbgAAAAAAABAAE"

If the page is personalised, use no-cache, private. A long max-age on HTML is the classic "users see the old version for days" bug: there is no way to recall a response from browsers' caches.

APIs and data

Public data that may be a little old (a product list, an exchange-rate table):

Text
Cache-Control: max-age=10, s-maxage=60, stale-while-revalidate=30

Browsers reuse the response for up to 10 seconds (counting the Age the CDN reports), the CDN for 60. After that, for 30 more seconds, either cache may answer with the stale copy while fetching a fresh one in the background. That is stale-while-revalidate (RFC 5861): users do not wait for the refresh, and the origin gets roughly one request per URL per minute from each CDN location instead of one per visitor. Browsers support it too (Chrome 75, Firefox 68, Safari 14).

stale-if-error=N lets a cache answer with a stale copy for N seconds when the origin fails (500, 502, 503, 504 or an unreachable network) — useful on a CDN in front of a flaky origin; check that your CDN supports it.

Personal or transactional data (cart, account, checkout quote):

Text
Cache-Control: no-store

or private, no-cache if the browser may keep a copy for back navigation.

Deploy order matters

After a deploy, users who still have the old HTML request old hashed files. Upload new assets first, switch the HTML last, and keep old assets for a while; deleting them breaks every open tab that lazy-loads a chunk later (TypeError: Failed to fetch dynamically imported module in Chromium, ChunkLoadError in webpack apps).

SeniorPitfalls

Shared caches, Vary and personalised data

A shared cache returns whatever it stored under the key. If the response depends on anything that is not in the key, the first response wins and every later user gets it: wrong prices, the wrong language, another user's account page.

Vary adds request headers to the key

Text
Vary: Accept-Encoding

The correct, common case: gzip, Brotli and uncompressed variants are stored separately, so a client that cannot decode Brotli never gets Brotli. But every header you add multiplies the variants:

  • Vary: User-Agent — thousands of distinct values, so almost every request misses.
  • Vary: Cookie — the whole Cookie header, session id included, becomes part of the key: effectively one entry per visitor. For personalised responses MDN recommends Cache-Control: private instead.
  • Vary: * — never matches, so the response is never reused without validation.

Authorization, cookies and directives that unlock sharing

A shared cache must not reuse a response to a request with an Authorization header — unless the response carries public, s-maxage or must-revalidate. So s-maxage=300 added to an authenticated API "for performance" lets the CDN serve one user's data to the next. Cookies are not protected at all: a cacheable response that depends on a session cookie, or even carries Set-Cookie, may be stored and reused (RFC 9111 says Set-Cookie does not inhibit caching). Many CDNs skip such responses by default, but that is configuration, not protocol. Mark personalised responses private (or no-store) at the origin.

Example: a price keyed by URL

A shop keeps the selected currency in a cookie, and its CDN keys by URL. The first response wins:

Text
GET /api/products/lamp-l3   Cookie: currency=EUR   → MISS, cached: 30.00
GET /api/products/lamp-l3   Cookie: currency=USD   → HIT:  30.00

The USD customer gets the EUR number, and the page shows it with a dollar sign. The fix keeps the cache and completes the key: put the currency in the URL (/api/products/lamp-l3?currency=USD) or configure the CDN to key on that one cookie — not Vary: Cookie. The same rule holds for a cache in your own code: the key must contain every input the request depends on. And whatever decides what a customer pays should be computed by the origin, never read from a cache.

Cache poisoning

The security side of the same rule: if the origin builds a response from a header that is not in the key (say, X-Forwarded-Host for absolute URLs), one crafted request can get a poisoned response cached for everybody. Every request input the origin reads must be in the key or ignored.

The platform's stale-price-cache incident lets you investigate a wrong-data cache bug in a running shop.

SeniorWeb platform

Browser caches, service workers and CDN invalidation

"The browser cached it" can mean three different mechanisms with different rules. Name the right one when debugging.

The HTTP cache

Everything above applies here. DevTools labels a hit "(memory cache)" or "(disk cache)": that is where the browser happened to keep the response, not a different set of rules. Modern browsers also partition this cache by the top-level site, so a library loaded from a public CDN by two different sites is downloaded once per site.

The back/forward cache (bfcache)

The bfcache keeps a snapshot of the whole page, including its JavaScript heap, when the user navigates away, and restores it instantly on Back or Forward. Restoring a page from it makes no requests at all, and MDN warns that no-cache does not guarantee revalidation on history navigations. Pages sent with Cache-Control: no-store have historically been excluded from the bfcache (web.dev notes that Chrome is working on changing this). Data that can go stale while the page sits in the bfcache, such as a cart count, should be refreshed on pageshow:

JavaScript
window.addEventListener("pageshow", (event) => {
  if (event.persisted) refreshCartBadge();
});

The service worker's Cache API

caches.open() and cache.put() are storage that your code manages. MDN: the Cache API does not honour HTTP caching headers, and entries never expire unless you delete them. A service worker that serves from it decides freshness itself (cache first, network first, stale-while-revalidate as a strategy). Its own fetch() calls go through the HTTP cache like any other, so a precache step can store a stale copy unless the URLs are hashed or fetched with cache: "no-cache".

Invalidation

A response stored in browsers cannot be recalled before it expires; Clear-Site-Data: "cache" clears the browser cache only for a user who receives that header, and has no effect on intermediaries. That is why browser lifetimes for changing URLs stay short. A CDN, on the other hand, is a managed cache you can purge:

  • Versioned URLs for assets: nothing to purge, the new deploy uses new URLs.
  • Purge by URL or prefix after publishing content.
  • Purge by tag: the origin labels responses (Fastly's Surrogate-Key, Cloudflare's Cache-Tag) and one call purges every page that shows, say, product 42 when its price changes.
  • Soft purge (where offered) marks entries stale instead of deleting them, so stale-while-revalidate and stale-if-error keep working during the refill.

A common split is a long s-maxage with event-driven purges for the CDN, and a short max-age or no-cache for browsers, which you cannot purge. RFC 9213's CDN-Cache-Control header can carry the CDN's lifetime separately from Cache-Control.

SeniorInterview tips

Interview tips

A 30-second answer. "A cache reuses a stored response while it is fresh, as long as Cache-Control allows it. When it goes stale, the cache sends a conditional request with If-None-Match or If-Modified-Since and gets either a 304 or a new response. In practice I give hashed assets a one-year max-age with immutable, send HTML with no-cache and an ETag, and mark anything personal private or no-store."

Questions you are likely to get

  • no-cache vs no-store? no-cache stores and validates before every reuse; no-store never stores. Mention that no-store also costs the bfcache in many browsers.
  • Users still see the old version after a deploy — why? A long lifetime on HTML or on an unversioned file, heuristic freshness on a response without Cache-Control, or a service worker serving its own cache. Explain how you would tell them apart in DevTools (a 200 from "(disk cache)", a 304, or "(ServiceWorker)" in the Size column).
  • How do you cache static assets? Content hashes in file names, max-age=31536000, immutable, HTML revalidated; deploy assets before HTML and keep old ones.
  • What does a CDN add? Shared cache, s-maxage, Age, purge APIs, stale-while-revalidate and stale-if-error to protect the origin.
  • How can caching leak data? A personalised response cached by a shared cache: missing private, public or s-maxage on authenticated responses, or a key that ignores a cookie the response depends on.

Mistakes that cost points

  • Saying no-cache means "not cached".
  • Thinking Expires still matters when max-age is present.
  • Treating a 304 as "served from cache without a request" — it is a request, only the body is skipped.
  • Fixing a wrong-data bug by removing the cache. The senior answer is to fix the key or the lifetime and keep the cache.
  • Calling the bfcache, the HTTP cache and the Cache API "the browser cache" without distinguishing them.

Senior signal

Talk about the key and invalidation, not only headers: what the response depends on, who may share it, how long a wrong answer may live, and how you will remove it (versioned URLs, purge by tag, short browser lifetimes). Mention the metric that tells you caching is correct, not just effective: hit ratio and origin load next to a correctness check, for example sampling cached responses against the origin.

JuniorReview checklist

What to check when reviewing HTTP caching headers

Use this list on caching headers or cache code you did not write: a teammate's pull request, a library's config or an AI assistant's suggestion. A wrong header passes every test, then shows users an old version for days or one user's data to another, and copies stored in browsers cannot be recalled.

  • Are personalised responses marked private or no-store, with no public or s-maxage on authenticated ones? Those two let a CDN reuse responses to requests with Authorization, and a session cookie does not stop a shared cache from storing them. Check the headers in the DevTools Network panel.
  • Is the HTML sent with no-cache and an ETag (plus private if personalised), not a long max-age? It names the current hashed files, so a day of freshness means a day of the old app after a deploy.
  • Does every response set Cache-Control explicitly? Without it a cache may guess a lifetime from Last-Modified and keep serving yesterday's version.
  • Are max-age=31536000 and immutable only on URLs with a content hash? On an unversioned /logo.svg, a new version cannot reach users for a year.
  • Is everything the response depends on part of the cache key? In practice the key is the URL: a language read from a cookie is not in it, so the first stored response wins for everyone. Put the value in the URL or the CDN key; Vary: Cookie means one entry per visitor.
  • Does each directive mean what the author thinks? no-cache stores but validates before every reuse; no-store never stores and in many browsers costs the back/forward cache. In the Network panel's Size column, "(disk cache)" means no request went out; a 304 was a real request.

Check your understanding

  • Practice

    Predict-output and open interview questions with self-assessment.

    3 predict-output · 4 open

  • Quiz

    Multiple-choice questions with explanations and a score.

    6 questions

Hands-on work that uses this topic.