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.
The shortcut
For each endpoint, ask two questions: Who may keep a copy? For how long before checking?
GET /v1/genres
Anyone may keep it; it rarely changes:
public, max-age=86400plus an ETag.
The trap is reading no-cache as "do not cache". It means "cache, but revalidate every time". Only no-store forbids storing.
Drills
Answer fast — trust the rule.
What does Cache-Control: max-age=300 allow a client to do?
A client sends If-None-Match: "genres-v12" and the genres have not changed. What should the server return?
Which directive means the response must never be written to any cache?
Why should a member's own loan list use private rather than public?
Remember
- Fresh copies are reused; stale copies are checked, not refetched.
- Shortcut: who may keep a copy, and for how long before checking?
- Trap:
no-cachestill caches; onlyno-storeforbids it.
