paulund

14. Caching

14. Caching

Caching reduces the number of requests that reach your origin server and speeds up responses for your clients. HTTP provides a rich set of headers to control exactly how and for how long responses are cached.

Cache-Control

The Cache-Control header tells caches — both on the client and at intermediate proxies — how to treat a response:

Cache-Control: public, max-age=3600

This tells any cache that the response is safe to store and remains fresh for 3600 seconds (one hour). Use private instead of public if the response contains user-specific data that must not be stored in a shared proxy cache.

For responses that should never be cached — authenticated data that changes frequently, for example — be explicit:

Cache-Control: no-store

ETags and Conditional Requests

ETags provide a more precise freshness mechanism than time-based expiry. The server attaches an ETag header containing a unique identifier (often a hash of the response body) to each cacheable response:

ETag: "a1b2c3d4e5f6"

On the next request for the same resource, the client sends the previously received ETag in an If-None-Match header:

If-None-Match: "a1b2c3d4e5f6"

If the resource has not changed, the server responds with 304 Not Modified and an empty body. The client uses its cached copy. If the resource has changed, the server responds with 200 OK and the full updated payload along with a new ETag.

Benefits

  • Reduced bandwidth. 304 responses contain no body, cutting data transfer significantly for frequently polled endpoints.
  • Lower server load. The server still receives the request, but it skips the expensive work of serialising and transmitting the full response when nothing has changed.
  • Faster clients. Clients that support conditional requests get fresh data without waiting for a full round trip of payload transfer.

What to Cache and What Not to

Cache GET responses for data that does not change frequently — product catalogues, public content, reference data. Do not cache responses to POST, PUT, PATCH, or DELETE requests, and do not cache anything that contains user-specific secrets or session data without careful thought.