Skip to the workspace
Pebellslearn by building
HTTP in Depth  ›  Lesson

HTTP Caching

HTTP Caching 14 minCache-Control says who may keep a copy and for how long it is fresh, and once it goes stale an ETag lets the client ask whether it changed and receive a tiny 304 if not.

api design / HTTP Caching

Explore each scene at your own pace.

01 · The rule

The rule

HTTP Caching

The BookNook catalogue page asks for the list of genres on every screen. The genres change maybe twice a year. Sending the same list thousands of times a minute wastes the server, the network and the phone's battery. HTTP caching lets clients and proxies keep a copy and ask the server only when they need to.

The rule

Fresh copies are reused; stale copies are checked, not refetched.

Two ideas do the work.

Freshness — Cache-Control tells caches how long a response stays good:

HTTP/1.1 200 OK
Cache-Control: public, max-age=86400
ETag: "genres-v12"
  • max-age=86400: reuse this copy for a day without asking.
  • public: shared caches, like a CDN, may store it. private: only the user's own browser may, which suits a member's personal loans.
  • no-cache: you may store it, but check with the server before every reuse.
  • no-store: never store it at all. Use this for sensitive data.

Validation — once the copy is stale, the client asks "has it changed?" instead of downloading it again. The server gave the response a version tag, the ETag. The client sends that tag back:

GET /v1/genres HTTP/1.1
If-None-Match: "genres-v12"

HTTP/1.1 304 Not Modified
ETag: "genres-v12"

304 Not Modified has no body. The client keeps using its copy, and the round trip cost a few bytes instead of the whole list. If the genres had changed, the server would reply 200 OK with the new list and a new ETag. An older alternative pairs Last-Modified with If-Modified-Since, using a date instead of a tag.

Caching is for safe reads. Responses to POST, PUT, PATCH and DELETE are normally not reused.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.