Sub topic 14
HTTP caching and validation
HTTP caching lets browsers, CDNs, and proxies reuse responses without asking your application again. This chapter assumes you know the cache-aside pattern, TTL expiration, and basic client-server requests. The goal is to read and set the headers that control freshness and revalidation.
Freshness and validation
An HTTP cache answers two questions for every stored response.
- Is the response still fresh? A fresh response is served directly, with no network request to the origin.
- If it is stale, is it still correct? A stale response can be revalidated: the cache asks the origin whether the content changed. If it did not, the origin sends a short answer and the cache reuses its copy.
Freshness is HTTP's version of TTL expiration. Validation is the part with no equivalent in a simple key-value cache. An expired entry in your application cache is thrown away and rebuilt. An expired HTTP entry can be kept and confirmed cheaply.
Cache-Control directives
The Cache-Control response header carries the rules. The directives you will use most:
| Directive | Meaning |
|---|---|
| `max-age=N` | The response is fresh for N seconds after it was generated. |
| `s-maxage=N` | Same as `max-age`, but only for shared caches such as CDNs. It overrides `max-age` there. |
| `public` | Any cache may store the response, even if the request carried credentials. |
| `private` | Only the end user's browser cache may store it. Shared caches must not. |
| `no-cache` | The response may be stored, but it must be revalidated before every reuse. |
| `no-store` | Do not store the response anywhere. |
| `must-revalidate` | After it goes stale, do not serve it without successful revalidation. |
| `immutable` | The content will never change while fresh, so skip revalidation even on reload. |
| `stale-while-revalidate=N` | A stale response may be served for N more seconds while a refresh runs in the background. |
no-cache is a common source of confusion. It does not mean "do not cache". It means "cache, but check first". Use no-store when the data must never be written to disk or a shared cache, such as account pages with sensitive data.
Separate headers by audience. Personalized responses should be private. Static assets shared by everyone can be public.
Validators: ETag and Last-Modified
Revalidation needs a validator, a value that identifies a version of the resource.
ETagis an opaque version identifier, such as a content hash or a version number. It is the more precise option.Last-Modifiedis a timestamp with one-second resolution. It is easier to produce but coarser.
The client stores the validator with the response. When the entry goes stale, it sends the validator back in a conditional request:
If-None-Match: "v42"for an ETagIf-Modified-Since: <date>forLast-Modified
If the validator still matches, the server replies 304 Not Modified with no body. The cache refreshes its freshness timer and serves the stored body. If the resource changed, the server replies 200 with the new body and a new validator.
Here is the exchange from this chapter's example.
HTTP/1.1 200 OK
Cache-Control: public, max-age=3600
ETag: "v42"
--- later, after the entry is stale, the client revalidates ---
GET /report HTTP/1.1
If-None-Match: "v42"
HTTP/1.1 304 Not ModifiedThe first response lets clients reuse the resource for an hour. After that, the conditional request saves the cost of resending the body, though it still costs one round trip.
If both validators are present, If-None-Match takes precedence over If-Modified-Since.
Strong and weak ETags
A strong ETag such as "v42" means the bytes are identical. A weak ETag such as W/"v42" means the content is semantically the same, though the bytes may differ. Weak validators are fine for conditional GETs. Byte-range requests need strong ones. Compression often turns a strong ETag into a weak one, because the same resource is served in different encodings.
The request flow
The diagram shows what a cache does when it receives a request.
Implementing validation on a server
This stdlib-only server computes an ETag from the body and answers conditional requests. It is a minimal sketch. It compares If-None-Match as a single exact value, while real servers must also handle comma-separated lists, *, and weak comparison.
import hashlib
from http.server import BaseHTTPRequestHandler, HTTPServer
BODY = b'{"total": 42}'
ETAG = '"' + hashlib.sha256(BODY).hexdigest()[:16] + '"'
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
if self.headers.get("If-None-Match") == ETAG:
self.send_response(304)
self.send_header("ETag", ETAG)
self.send_header("Cache-Control", "public, max-age=60")
self.end_headers()
return
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(BODY)))
self.send_header("ETag", ETAG)
self.send_header("Cache-Control", "public, max-age=60")
self.end_headers()
self.wfile.write(BODY)
if __name__ == "__main__":
HTTPServer(("127.0.0.1", 8000), Handler).serve_forever()Test it with curl -i http://127.0.0.1:8000/, then repeat with -H 'If-None-Match: <the ETag you received>'. The second call returns 304 with no body.
Note that the 304 repeats ETag and Cache-Control. A 304 should carry the headers that would have appeared on the 200, so the cache can update its stored metadata.
A validator does not have to save work at the origin. If computing the ETag means rebuilding the whole response, you save only bandwidth. To save CPU and database time, derive the ETag from something cheap, such as a row version or an updated_at column.
Vary and cache keys
A cache key for HTTP is normally the method plus the URL. If the response depends on a request header, the origin must say so with Vary. For example, Vary: Accept-Encoding tells caches to store separate copies for gzip and brotli clients.
Two pitfalls:
Vary: CookieorVary: User-Agentfragments the cache into near-unique entries and drops the hit ratio. This is the key-design problem from earlier, in HTTP form.- Forgetting
Varymakes a cache serve a response in the wrong language or encoding to the next client.
Common mistakes
- Long max-age on a URL that changes. You cannot recall a response from browsers once it is served as fresh. For assets, put a content hash in the filename (
app.3f9a1c.js) and sendmax-age=31536000, immutable. A new deploy gets a new URL. - No explicit freshness. If a response has
Last-Modifiedbut nomax-age, caches may apply a heuristic, commonly around 10% of the time since the last modification. Behavior then varies between caches. Always state your intent. - Caching personalized responses as public. A shared cache can serve one user's data to another. Use
private, orno-storefor sensitive data. - Expecting
no-cacheto prevent storage. It does not. Useno-store. - Reload behavior. Browsers often revalidate on a normal reload and bypass caches on a hard reload. Test with fresh navigation, not only reload.
Exercise
A JSON endpoint returns Cache-Control: public, max-age=300 and ETag: "a1". A browser fetched it 10 minutes ago. The data has not changed. What does the browser send on the next request, what does the server reply, and what is saved compared with a plain 200?
Show answer
The stored copy is stale (600 s is past the 300 s lifetime), so the browser sends a conditional GET with If-None-Match: "a1". The server sees the ETag still matches and replies 304 Not Modified with no body. The browser resets the freshness timer and serves its stored body. The saving is the response body transfer, and possibly the server's work to build it if the ETag was cheap to compute. The round trip still happens.
Exercise
Which header would you set for a fingerprinted file app.3f9a1c.js, and which for a page showing a logged-in user's account balance?
Show answer
For the fingerprinted file: Cache-Control: public, max-age=31536000, immutable, since a change produces a new URL. For the account page: Cache-Control: private, no-store, or at least private, no-cache, so a shared cache never stores or reuses one user's data for another.