HTTP caching: Cache-Control, ETag and conditional requests

Difficulty: Intermediate

Question

How do you use HTTP caching headers in an API? Explain Cache-Control, ETag and conditional requests.

Answer

Caching is the cheapest performance win in web systems: the fastest request is the one that never reaches your server. Think of a newspaper stand. Some items are fresh for a day, so you do not phone the publisher each time; for others you ask 'has this changed since my copy?' and only take a new one if it has. HTTP encodes both ideas.

Freshness is controlled by Cache-Control. max-age=N says a response is fresh for N seconds; during that time, a cache may reuse it with no network call. public allows shared caches such as CDNs to store it; private restricts it to the user's browser, important for personalised data. no-cache does not mean do not store, it means store but revalidate before reuse. no-store means never store at all, appropriate for sensitive responses like tokens or bank statements. s-maxage sets a separate lifetime for shared caches, and stale-while-revalidate lets a cache serve a stale copy while fetching a fresh one in the background, hiding latency. must-revalidate forbids serving stale after expiry.

Validation handles the expired case. The server sends a validator: ETag, an opaque identifier for a specific version of the representation (often a hash or a version number), or Last-Modified, a timestamp. When the cached copy expires, the client sends a conditional request with If-None-Match: "abc123" (or If-Modified-Since). If the resource is unchanged, the server replies 304 Not Modified with no body, so you save bandwidth and serialisation cost; otherwise it returns 200 with the new body and new ETag. Strong ETags mean byte-for-byte equality; weak ETags, prefixed W/, mean semantic equivalence.

Important design details. Use Vary to declare which request headers affect the response, for example Vary: Accept-Encoding, Accept-Language, or Authorization. Without it, a shared cache could serve a Hindi response to an English user. Never cache authenticated, per-user responses with public. GET responses are cacheable by default; POST generally not. Cache keys include the URL and query string, so normalise parameter order to increase hit rate.

What to cache in a real API: reference data such as product catalogues, config and country lists deserve long max-age and CDN caching. Frequently read but slowly changing resources get short max-age plus ETag. Highly dynamic or sensitive data gets no-store or private, no-cache. For immutable assets, use fingerprinted URLs with max-age=31536000, immutable.

Invalidation is the hard part. Options: short TTLs, versioned URLs, surrogate keys or purge APIs on CDNs such as Fastly and Cloudflare, and event-driven invalidation on write. Keep in mind that browser caches cannot be purged remotely, so be careful with long max-age values on mutable data.

Beyond reads, ETags help writes: If-Match on PUT or PATCH prevents lost updates, replying 412 Precondition Failed if the version changed. That is optimistic concurrency at the HTTP layer.

In an interview, walk through a sequence: first request 200 with ETag and max-age=60; within 60 seconds served from cache; afterwards conditional GET returning 304; and mention the difference between no-cache and no-store, which is a very common trick question.

Code examples

Conditional GET flow

GET /v1/products/42 HTTP/1.1

HTTP/1.1 200 OK
Cache-Control: public, max-age=60, stale-while-revalidate=30
ETag: "v17"
Vary: Accept-Encoding

{ "id": 42, "name": "Keyboard", "price": 199900 }

# later, after expiry
GET /v1/products/42 HTTP/1.1
If-None-Match: "v17"

HTTP/1.1 304 Not Modified
ETag: "v17"
Cache-Control: public, max-age=60

The 304 has no body, so the client reuses its cached copy and refreshes its freshness timer.

ETag in Express

import crypto from 'crypto';
app.get('/v1/products/:id', async (req, res) => {
  const product = await getProduct(req.params.id);
  const etag = '"' + crypto.createHash('sha1').update(JSON.stringify(product)).digest('hex') + '"';
  res.set({ 'Cache-Control': 'public, max-age=60', ETag: etag });
  if (req.header('If-None-Match') === etag) return res.status(304).end();
  res.json(product);
});

Compares the client's validator against a hash of the current representation.

Key points

Common follow-up questions

Interview tips

Concepts covered

caching, Cache-Control, ETag, conditional requests

More API Design questions