Sub topic 13
Caching and conditional requests
This chapter assumes you can read an HTTP request and response, know what status codes and headers are, and have used curl -v. It covers how a browser decides whether to reuse a stored response, how it checks whether that response is still valid, and which mistakes make caches misbehave.
Why caching exists
Every request costs time and bandwidth. A cache is a store of earlier responses that can answer a later request without repeating the full exchange. HTTP caching rests on two ideas:
- Freshness. The server says how long a stored response may be reused without asking again.
- Validation. When the stored response is no longer fresh, the client asks the server whether it has changed. If it hasn't, the server answers with a short message instead of the whole body.
Freshness with Cache-Control
The Cache-Control response header carries caching instructions. The most common one is max-age, the number of seconds the response counts as fresh.
HTTP/1.1 200 OK
Cache-Control: max-age=3600
ETag: "v1"
Content-Type: image/pngFor the next 3600 seconds, the browser serves /logo.png from its cache. It sends no request at all, so the network panel in DevTools shows the entry as served from disk or memory cache. After that, the response is stale. Stale does not mean deleted. The browser keeps the copy and tries to validate it.
Validation with ETag and If-None-Match
An ETag is an opaque identifier for one version of a resource. Servers often derive it from a hash of the content or from a version number. When the browser revalidates, it sends the stored value back in If-None-Match:
GET /logo.png HTTP/1.1
Host: example.com
If-None-Match: "v1"If the resource still matches, the server replies with no body:
HTTP/1.1 304 Not Modified
ETag: "v1"The 304 status means the stored copy is still valid. The browser reuses it and treats it as fresh again. If the resource has changed, the server sends a normal 200 with the new body and a new ETag. A request that carries a validator like If-None-Match is called a conditional request.
The older equivalent is Last-Modified in the response and If-Modified-Since in the next request. It works the same way but compares timestamps, which have one-second resolution. Prefer ETag when you can produce one.
The following diagram shows the decision a browser makes for each cacheable request.
A server that supports validation
This Node.js server computes an ETag from its body and answers conditional requests with 304. It compares only one exact value. Real servers must also handle a list of ETags, the * value, and weak validators such as W/"abc".
import { createServer } from "node:http";
import { createHash } from "node:crypto";
const body = "<h1>Hello</h1>";
const hash = createHash("sha256").update(body).digest("hex").slice(0, 16);
const etag = `"${hash}"`;
const server = createServer((req, res) => {
if (req.headers["if-none-match"] === etag) {
res.writeHead(304, { ETag: etag, "Cache-Control": "no-cache" });
res.end();
return;
}
res.writeHead(200, {
"Content-Type": "text/html; charset=utf-8",
"Content-Length": Buffer.byteLength(body),
ETag: etag,
"Cache-Control": "no-cache",
});
res.end(body);
});
server.listen(3000);Run it, then test with curl. The first request returns the body and an ETag. The second sends that value back and should receive a 304:
curl -i http://localhost:3000/
curl -i -H 'If-None-Match: "REPLACE_WITH_ETAG"' http://localhost:3000/Copy the exact ETag value, including its quotes, from the first response.
Common Cache-Control directives
| Directive | Meaning |
|---|---|
| `max-age=N` | The response is fresh for N seconds. |
| `no-cache` | A cache may store the response but must validate it before every reuse. |
| `no-store` | Do not store the response at all. Use it for sensitive data. |
| `private` | Only the user's own browser may store it, not shared caches. |
| `public` | Shared caches such as CDNs may store it. |
| `s-maxage=N` | Like `max-age`, but applies only to shared caches. |
| `immutable` | The content will never change during its freshness lifetime, so skip revalidation on reload. |
Private and shared caches
A browser cache belongs to one user. A shared cache, such as a proxy or CDN, serves many users. If a response contains per-user data, such as an account page, mark it private or no-store. Otherwise a shared cache could hand one user's page to another. The later chapter on proxies and CDNs returns to this.
Strategy: versioned URLs for assets, validation for pages
Two patterns cover most sites.
- Static assets with versioned names. Build tools produce files such as
app.3f9c1a.js, where the hash changes when the content changes. Serve them withCache-Control: public, max-age=31536000, immutable. The URL changes on every release, so a long lifetime is safe. - HTML documents with validation. The page must pick up new asset names right away, so serve it with
Cache-Control: no-cacheand anETag. Each load costs a small round trip, but a304is cheap.
Gotchas and failure modes
- Long max-age on a URL that changes in place. If
/style.csshasmax-age=31536000and you edit the file, returning visitors keep the old version for up to a year. The server cannot recall the copy. The fix is to change the URL. - Heuristic freshness. If a response has
Last-Modifiedbut noCache-ControlorExpires, caches may guess a lifetime, commonly a fraction of the time since modification. State your policy explicitly. - Missing Vary. If a response differs by request header, for example
Accept-EncodingorAccept-Language, the server must sendVarynaming that header. Without it, a cache can return a compressed or wrong-language body to a client that cannot use it. - Caching error responses. A cached
500or a wrongly cached redirect can persist longer than the problem. Check which status codes your CDN caches and for how long. - Reload behavior. A normal reload makes the browser revalidate the main resource. A hard reload bypasses the cache. Testing with a normal navigation, not a reload, shows what real visitors experience.
- Validators that never match. If a load-balanced server farm generates ETags from file inode numbers or modification times, each machine can produce a different value. Clients then never get a
304. Derive ETags from content.
Inspecting caching in practice
Use curl -I to see only the response headers:
curl -sI https://example.com/Look for Cache-Control, ETag, Last-Modified, Vary, and Age. A non-zero Age header means a shared cache served the response and tells you how long it has been stored. In the browser's DevTools Network panel, a size column that reads "disk cache" or "memory cache" means no request was sent. A 304 status means a conditional request succeeded. The "Disable cache" checkbox, active while DevTools is open, turns caching off and can hide the problems you are trying to reproduce.
Exercise
A page is served with Cache-Control: max-age=600 and ETag: "a1". A visitor loads it, then returns 15 minutes later. Describe what the browser sends and what happens if the page has not changed. What would be different if the header were Cache-Control: no-store?
Show answer
After 15 minutes the stored copy is stale because 600 seconds have passed. The browser sends a conditional GET with If-None-Match: "a1". The server replies 304 Not Modified with no body, and the browser reuses its stored copy and treats it as fresh for another 600 seconds. With no-store, the browser never keeps the response, so every visit sends a normal request and downloads the full body.