HTTP Caching and Conditional Requests
Use HTTP caching correctly with Cache-Control, ETag, Last-Modified, and conditional requests.
Cache-Control
HTTP caching can dramatically reduce API latency and server load.
Cache-Control: max-age=60 allows a response to be considered fresh for 60 seconds. Other directives include private, public, no-cache, no-store, must-revalidate, and s-maxage.
no-cache does not mean "never store". It means the stored response must be revalidated before reuse. no-store instructs caches not to store the response.
Caching must be designed with authorization and data sensitivity in mind.
Fresh for 60 secondsDo not storePrivate cache onlyRevalidate before reuseETag and Conditional Requests
ETag
An ETag identifies a particular representation version.
The server can return:
ETag: "user-42-v7"
The client can later send:
If-None-Match: "user-42-v7"
If the representation has not changed, the server can return 304 Not Modified without retransmitting the body.
If-Match can also implement optimistic concurrency control. A client sends the version it previously observed, and the server rejects the update if the resource changed meanwhile.
Preventing Lost Updates
Optimistic Concurrency
Imagine two administrators read the same user record. Administrator A updates it. Administrator B then submits an update based on stale data and accidentally overwrites A's changes.
ETags and If-Match can prevent this.
The client sends the representation version it read. If the server's current version differs, the server returns 412 Precondition Failed rather than silently overwriting newer data.
This technique is essential for collaborative systems and APIs where concurrent edits are possible.
- ETags support efficient caching.
- Conditional requests can prevent stale writes.
- HTTP provides mechanisms for optimistic concurrency.