HTTP Caching Headers Without the Guesswork

HTTP Caching Headers Without the Guesswork

About Cache-Control we were mostly guessing, to be honest, so we wrote a small server which counts every knock on his door, and asked Chrome to fetch one address two times in a row, each time with another header.

max-age=60, second knock never happened, browser answered from his pocket. no-cache with ETag, he knocked, got 304, so it is saving the file, whatever the name says, only asks permission each time, and max-age=0 with must-revalidate did exactly same dance, 200 and 304. no-store we gave also with ETag and still two times full 200, he keeps nothing.

/pricing/
Cache-Control: no-cache
GET /pricing/
If-None-Match: "a41f-6b2"

HTTP/2 304

Now the nasty one. We removed Cache-Control completely and sent only Last-Modified with date ten days back, fetched, fetched again, and the server counted one. One! Chrome decided by his own head that file is probably fresh, the name for this is heuristic caching, and imagine you deploy, and some visitor is still looking on last week, and in your headers there is nothing which says cache me. Without any of these headers it knocked both times.

curl -sI https://example.com/ | grep -i -E 'cache-control|etag|age|cf-cache-status'

And stale-while-revalidate with stopwatch, our server sleeps 300 ms here, first time 305 ms, we wait until expired, second time 2 ms but the old text, third time 6 ms and new text, somebody always eats the old one, nobody waits.

/assets/app-9f2c1b7a.js
Cache-Control: public, max-age=31536000, immutable
Cache-Control: public, max-age=0, s-maxage=600, stale-while-revalidate=60

See also: web performance basics and srcset and sizes.