Sub topic 10
How HTTP Caching Avoids Repeat Requests
This chapter assumes you can read an HTTP request and response (method, status line, headers), and that you know the browser checks local state before it goes to the network. Here we look at what makes a stored response reusable, how a stale one is revalidated, and where caching goes wrong.
Why caching sits on the critical path
Every stage you have seen so far costs time: a DNS lookup, a TCP handshake, a TLS handshake, then a round trip for the request itself. The fastest request is one that never leaves the machine. HTTP caching lets a browser, or a shared proxy or CDN between the browser and the origin server, reuse a response it already holds.
There are two kinds of cache to keep apart:
- A private cache belongs to one user. The browser's own HTTP cache is the main example.
- A shared cache serves many users. CDNs and corporate proxies are examples.
The server controls both through response headers. The browser's decision has three possible outcomes for a request:
- Fresh hit. The stored response is still within its freshness lifetime. The browser uses it with no network traffic.
- Stale, revalidated. The stored response is too old. The browser asks the server whether it is still valid. If it is, the server replies with a short
304 Not Modifiedand no body. - Miss. Nothing usable is stored, or the stored copy is no longer valid. The browser performs a full request and stores the new response if allowed.
Freshness: Cache-Control and Expires
The response from the earlier chapter included this header:
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Cache-Control: max-age=3600
Content-Length: 1256Cache-Control: max-age=3600 says the response is fresh for 3600 seconds (one hour) after it was generated. During that hour a repeat request for the same URL can be answered from cache without contacting the server.
The age of a stored response is measured from when it was generated, not from when you received it. If a CDN held the response for 20 minutes before passing it to you, the Age: 1200 header tells you so, and only 40 minutes of freshness remain.
The most useful Cache-Control response directives are:
| Directive | Meaning |
|---|---|
| `max-age=N` | Fresh for N seconds. |
| `s-maxage=N` | Like `max-age`, but applies only to shared caches. |
| `no-cache` | May be stored, but must be revalidated before every reuse. |
| `no-store` | Do not store the response at all. |
| `public` | Any cache may store it, even if the request carried credentials. |
| `private` | Only a private cache (the browser) may store it. |
| `must-revalidate` | Once stale, do not reuse without successful revalidation. |
| `immutable` | The body will never change during its freshness lifetime, so skip revalidation on reload. |
The names no-cache and no-store are the most commonly confused. no-cache does not mean "do not cache." It means "cache, but check first." Use no-store for sensitive responses such as account pages that must not remain on disk.
An older header, Expires, gives an absolute date instead of a duration. If Cache-Control: max-age is present, it takes precedence and Expires is ignored.
Heuristic freshness
If a response has no explicit freshness information but has a Last-Modified header, caches are allowed to guess a lifetime. A common rule is 10% of the time since the last modification. A page last changed 100 days ago might be reused for 10 days with no revalidation. This surprises people who forgot to set headers, so set Cache-Control explicitly on anything you serve.
Validation: ETag and Last-Modified
When a response goes stale, the browser does not have to download it again. If the original response carried a validator, the browser sends it back and asks "has this changed?"
Two validators exist:
ETagis an opaque identifier for a specific version of the resource, often a hash of the content.Last-Modifiedis a timestamp.
A response that supports validation looks like this:
HTTP/1.1 200 OK
Content-Type: text/css
Cache-Control: max-age=60
ETag: "a3f9c2"
Last-Modified: Tue, 24 Nov 2026 10:00:00 GMTAfter 60 seconds the entry is stale. The next request becomes conditional:
GET /style.css HTTP/1.1
Host: example.com
If-None-Match: "a3f9c2"
If-Modified-Since: Tue, 24 Nov 2026 10:00:00 GMTIf the resource is unchanged, the server answers with no body:
HTTP/1.1 304 Not Modified
ETag: "a3f9c2"
Cache-Control: max-age=60The browser keeps its stored body, resets the freshness clock using the new headers, and hands the stored body to the page. You still pay one round trip, but you skip the transfer of the body. If the file changed, the server returns a normal 200 OK with the new body and new validators.
ETag is generally more reliable than Last-Modified. Timestamps have one-second resolution, and they change when a file is redeployed even if its content is identical. When both validators are present, If-None-Match takes priority.
The Vary header
A cache stores responses by URL, but the same URL can produce different responses depending on request headers. A server that returns compressed content when the client sends Accept-Encoding: gzip and plain text otherwise must say so:
HTTP/1.1 200 OK
Content-Encoding: gzip
Vary: Accept-Encoding
Cache-Control: max-age=600Vary: Accept-Encoding tells the cache to treat the request's Accept-Encoding value as part of the cache key. A stored gzip response is only reused for requests with a matching value. Omitting Vary when content differs by language, encoding, or a cookie can cause one user to receive another user's variant from a shared cache. Vary: * effectively disables reuse.
Cache busting with versioned URLs
You cannot recall a response that a browser has stored under a long max-age. The standard solution is to put a version or content hash in the URL, so a change produces a new URL and therefore a cache miss:
<link rel="stylesheet" href="/assets/style.3fa91c.css">
<script src="/assets/app.b72e04.js" defer></script>Those assets can be served with a very long lifetime:
Cache-Control: public, max-age=31536000, immutableThe HTML document that references them is served with a short lifetime or no-cache, so a new deploy reaches users quickly and points them at the new asset URLs. This split is the most common production strategy: short-lived HTML, long-lived fingerprinted subresources.
How reload and navigation change behaviour
The way you trigger a request affects how the cache is used.
| Action | Cache behaviour |
|---|---|
| Typing a URL and pressing Enter, or following a link | Normal. Fresh entries are used without a request. |
| Back and forward buttons | Browsers often reuse stored entries even if stale, to restore the page quickly. |
| Normal reload | The main document is revalidated. Subresources follow normal rules in most browsers. |
| Hard reload (Ctrl+Shift+R or Cmd+Shift+R) | The cache is bypassed and requests are sent unconditionally. |
This explains why a page can look different after a hard reload than after pressing Enter.
Related caches
HTTP caching is one of several layers that can answer before the network. The earlier chapter on local state described the DNS cache and HSTS list. The browser may also use a memory cache for resources already loaded by the current page, and a service worker can intercept requests and answer from its own storage. When you debug an unexpected stale response, check each layer in turn.
Observing caching
Use curl to see the headers a server sends, without downloading the body:
curl -sI https://example.com/ | grep -i -E 'cache-control|etag|last-modified|age|vary|expires'To test revalidation, send a validator yourself. Replace the ETag value with one from the previous command:
curl -sI https://example.com/ -H 'If-None-Match: "a3f9c2"'A 304 status line means the validator matched. In the browser's Network panel, a response served from the HTTP cache shows (disk cache) or (memory cache) in the Size column and almost no timing, while a revalidated response shows a status of 304. Disabling the cache option in the panel makes the browser skip the cache while DevTools is open, which is useful for testing but changes the behaviour you are trying to observe.
You can also check the timing from script. A cache hit typically shows near-zero values for DNS, connect and response time:
const [nav] = performance.getEntriesByType('navigation');
console.log('DNS ms:', nav.domainLookupEnd - nav.domainLookupStart);
console.log('Connect ms:', nav.connectEnd - nav.connectStart);
console.log('TTFB ms:', nav.responseStart - nav.requestStart);
console.log('Transfer size:', nav.transferSize);A transferSize of 0 generally indicates the response came from cache. A small non-zero value with a 304 indicates only headers were transferred.
Common errors
- Using
no-cachewhen you meanno-store. Sensitive data remains stored and is only revalidated. - No
Cache-Controlat all. Browsers fall back to heuristic freshness, producing unpredictable staleness. - Long
max-ageon an unversioned URL. Users keep the old file until the lifetime ends, and you cannot force them to refresh. - Missing
Vary. A shared cache serves the wrong variant. - Caching
privatecontent aspublic. A CDN may serve one user's page to another. - Caching error responses with long lifetimes. A temporary
500or an unintended301can persist. Permanent redirects are cacheable by default and are especially hard to undo.
Exercise
A stylesheet at /site.css is served with "Cache-Control: max-age=300" and 'ETag: "v7"'. A user loads a page that uses it, and returns 10 minutes later. The file has not changed. What request does the browser send, what does the server reply, and what is transferred over the network?
Show answer
The 300-second lifetime has expired, so the entry is stale. The browser sends a conditional GET with "If-None-Match: "v7"". Because the file is unchanged, the server replies "304 Not Modified" with headers only. The browser reuses its stored body and resets the freshness clock. Only the request and response headers cross the network, not the stylesheet body.
Exercise
Your build tool produces app.js and you deploy a new version daily. You want returning visitors to avoid downloading unchanged files but to pick up new releases immediately. What headers and URL scheme would you use for the HTML page and for the script?
Show answer
Put a content hash in the script file name (for example app.b72e04.js) and serve it with "Cache-Control: public, max-age=31536000, immutable". Serve the HTML with a short max-age or "no-cache" plus an ETag, so browsers revalidate it on each visit. When app.js changes, the HTML references a new file name, which is a cache miss and is downloaded. Unchanged files keep the same name and stay cached.