Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 39 ยท Pagination, Caching and Versioning

HTTP Caching, ETags and Conditional Requests

Speed up your API with HTTP caching: Cache-Control, ETag and If-None-Match for 304 responses, Last-Modified, Vary, and If-Match for safe concurrent updates.

The fastest request is the one that never reaches your server. HTTP has caching built in, and a REST API that uses it well can serve most reads from a browser, a CDN or a reverse proxy at almost no cost. Caching also gives you two bonus features for free: cheap "has this changed?" checks and protection against lost updates when two clients edit the same resource.

This lesson covers freshness (Cache-Control), validation (ETag, If-None-Match, Last-Modified), the Vary header, and using If-Match for optimistic concurrency. All of it is plain HTTP, no extra library needed.

Two ways a cache helps

Freshness Reuse the copy, no request at all.
Validation Ask "changed?" and get 304.
Saves Bandwidth, CPU and latency.

Freshness avoids the request. Validation shrinks the response.

1 / 2

Freshness with Cache-Control

The Cache-Control response header tells caches how long a response stays fresh and who may store it.

Directive Meaning
max-age=60 Fresh for 60 seconds; reuse without asking the server
s-maxage=300 Like max-age, but only for shared caches (CDNs)
public Shared caches may store it
private Only the user's own cache may store it (per-user data)
no-cache May be stored, but must be revalidated before each use
no-store Never store it (tokens, sensitive data)
stale-while-revalidate=30 May serve a stale copy for 30 s while refreshing in the background
immutable Will never change (versioned URLs)

Typical choices for an API:

  • Reference data that changes rarely (countries, categories): public, max-age=3600.
  • A list that changes sometimes: public, max-age=30, stale-while-revalidate=60.
  • Personal data (/me): private, no-cache (or no-store when sensitive).
  • Responses with tokens or secrets: no-store.

Only GET and HEAD responses are cached by default. Responses to POST, PUT and DELETE are not (and unsafe methods invalidate the cached copy of the same URL).

Validation with ETag

When a copy is stale (or no-cache), the cache does not have to download it again. The server labels each version of a resource with an ETag, an opaque string such as a hash of the content. The client stores it and next time sends it back:

HTTP
GET /articles/7 HTTP/1.1
If-None-Match: "a1b2c3"

If the resource still has that ETag, the server answers 304 Not Modified with no body. The client reuses its stored copy. If it changed, the server sends 200 with the new body and a new ETag. You still pay for a round trip, but not for the payload, and often you can skip the expensive database work too.

Strong ETags are quoted ("a1b2c3"); weak ETags start with W/ and say "semantically equivalent". Use a content hash, a version number or the row's updated_at plus ID.

Node.js ETag and 304 Not Modified

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Five requests, but the server sent the body only twice: the first time and after the change.

Last-Modified

Last-Modified is the older, date-based validator. The client sends it back as If-Modified-Since, and the server answers 304 if nothing changed after that date. It has one-second resolution, so prefer ETags when changes can happen faster than that. Sending both is fine; if both validators are present, If-None-Match wins.

Vary

If the same URL returns different content depending on a request header, tell caches with Vary, or a CDN may serve a French response to an English reader:

HTTP
Vary: Accept-Language, Accept-Encoding

Vary: Authorization or Vary: Cookie makes shared caches useless for personalized responses. Use private for those instead. For CORS responses add Vary: Origin (CORS and Security Headers).

Safe updates with If-Match

ETags solve another problem: lost updates. Two users load the same article. Both edit it. The second PUT silently overwrites the first, and nobody notices. With optimistic concurrency, the client sends the ETag it last saw in an If-Match header:

HTTP
PUT /articles/7 HTTP/1.1
If-Match: "a1b2c3"

The server applies the change only if the current ETag still matches. If somebody else changed the resource meanwhile, it answers 412 Precondition Failed, and the client must fetch the new version and merge. If a client sends no If-Match at all on an API that requires it, answer 428 Precondition Required.

Node.js If-Match prevents lost updates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Ben's first save is refused instead of destroying Ana's work. This is also how you can make DELETE safe.

Caching rules of thumb

  1. Decide a caching policy for every response, and send Cache-Control explicitly, because heuristic caching is unpredictable.
  2. Use private for anything user-specific and no-store for secrets.
  3. Prefer short max-age plus validation for data that changes, and long max-age plus versioned URLs for static data.
  4. Generate ETags from the content or a version, and make them cheap to compute (an updated_at or version column avoids loading the whole row).
  5. Avoid putting changing data in URLs that you cache for a long time; to invalidate, change the URL or wait for expiry (CDNs also support purging).
  6. Paginated responses are cacheable too, but include the query string in the cache key, which is automatic for URLs.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a 304 Not Modified response contain?

    304 says the cached copy is still valid, so the server sends headers only.
  2. 2. Which Cache-Control value suits a response containing a user's private profile?

    Private keeps shared caches from storing it, and no-cache forces revalidation before reuse.
  3. 3. What does no-cache mean?

    no-cache is about revalidation. no-store is the directive that forbids storing.
  4. 4. A client sends PUT with If-Match, but the resource changed. Which status does the server return?

    412 Precondition Failed tells the client its version is out of date and must be reloaded.
  5. 5. Why add Vary Accept-Language to a response?

    Vary lists request headers that influence the response, so caches use them in their cache key.

Summary

  • Use Cache-Control to set freshness: max-age, s-maxage, public, private, no-cache, no-store.
  • Validate stale copies with ETag and If-None-Match; 304 saves the body.
  • Vary lists the request headers that change a response; avoid Vary: Cookie on shared caches.
  • Use If-Match for optimistic concurrency: 412 on a conflict, 428 when the precondition is missing.
  • Choose a caching policy deliberately for every endpoint.

Next: API Versioning and Evolution