Card 01/ 11
Caching an API Response: Who Stores It, and for How Long
A browser, a CDN and a proxy may each keep a copy, and the headers say what each may do.
An HTTP cache stores a copy of a response so a later request can be answered without asking the server, the origin, again. A private cache, such as a browser's, serves one user; a shared cache, such as a CDN or a company proxy, serves many. The origin sets how long a copy stays fresh, and while it is fresh a cache answers on its own, saving the round trip and the server's work.
Freshness. A response is fresh for as long as the origin says, usually with Cache-Control: max-age=3600, meaning 3,600 seconds. A fresh copy is served without contacting the origin. Once it is stale, the cache must check with the origin before using it again, which is called revalidating.
What caches store by default. Caches store responses to GET, and to HEAD, by default; they almost never store responses to POST, PUT or DELETE. That is one reason reads belong on GET.
Private and shared. A browser cache holds data for the person using that browser, so it can safely keep personal responses. A shared cache sits in front of many users, so anything it stores may be handed to anyone who asks for the same URL. Which kind of cache may store a response is the most important choice in this topic.
Without a header. If a response has no caching headers, caches may still guess a lifetime from other headers, such as Last-Modified. An API should never leave the decision to a guess; every response should say what it wants.
So set caching on purpose for every response: who may store it, and for how long it stays fresh.
← → move through sections and cards