Skip to content
Commitwise
Menu
Networking

HTTP caching

How browsers, apps and CDNs reuse responses. Covers Cache-Control, max-age, no-cache vs no-store, heuristic caching when there are no headers, ETags and 304 Not Modified, private vs shared caches, s-maxage, Vary, stale-while-revalidate, versioned asset URLs, caching in iOS and Android clients, and the CDN bug that shows one user's data to another.

intermediate

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

The fastest request is the one that never goes out. HTTP caching lets a browser, an app or a CDN keep a copy of a response and reuse it: the page loads instantly, the server handles a fraction of the traffic, and the user’s data plan lasts longer.

Caching is controlled by a few response headers, and most caching bugs come from misreading them: no-cache that still caches, a release that users don’t see for a day, a profile cached by a CDN and shown to the wrong person. This lesson covers how a cache decides whether a stored copy is fresh, how it checks a stale copy cheaply, and what changes when the cache is shared. It builds on HTTP: methods, status codes and headers.

New to some of these? Open what you need, or skip ahead.

Basics:Request and response headers

Every HTTP response carries headers, name-value lines before the body, like Content-Type: application/json. Caching is controlled almost entirely by response headers the server sends, and a few request headers the client adds when it checks a stored copy. See HTTP: methods, status codes and headers.

Basics:Cache

A cache is a store of copies kept close to where they’re needed, so the original doesn’t have to be fetched again. The hard parts are always the same: how long a copy stays valid, and how to notice when the original has changed. See cachingCachingKeeping a copy of data somewhere faster, so you don't fetch or compute it again every time.Open in glossary →.

Part Not started

Freshness: how long a copy can be reused

When a response arrives, a cache asks one question: may I store this, and for how long can I reuse it without asking the server? The server answers with the Cache-ControlCache-ControlThe HTTP header that tells browsers, apps and CDNs whether a response may be stored and how long it stays fresh.Open in glossary → header:

HeaderMeaning
Cache-Control: max-age=3600Fresh for 3600 seconds. Reuse it without any request during that time.
Cache-Control: no-cacheYou may store it, but check with the server every time before using it.
Cache-Control: no-storeDon’t store it at all. Use for sensitive data.
Cache-Control: privateOnly the user’s own browser or app may store it, not a shared cache like a CDN.
Cache-Control: public, max-age=31536000, immutableAnyone may cache it for a year, and it will never change.

While a stored response is fresh, the cache answers from its copy and no request leaves the device. When it becomes stale, the cache doesn’t throw it away: it asks the server whether the copy is still good, which the next part covers.

The names are confusing, so remember this pair: no-cache means “revalidate before use”, and no-store means “don’t keep it”. If a response contains a bank balance or a medical record, no-store is the one you want.

One more surprise: a response with no caching headers at all can still be cached. If it has a Last-Modified date, browsers and many clients guess a lifetime, commonly 10% of the time since the last modification. A file last changed 10 days ago may be reused for about a day without asking. So every response should say what it wants explicitly.

  • Freshness lifetime, in priority order: s-maxage (shared caches only), max-age, then Expires (an absolute date, sensitive to clock skew), then heuristic freshness (RFC 9111 suggests up to 10% of the age since Last-Modified) for cacheable status codes like 200, 301 and 404. Age is the response’s current Age header plus time spent in this cache.
  • no-cache stores and always revalidates; no-store forbids storage (memory too, ideally); must-revalidate forbids serving stale copies even when offline or when the origin is down; private excludes shared caches; immutable tells browsers not to revalidate on reload.
  • Request directives matter too: a browser reload sends Cache-Control: max-age=0 (revalidate), a hard reload sends no-cache; fetch(url, { cache: 'no-store' }) and similar options in client libraries override the default for one request.
  • What’s cacheable: GET and HEAD by default; POST responses only with explicit freshness, and in practice nobody caches them. Responses with Authorization are not stored by shared caches unless public, s-maxage or must-revalidate say so.
  • Browsers have several layers: memory cache, HTTP disk cache, service worker caches (programmable, ignore HTTP headers unless your code checks them), and the back/forward cache, which keeps the whole page in memory and is blocked by Cache-Control: no-store on the document in some browsers.
  • Clients outside browsers: URLCache on iOS (on by default for URLSession.shared, size-limited), OkHttp’s Cache on Android (off until you configure one), and no HTTP cache at all in Java’s HttpClient or Node’s fetch.

Predict the output

The server sends the response below, with no Cache-Control and no Expires. The page fetches the same URL twice, a few seconds apart. How many requests reach the server?

HTTP/1.1 200 OK
Content-Type: text/plain
Last-Modified: Thu, 05 Nov 2026 09:12:00 GMT

t=1794778959425
# build output with a content hash in the name: cache forever
GET /_astro/app.8d2f1c.js
Cache-Control: public, max-age=31536000, immutable

# the HTML that references those files: always check, so a release shows up at once
GET /orders
Cache-Control: no-cache

# an API response that is the same for everyone and may be a minute old
GET /api/products?category=shoes
Cache-Control: public, max-age=60

# one user's data: their device may keep it briefly, nobody else may
GET /api/me
Cache-Control: private, max-age=30

# sensitive: never written to disk
GET /api/account/statements/2026-10
Cache-Control: no-store

The header that sounds right

Spot the bugKeeping bank statements out of the cache

Tap the line with the bug.

app.get('/api/statements/:month', requireLogin, async (req, res) => {
  const statement = await loadStatement(req.user.id, req.params.month);
  // statements must never be cached
  res.set('Cache-Control', 'no-cache');
  res.json(statement);
});

Deep dive"We deployed, but users still see the old version"Interview favorite

A classic support ticket, and the question behind it is “which cache is holding the old copy, and who told it to?”. Work through the layers from the user outward:

  1. The HTML document. If index.html has max-age=3600, or no header at all (heuristic caching), browsers keep showing the old page, which references the old JavaScript files. Fix: Cache-Control: no-cache on HTML, so every visit revalidates, which is cheap with an ETag.
  2. Assets without versioned names. /app.js with a long max-age can’t be updated: the browser won’t ask. Fix: content-hashed names (app.8d2f1c.js, which every modern bundler produces) with max-age=31536000, immutable, so a new release simply references new URLs.
  3. The CDN. It may have its own TTL from s-maxage or from dashboard rules that override the origin’s headers. Fix: purge the HTML on deploy, or keep its edge TTL short.
  4. A service worker. It serves from its own cache regardless of HTTP headers, and a new worker version waits until all tabs using the old one close. Fix: a deliberate update strategy (prompt the user, or skipWaiting plus reload), and never cache the service worker script itself for long.
  5. Mobile apps don’t have this problem for their own UI, but their API responses can: an URLCache or OkHttp cache honouring a generous max-age serves an old feature-flag config. Fix: short lifetimes on config, or validators.

The general rule to state: long-lived caching only for URLs whose content never changes, short or revalidated caching for the entry points that point to them. Mention the opposite failure too: a site that sends max-age=0, must-revalidate on hashed assets makes every visit revalidate every file, wasting a round trip each, when a year-long immutable would cost nothing.

  • Lifetime: s-maxage (shared) > max-age > Expires > heuristic (~10% of age since Last-Modified). Always send Cache-Control.
  • no-cache = store, revalidate every use; no-store = never store; must-revalidate = no stale serving; private = no shared caches; immutable = no reload revalidation.
  • Hashed assets: a year, immutable. HTML entry points: no-cache. Sensitive data: no-store.
  • Clients: iOS URLCache on by default, OkHttp cache off until configured, Java HttpClient and Node fetch have none. Service workers ignore HTTP headers.
Cache-Control: public, max-age=31536000, immutable   # /assets/app.8d2f1c.js
Cache-Control: no-cache                              # /index.html
Cache-Control: no-store                              # /api/statements/...

Check this part

  1. Which header keeps a response out of every cache?

  2. A response has no Cache-Control header but has Last-Modified a month ago. Can the browser reuse it without asking?

  3. Hashed asset URLs get max-age=0, must-revalidate. What is the cost?

  4. Which HTTP client caches responses by default?

Cache-Control tells caches how long a response stays fresh. max-age=N means reuse it without asking for N seconds. no-cache means store it but check with the server before every use; no-store means never store it. Without any caching headers, caches may still reuse a response for a while based on Last-Modified (heuristic caching), so always send Cache-Control.

Part Not started

Validation: ETags and 304 Not Modified

When a stored copy is stale, or was stored with no-cache, downloading it again would be wasteful if nothing changed. Instead the cache asks: “I have this version; has it changed?”

For that, the server includes a validator with the original response:

The next request repeats the validator in a conditional header, and the server compares:

1st request   GET /api/products/42
              <- 200 OK, ETag: "v1", Cache-Control: no-cache, body (2 KB)

2nd request   GET /api/products/42
              If-None-Match: "v1"
              <- 304 Not Modified, no body           (nothing changed: use your copy)

after an edit GET /api/products/42
              If-None-Match: "v1"
              <- 200 OK, ETag: "v2", new body

A 304 still costs a round trip, but no body: a few hundred bytes instead of the whole response, and often less work on the server. That’s why no-cache plus an ETag is the usual choice for HTML and for API data that must always be current.

If-Modified-Since works the same way with dates. When a response has both validators, the ETag wins.

  • Strong vs weak ETags: "abc" promises byte-identical content (usable for range requests); W/"abc" means semantically the same. Compression changes the bytes, so NGINX turns strong ETags into weak ones when it gzips on the fly.
  • Generating ETags: a hash of the body (simple; still costs rendering the body, but saves bandwidth), a version column or updated_at from the database (lets the server answer 304 without building the response), or a framework default. Make sure all instances generate the same ETag for the same content; inode-based file ETags (old Apache defaults) differ per server.
  • Who handles conditionals: frameworks often answer 304 automatically for GET when the computed ETag matches (Express, Spring’s ShallowEtagHeaderFilter); CDNs revalidate with the origin and may also answer clients’ conditional requests themselves.
  • Clients: browsers, URLCache and OkHttp send conditional requests and turn a 304 into the stored 200 for your code; you only see the 304 if you send If-None-Match yourself. Apps that manage their own cache (Room, Core Data) can store the ETag and send it manually.
  • Write side: If-Match: "v1" on PUT or PATCH gives optimistic concurrency: the server answers 412 Precondition Failed if someone else changed the resource first. Same validators, different purpose.

Predict the output

The endpoint below sends Cache-Control: no-cache with an ETag. The page fetches it twice. The second time the server receives If-None-Match: "v1" and answers 304 with no body. What does the second fetch() give the JavaScript code?

const first = await fetch('/api/price');   // 200, ETag: "v1", Cache-Control: no-cache
const second = await fetch('/api/price');  // server gets If-None-Match: "v1", answers 304
console.log(second.status, await second.text());
// server side: compare the stored version with the client's ETag
app.get('/api/products/:id', async (req, res) => {
  const product = await db.products.find(req.params.id);
  const etag = `"${product.version}"`;
  res.set({ ETag: etag, 'Cache-Control': 'no-cache' });
  if (req.get('If-None-Match') === etag) return res.status(304).end();
  res.json(product);
});
# first request: note the ETag
curl -sI https://shop.example/api/products/42 | grep -iE 'etag|cache-control'
# etag: "7c1f2a"
# cache-control: no-cache

# conditional request with the ETag: 304 and no body if unchanged
curl -s -o /dev/null -w '%{http_code} %{size_download} bytes\n' \
  -H 'If-None-Match: "7c1f2a"' https://shop.example/api/products/42
# 304 0 bytes

Worked example: a product page revisited

  1. Monday, first visit. The app requests /api/products/42. The server answers 200 with the product (2 KB), ETag: "v7" and Cache-Control: max-age=60. The client stores it.
  2. Thirty seconds later. The user opens the product again. The copy is 30 seconds old, still fresh, so the client uses it. No request goes out.
  3. Five minutes later. The copy is stale. The client sends GET /api/products/42 with If-None-Match: "v7".
  4. The server compares. The product is still version 7, so it answers 304 Not Modified with no body. The client marks its copy fresh for another 60 seconds and shows it.
  5. Tuesday, after a price change. The product is now version 8. The conditional request gets 200 OK, ETag: "v8" and the new body, which replaces the stored copy.

Over a day of browsing, most visits cost nothing or a tiny 304, and the price is never more than 60 seconds out of date.

Deep diveETags that never matchInterview favorite

“We added ETags, but the hit rate is zero.” Validation silently stops working in a few predictable ways, and each is a good interview probe:

  • Different ETags per server. Behind a load balancer, instance A answers "abc-1", instance B "abc-2" for identical content, because the ETag includes an inode, a build timestamp or a per-process counter. Every conditional request that lands on another instance misses. Fix: derive ETags from content or a database version.
  • The body changes on every request. The ETag is a hash of a JSON body that includes serverTime or a request ID. Remove volatile fields, or compute the ETag from the stable data.
  • A proxy modifies the response. On-the-fly compression weakens ETags (W/), and some old proxies or CDNs strip ETags from compressed responses entirely. Check what actually reaches the client with curl -I through the real path.
  • The client never sends it. Custom caching code stores the body but not the ETag, or a library is configured with no cache. Check the server log for If-None-Match.
  • The server ignores it. A framework computes ETags only for some responses, or a hand-written handler sets an ETag but always returns 200.

Also mention what an ETag costs: if it’s a hash of the rendered body, the server still does the full database query and rendering, and only saves bandwidth. A version stored with the data (updated_at, a revision counter) lets the server answer 304 after a cheap lookup, which is where the real CPU savings come from.

  • Validators: ETag (strong or W/ weak) and Last-Modified; conditionals If-None-Match (wins) and If-Modified-Since; 304 has no body.
  • Browsers, URLCache, OkHttp turn 304 into the stored 200 for your code.
  • ETags must be identical across instances; derive them from content or a stored version so 304 also saves CPU.
  • If-Match plus 412 gives optimistic concurrency on writes.
curl -s -o /dev/null -w '%{http_code}\n' -H 'If-None-Match: "7c1f2a"' https://host/api/x   # 304

Check this part

  1. What does a 304 Not Modified response contain?

  2. Which request header carries the ETag back to the server?

  3. Conditional requests miss on half the requests behind a load balancer. Likely cause?

  4. What does If-Match on a PUT give you?

A stale copy is checked with a conditional request. The server sends a validator (ETag or Last-Modified); the client sends it back in If-None-Match or If-Modified-Since, and the server answers 304 Not Modified with no body if nothing changed. JavaScript and most client libraries see the cached body as a normal 200. ETags must be the same on every server behind a load balancer.

Part Not started

Shared caches and CDNs

So far the cache belonged to one user: their browser or app. A shared cache sits between many users and the server, most often a CDNCDN (content delivery network)Servers in many cities that keep copies of your files and answer users from nearby, fetching from your origin only on a miss.Open in glossary →, and answers everyone from the same stored copy. That’s what makes CDNs powerful, and dangerous:

  • A product list cached at the CDN is served to a million users while the server sees a handful of requests.
  • A /api/me response cached at the CDN is served to everyone, with the first user’s name and address.

So for every response, decide whether it’s the same for everyone. If it isn’t, it must say private (only the user’s own device may store it) or no-store.

A few more tools for shared caches:

  • s-maxage=N sets the lifetime for shared caches only: Cache-Control: public, max-age=60, s-maxage=600 lets browsers reuse for a minute and the CDN for ten.
  • Vary lists request headers that change the response. With Vary: Accept-Language, the cache keeps a separate copy per language instead of serving English to everyone.
  • stale-while-revalidate=N: after the copy goes stale, the cache may still serve it for N more seconds while it fetches a fresh one in the background. Users get an instant answer, and the copy is updated for the next one.

And the best way to change cached files is not to change them: give each version a new URL (app.8d2f1c.js) instead of trying to remove the old one from caches around the world.

  • Cache key: by default method plus URL (scheme, host, path, query). Vary adds request headers; CDNs often let you normalize or drop query parameters (tracking parameters fragment the cache) and add headers or cookies to the key explicitly.
  • Vary costs: Vary: User-Agent or Vary: Cookie makes nearly every request a miss; prefer normalized headers (a CDN-computed device class) or separate URLs. Vary: Accept-Encoding is normal; Vary: Origin is required when CORS headers differ per origin.
  • Default safety: shared caches don’t store responses to requests with Authorization unless told to, but cookie-authenticated responses with public or a CDN rule like “cache everything” are stored. Web cache deception attacks trick a CDN into caching /account/settings/x.css because of the extension.
  • Stale serving: stale-while-revalidate (latency), stale-if-error (serve old content when the origin fails); CDNs add request collapsing so one miss for a hot key sends one origin request, not thousands.
  • Invalidation: versioned URLs for assets; for content that changes in place, short edge TTLs, purge by URL, or purge by tag (Cache-Tag, Surrogate-Key) on content updates. CDN-Cache-Control or Surrogate-Control let you set CDN rules without affecting browsers.
  • Debugging headers: Age (seconds the copy spent in caches), cf-cache-status or x-cache (HIT, MISS, EXPIRED, BYPASS), Cache-Status (the standard, RFC 9211).

Predict the output

A product list is served through a CDN with the header below. A copy was stored 200 seconds ago. A user requests it now. What happens?

Cache-Control: public, max-age=60, stale-while-revalidate=300
// iOS: URLSession.shared already uses URLCache.shared; give it room and pick a policy per request
URLCache.shared = URLCache(memoryCapacity: 20 * 1024 * 1024,
                           diskCapacity: 100 * 1024 * 1024)
var request = URLRequest(url: URL(string: "https://api.shop.example/products")!)
request.cachePolicy = .useProtocolCachePolicy   // follow Cache-Control and ETags (default)
let (data, response) = try await URLSession.shared.data(for: request)
// Android: OkHttp caches only when you give it a Cache
val client = OkHttpClient.Builder()
    .cache(Cache(File(context.cacheDir, "http"), 50L * 1024 * 1024))
    .build()

// force a network check for one request, e.g. pull-to-refresh
val request = Request.Builder()
    .url("https://api.shop.example/products")
    .cacheControl(CacheControl.FORCE_NETWORK)
    .build()

Practice: pick the headers

Exercisemedium

Cache-Control for an online shop

Choose a Cache-Control header for each response. The site uses a CDN.

  1. /assets/app.3f9a1c.js, a file built with a content hash in its name.
  2. / and other HTML pages.
  3. /api/products?category=shoes, the same for every user, fine if a minute old.
  4. /api/cart, the current user’s cart.
  5. /api/orders/1842/invoice.pdf, an invoice with the customer’s address.
  6. /logo.png, a file that keeps its name when the designer updates it.
›

For each: is it the same for every user? Can it change while keeping its URL? Is it sensitive?

SolutionTry it yourself first
  1. public, max-age=31536000, immutable. The content can never change under this URL, so cache it everywhere for a year.
  2. no-cache (with an ETag). Pages must reflect a new release immediately; revalidation is cheap.
  3. public, max-age=60 (optionally stale-while-revalidate=300). The CDN absorbs nearly all traffic.
  4. private, no-cache or simply no-store. Never in the CDN; a stale cart in the app is confusing anyway.
  5. private, no-store. Personal and sensitive: not in the CDN, not on the device’s disk.
  6. Either rename it with a hash like the other assets (best), or give it a short lifetime such as public, max-age=3600, accepting that a change takes up to an hour to reach everyone.
Deep diveThe CDN that showed one user's account to anotherInterview favorite

“After we put the API behind a CDN, some users saw other people’s profiles.” A real incident pattern, worth being able to dissect.

How it happens. /api/me is authenticated by a session cookie. A developer adds Cache-Control: public, max-age=60 to speed up the profile screen, or a CDN rule says “cache all GET responses for 60 seconds” and ignores the origin’s headers. The cache key is the URL, and the URL is the same for everyone. The first user’s response is stored; for the next minute, everyone who asks gets it. Variants: caching a response that sets a session cookie (Set-Cookie served to everyone logs them in as one person), and web cache deception, where /api/me/x.css is cached because of a “cache static extensions” rule.

How to prevent it, as layers:

  • Personalized responses send Cache-Control: private or no-store, set by default in the framework (a middleware that marks every authenticated response private unless a route opts in).
  • CDN rules respect origin headers, and “cache everything” rules are limited to asset paths. Bypass the cache when a session cookie or Authorization is present.
  • Never cache responses with Set-Cookie; most CDNs bypass them by default, check yours.
  • Make paths strict: /api/me/anything.css should be a 404, not the profile.
  • Test it: a CI check that requests authenticated endpoints and fails on public or a missing private, and monitoring of cf-cache-status or Cache-Status for API routes that should always be BYPASS.

After it happens: purge the cache for the affected paths at once, fix the headers, find the time window from CDN logs, and treat it as a data breach for legal purposes, since personal data was disclosed.

  • Shared caches key on method plus URL (plus Vary): personalized responses must be private or no-store, or one user’s data goes to everyone.
  • s-maxage (or CDN-Cache-Control) for the edge; Vary sparingly (Origin with per-origin CORS, never Cookie); stale-while-revalidate, stale-if-error.
  • Versioned URLs over purges; purge by tag for content updated in place. Bypass the CDN on cookies, Authorization, Set-Cookie.
  • Debug with Age, Cache-Status, cf-cache-status, x-cache.
Cache-Control: public, max-age=60, s-maxage=600, stale-while-revalidate=300
Vary: Accept-Encoding, Accept-Language

Check this part

  1. Which directive stops a CDN from storing /api/me while still letting the user's phone cache it briefly?

  2. What is the best way to update a cached JavaScript file?

  3. Why is Vary: Cookie a bad idea at a CDN?

  4. What does stale-if-error give you?

Shared caches (CDNs, proxies) serve one stored response to many users, so personal responses must be private or no-store, or one user sees another's data. s-maxage sets the CDN lifetime separately, Vary lists request headers that change the response, and stale-while-revalidate serves a slightly old copy while refreshing in the background. Versioned URLs beat purging.

Key takeaways

  • Cache-Control decides how long a copy is fresh: max-age to reuse, no-cache to always check, no-store to never keep.
  • Without headers, caches guess a lifetime from Last-Modified, so always send Cache-Control.
  • Stale copies are checked with ETags: If-None-Match gets a cheap 304 Not Modified when nothing changed.
  • CDNs share one copy among all users: personal responses must be private or no-store.
  • Change cached files by giving them new URLs, and keep HTML revalidated so it points to them.
  • Lifetime order: s-maxage, max-age, Expires, heuristic; immutable for hashed assets, no-cache for entry points.
  • Know which client caches by default: browsers and URLCache yes, OkHttp only when configured, Java HttpClient and Node fetch no.
  • ETags must be stable across instances and ideally come from a stored version, so 304 saves CPU too.
  • Shared caches: cache key plus Vary, bypass on credentials, purge by tag, stale serving, and tests that personalized routes never become public.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.