How a cache makes things faster
A cache keeps a copy of an earlier answer close by, so the next request does not start from scratch. The idea to keep: reuse the copy while it is fresh, and check it cheaply once it is not.
The short version
A browser cache is the example here. It stores a response and reuses it for later requests to the same URL. The server says how long the copy counts as fresh, for instance with Cache-Control: max-age=604800, which is one week. While the copy is younger than that, the browser answers from its own storage and the server is not asked. After that the copy is stale, but it is not thrown away: the browser can check it with the server first.
Step by step
- A request arrives and the cache looks for a stored copy. With no copy, the request goes to the server as usual.
- If the copy is fresh, it is reused and the server is not contacted.
- If it is stale, the cache asks the server, sending the copy's ETag in an
If-None-Matchheader. - If nothing changed, the server replies
304 Not Modifiedwith no body, and the stored copy is reused. - If it changed, the server replies
200 OKwith the new version, which replaces the copy.
Why it matters
Fewer full downloads mean faster pages and less work for the server. The trade-off is yours to pick with max-age: a longer lifetime saves more requests, but the copy can be out of date for longer.
Sources
- HTTP caching — MDN — a cache stores a copy of a response and reuses it; fresh and stale by age;
max-age=604800as one week; revalidation with ETag andIf-None-Match; 304 versus 200 - RFC 9111: HTTP Caching — a cache reduces response time and bandwidth (section 1); freshness lifetime versus age (4.2); conditional requests and 304 (4.3)