HomeBytesheetsRoadmapsUI TemplatesUI ToolsStack Discussion
3 Topics
Chapter•150 Minutes

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.

Cache Directives
max-age=60: Fresh for 60 seconds
Allows reuse while the response remains fresh.
no-store: Do not store
Useful for sensitive responses that should not be cached.
private: Private cache only
Prevents shared caches from storing the response.
no-cache: Revalidate before reuse
The response may be stored but must be validated before reuse.

ETag 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.

Conditional GET

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.

Key Takeaways
  • ETags support efficient caching.
  • Conditional requests can prevent stale writes.
  • HTTP provides mechanisms for optimistic concurrency.