ETag, 304 and Cache-Control
An ETag is a version of a resource: the client sends it in If-None-Match, and if nothing changed the server answers 304 Not Modified without a body. Cache-Control manages caching: max-age sets freshness, no-cache allows storing but requires revalidation, no-store forbids storing, and private excludes shared caches. A cache is tested with a sequence of requests, and personal data gets no-store or private.
API · Cache
One user's balance suddenly shows up for another. Which header allowed it?
A user opens "My accounts" and sees someone else's balance. The database and the authorisation code are fine: the response with personal data had Cache-Control: public, max-age=300, and a CDN served it to the next requester. A single-request test does not show this, because the defect appears only when a cache sits between the client and the server.
This lesson covers how conditional requests with ETag work, what the Cache-Control directives mean, and what to check so you miss neither an unwanted cache nor broken validation.
How it is built
Caching (RFC 9111) solves two problems: not downloading the same thing again, and not serving stale data. There are two mechanisms. Freshness: Cache-Control: max-age=60 says a cache may serve the response for 60 seconds without asking the server. Validation: when freshness runs out, the client asks the server "is my version still current?". The version is marked by the ETag validator, and the question is the If-None-Match header. If nothing changed, the server answers 304 Not Modified with no body, and the client uses what it stored. If it changed, it is an ordinary 200 with a new body and a new ETag.
A conditional request with ETag
The same ETag works the other way, as protection against lost updates. The client reads a resource together with ETag: "v7", edits it and sends PUT with If-Match: "v7". If someone changed the resource meanwhile, the version is different now, and the server answers 412 Precondition Failed instead of silently overwriting someone else's edit. Some APIs require If-Match and answer 428 Precondition Required when it is missing.
Cache-Control: what each directive means
max-age=60: the response is fresh for 60 seconds, during which a cache does not ask the server.no-cache: it may be stored, but must be validated before every use (viaETagor a date). The name is misleading: there is plenty of cache here.no-store: do not store the response anywhere, neither in the browser nor in intermediate caches.private: may be stored only in a single user's cache (the browser), not in shared ones (CDN, proxy).public: shared caches may store it too.must-revalidate: a stale response must not be served without validation, even if the server is unreachable.
no-cache and no-store
no-cache
The response is stored, but a cache asks the server before every use. Fits data that changes but is not secret.
no-store
Nothing is stored. Fits balances, tokens and personal data, where a copy on disk is already a problem.
Example: from "it works" to checking caching and versions
Before: the test makes one GET /accounts/42 and looks at the body. Below is a manual validation check with curl (lines starting with # are the expected result, not output):
curl -i "$BASE/v1/accounts/42" -H "Authorization: Bearer $TOKEN"
# HTTP/1.1 200 OK
# ETag: "v7"
# Cache-Control: private, no-cache
curl -i "$BASE/v1/accounts/42" -H "Authorization: Bearer $TOKEN" \
-H 'If-None-Match: "v7"'
# HTTP/1.1 304 Not Modified (no body, ETag: "v7" again)
A second request with no body and status 304 means validation works. Next we move this into an automated test that also checks the other side: an old ETag after a change does not give 304, and a stale If-Match gives 412.
test('ETag changes after an update, a stale If-Match gives 412', async ({ request }) => {
const first = await request.get('/v1/accounts/42');
const etag = first.headers()['etag'];
expect(etag).toBeTruthy();
const same = await request.get('/v1/accounts/42', {
headers: { 'If-None-Match': etag },
});
expect(same.status()).toBe(304);
expect(await same.text()).toBe('');
const upd = await request.patch('/v1/accounts/42', {
data: { nickname: 'main' },
headers: { 'If-Match': etag },
});
expect(upd.ok()).toBeTruthy();
expect((await request.get('/v1/accounts/42')).headers()['etag']).not.toBe(etag);
const stale = await request.patch('/v1/accounts/42', {
data: { nickname: 'other' },
headers: { 'If-Match': etag }, // the old version
});
expect(stale.status()).toBe(412);
});
Four different defects are covered by one scenario: the server does not return ETag, returns 304 with a body, does not change ETag after an update, or lets someone else's edit be overwritten. The first request stores the version, the second proves that 304 is empty, the third and fourth look at behaviour after the change.
Responses with personal data are checked separately:
test('private data is not stored by shared caches', async ({ request }) => {
const res = await request.get('/v1/accounts/42/balance');
const cc = res.headers()['cache-control'] ?? '';
expect(cc).toMatch(/no-store|private/);
expect(cc).not.toMatch(/public/);
});
This is a cheap test for a catastrophic defect: a balance or profile response in a shared cache. If there are no directives at all, a cache may apply a heuristic based on Last-Modified and store the response on its own, so a missing Cache-Control on a personal response is also worth a remark. A shared cache will not store a response to a request with Authorization without public, s-maxage or must-revalidate, but it will store one authenticated by a cookie.
One more request pair is useful for a manual check: 412 shows that resource versioning is actually enforced.
PUT /v1/accounts/42 HTTP/1.1
If-Match: "v7"
Content-Type: application/json
{ "nickname": "main" }
HTTP/1.1 412 Precondition Failed
Limits and alternatives
- A weak validator
W/"v7"means "semantically the same", not byte for byte. That is enough forIf-None-Match, whileIf-Match(a write) needs a strong one. - Instead of
ETagthere is theLast-Modified/If-Modified-Sincepair: second precision, so it may miss quick changes.ETagis more reliable. - Playwright
requestcaches nothing itself, so this test cannot verify the browser cache or the CDN cache. It checks only the headers the server returned. Cache behaviour is observed in the browser Network tab (the Size column shows "disk cache", the Status column shows 304) and on the cache that sits in front of the test environment. - Static files with a hash in the name (
app.3f9a.js) getmax-ageof a year andimmutable. A JSON API must not do this. ETagwithIf-Matchis not the only way to version: some APIs put the version in the body ("version": 7) and compare it themselves. Then 409 is returned instead of 412, which also has to be matched against the contract.
Common mistakes
- Confusing
no-cacheandno-store. A developer putsno-cacheon a balance and thinks there is no caching. A copy is stored, and on a shared cache that is a leak. - Testing the cache with one request. The defect shows only in a sequence: the first request, a repeat with a validator, a request after a change.
- Expecting 304 with a body. A 304 response has no body. A body in it means a defect, or a proxy that "added" something.
- Not changing the ETag after an update. The client then sees 304 forever and never gets new data. It is a silent bug visible only on a repeat request.
- Putting
publicon authorised responses. A shared cache does not know the response depends on the token and serves it to everyone.
Check yourself
The client sends If-None-Match: "v7" and the server answers 200 with the same ETag: "v7" and a full body. What does it mean?
Answer
The server does not support conditional requests: it should answer 304 with no body because the version did not change. The data is functionally right, but there is extra traffic. It is a remark about performance, not correctness.
The response to GET /accounts/42/balance has Cache-Control: no-cache. Is that enough?
Answer
No, if the balance must not be stored. no-cache allows a copy to be stored and only requires validation before use. For personal data expect no-store or at least private, so a shared cache does not hold someone else's data.
ETag is a resource version. The client sends it in If-None-Match, and if nothing changed the server answers 304 with no body. no-cache means "validate before use", no-store means "do not store". Middle/Senior: I test caching with a sequence of requests: the first, a repeat with a validator (I expect an empty 304), a request after a change (a new ETag, and the old one gets 200). I check a stale version in If-Match for 412, which protects against lost updates. For personal and financial data I expect no-store or private, because public lets a shared cache store a response even to a request with Authorization, which ends in someone else's balance leaking.