How a cache makes things faster

· 2 min read

#how-it-works#web

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.

How a cache answers a request A request reaches the cache. If the stored copy is fresh, it is reused. If it is stale, the cache asks the server. A 304 reply means keep the copy, and a 200 reply brings a new copy. Request Copy still fresh? age below max-age Reuse the copy Stale: ask server If-None-Match + ETag 304: keep copy 200: new copy 1 ask 2 yes 2 no 3 same 3 changed example: Cache-Control: max-age=604800 is one week
Simplified: only the browser's HTTP cache is shown.

Step by step

  1. A request arrives and the cache looks for a stored copy. With no copy, the request goes to the server as usual.
  2. If the copy is fresh, it is reused and the server is not contacted.
  3. If it is stale, the cache asks the server, sending the copy's ETag in an If-None-Match header.
  4. If nothing changed, the server replies 304 Not Modified with no body, and the stored copy is reused.
  5. If it changed, the server replies 200 OK with 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