Sub topic 11
Cache-Control, ETag, and Last-Modified
This chapter covers how HTTP caching headers decide how long a changed price or date stays invisible to visitors and crawlers. It assumes you know basic HTML, how a page is served over HTTP, and how to read JSON. The next chapter covers purging caches and CDNs after a change.
Why caching headers belong in a freshness plan
You can store each fact once and render it everywhere, and the page can still show an old price. A browser, a corporate proxy, or a CDN may hold a copy of the page and answer for your server. That copy is correct until the fact changes, and wrong afterward.
Caching is not the enemy. It makes pages fast and protects your origin server from load. The goal is to choose a deliberate maximum age for each kind of page. That age is the longest time a stale fact can survive without any action from you.
The working model
A cache stores a response and decides, on each later request, among three outcomes:
- Fresh hit. The stored copy is still within its allowed age. The cache answers without contacting your server.
- Revalidation. The copy is too old. The cache asks your server whether it is still current. If it is, the server answers with a tiny "not modified" reply and the cache reuses the body.
- Miss. There is no usable copy, or the server says the content changed. The server sends the full response.
Freshness is controlled by Cache-Control. Revalidation is controlled by validators: ETag and Last-Modified.
Cache-Control
The Cache-Control response header holds directives separated by commas. These are the ones you will use most.
| Directive | Meaning |
|---|---|
| `max-age=N` | Any cache may reuse the response for N seconds without asking the origin. |
| `s-maxage=N` | Like `max-age`, but only for shared caches such as CDNs. It overrides `max-age` there. |
| `public` | Shared caches may store the response, even in cases where they normally would not. |
| `private` | Only the visitor's own browser may store it. Use this for personalized pages. |
| `no-cache` | A cache may store the response but must revalidate before every reuse. |
| `no-store` | Do not store the response anywhere. |
| `must-revalidate` | Once stale, a cache must not serve the copy without successful revalidation. |
| `stale-while-revalidate=N` | For N seconds after expiry, a cache may serve the stale copy while it refreshes in the background. |
Two names cause frequent mistakes. no-cache does not mean "do not cache". It means "cache, but check first". no-store is the directive that prevents storage.
A concrete policy
Here is a response for a product page, based on the header example in this tutorial's plan:
HTTP/1.1 200 OK
Cache-Control: public, max-age=300, stale-while-revalidate=60
ETag: "v42"
Last-Modified: Fri, 20 Nov 2026 08:00:00 GMT
Content-Type: text/html; charset=utf-8Read it line by line:
max-age=300lets a cache reuse the page for five minutes with no contact with your server.stale-while-revalidate=60lets a cache serve an expired copy for up to one more minute while it fetches a fresh one. The visitor gets speed. The cost is a small extra window of staleness.- The worst case for a price change is therefore about 360 seconds, six minutes, assuming every cache between you and the visitor honors the directives.
That sum is the number to write down. Ask the business how long a wrong price may be shown, then choose max-age and stale-while-revalidate so their total stays below it.
Choosing values by fact type
Match the age to how quickly the fact decays and how costly an error is.
| Page type | Suggested policy | Reason |
|---|---|---|
| Product page with price and stock | `public, max-age=300, stale-while-revalidate=60` | A wrong price creates complaints and possible legal exposure. |
| Article or guide | `public, max-age=3600` to `86400` | Edits are rare and low risk. |
| Static assets with hashed names | `public, max-age=31536000, immutable` | The file name changes when content changes. |
| Cart, checkout, account | `private, no-store` | Content is personal and must not be shared. |
Validators: ETag and Last-Modified
Validators let a stale cache ask a cheap question instead of downloading the page again.
ETag
An ETag is an opaque identifier for one version of a response. The server picks it. The cache stores it, and on revalidation sends it back in If-None-Match:
GET /p/trail-runner-2 HTTP/1.1
Host: example.com
If-None-Match: "v42"If the current version is still "v42", the server replies:
HTTP/1.1 304 Not Modified
ETag: "v42"
Cache-Control: public, max-age=300, stale-while-revalidate=60There is no body. The cache reuses its copy and restarts the freshness clock. If the price changed and the ETag is now "v43", the server sends a normal 200 OK with the full new body.
Good ETags change when the rendered output changes, and only then. You can derive one from a hash of the response body, or from a version number stored with the product record. This ties caching back to the single source of truth: when the record changes, its version changes, and so does the ETag.
Last-Modified
Last-Modified is a timestamp in HTTP date format. The cache returns it in If-Modified-Since. If nothing changed after that time, the server answers 304.
Last-Modified has one-second resolution and depends on trustworthy clocks. ETag is more precise. When both are present, caches prefer ETag. Sending both is normal.
Generating validators from one record
This Python sketch derives both validators from a product record and answers a conditional request. It uses only the standard library.
import hashlib
from datetime import datetime, timezone
from email.utils import format_datetime, parsedate_to_datetime
def validators(product, body):
etag = '"' + hashlib.sha256(body.encode('utf-8')).hexdigest()[:16] + '"'
modified = product['modified_at']
last_modified = format_datetime(modified, usegmt=True)
return etag, last_modified
def respond(product, body, if_none_match=None, if_modified_since=None):
etag, last_modified = validators(product, body)
headers = {
'Cache-Control': 'public, max-age=300, stale-while-revalidate=60',
'ETag': etag,
'Last-Modified': last_modified,
}
if if_none_match is not None:
not_modified = if_none_match == etag
elif if_modified_since is not None:
since = parsedate_to_datetime(if_modified_since)
not_modified = product['modified_at'] <= since
else:
not_modified = False
if not_modified:
return 304, headers, ''
return 200, headers, body
product = {'modified_at': datetime(2026, 11, 20, 8, 0, tzinfo=timezone.utc)}
body = '<html><body>Trail Runner 2: 89.00 EUR</body></html>'
status, headers, _ = respond(product, body)
print(status, headers['ETag'])
status, _, _ = respond(product, body, if_none_match=headers['ETag'])
print(status)
status, _, _ = respond(product, body.replace('89.00', '79.00'), if_none_match=headers['ETag'])
print(status)The output is 200 with an ETag, then 304, then 200 again after the price text changes. The code follows the rule that If-None-Match takes precedence over If-Modified-Since when both arrive.
Common errors
- Hashing volatile content. If the body contains a timestamp, a nonce, or a rotating banner, the ETag changes on every request. Revalidation never returns
304, and you lose the savings. Hash only stable content, or derive the ETag from the record version. - Different ETags per server. Some servers build ETags from file inode numbers. Behind a load balancer, two servers then return different tags for identical content. Use a content hash.
- Fake Last-Modified. Sending the current time on every response, or a date unrelated to the content, misleads caches and crawlers. Use the real modification time of the underlying record. This matches the rule from the earlier chapters on dates: signal changes honestly.
- Long
max-ageon pages with prices. An hour-long age on a product page means an hour of wrong prices after every change. Keep the age short, or purge on change. - Missing
Vary. If the response differs by language or currency, addVary: Accept-Languageor key the cache another way. Otherwise a cache may show a euro price to a visitor who should see dollars. - Caching personalized pages publicly. A
publicpage with a user's name in it can be served to someone else. Useprivate. - Mismatch with JSON-LD. The page body includes the markup, so a cached copy carries the old structured data as well. The markup and the visible price stay in agreement, but both are equally old.
Crawlers and conditional requests
Search crawlers often send If-None-Match or If-Modified-Since. A correct 304 saves them bandwidth and lets them spend crawl time on pages that changed. A server that ignores conditional requests still works, but the crawler downloads everything each time.
Validators also affect trust. If your Last-Modified header says 2020 for a page that shows a 2026 price, the signals disagree. Treat Last-Modified, the dateModified value in JSON-LD, and the sitemap lastmod as three views of one fact, generated from the same record.
Verifying your headers
Check what a client actually receives, not what you configured. Use curl:
curl -sI https://example.com/p/trail-runner-2
curl -sI -H 'If-None-Match: "v42"' https://example.com/p/trail-runner-2The first command shows the response headers. The second should return HTTP/1.1 304 Not Modified if the tag is current. Also look for CDN headers such as Age and X-Cache. Age tells you how many seconds the copy has sat in a shared cache, which helps you confirm that the policy you chose is the one in effect.
Summary of decisions
- Decide the longest acceptable lifetime of a wrong fact for each page type.
- Set
max-ageplusstale-while-revalidateto fit inside it. - Generate
ETagandLast-Modifiedfrom the same record that feeds the page, markup, and sitemap. - Use
private, no-storefor anything personal. - Test the headers on the live URL.
Exercise
A product page sends Cache-Control: public, max-age=600, stale-while-revalidate=120. The price changes at 10:00 and no cache is purged. What is the longest time, after 10:00, that a visitor could still see the old price? Then name one change that would cut it to under three minutes.
Show answer
The worst case is 600 + 120 = 720 seconds, so 12 minutes: a cache that stored the page just before 10:00 stays fresh for 10 minutes and may serve the stale copy for 2 more while it refreshes. Setting max-age=120, stale-while-revalidate=30 would give a worst case of 150 seconds, 2.5 minutes. Purging the cache when the price changes would also cut it.
Exercise
Your ETag is a hash of the full HTML body. The body includes a "Generated at" timestamp in the footer. Every request gets a new ETag. What goes wrong, and how do you fix it?
Show answer
Revalidation never matches, so caches and crawlers always get a full 200 instead of 304, and you lose the bandwidth savings. Fix it by removing the timestamp from the hashed content, or by building the ETag from the product record's version number or modification time instead of the rendered body.