How-To Guide

How to Implement HTTP Cache Validation with ETags

Generate stable validators, answer If-None-Match with 304 responses, keep ETags consistent across server replicas, and prove validation with curl.

On this page

  1. Introduction
  2. How validation works
  3. Generate a stable ETag
  4. Weak versus strong validators
  5. Vary and negotiation
  6. Combine with Cache-Control
  7. Test the whole flow
  8. Common pitfalls
  9. Conclusion

Introduction

Every cacheable response eventually becomes stale, and when it does the client faces a choice: refetch the full body, or ask the server whether anything actually changed. Conditional requests implement the second option. The server attaches a validator to each response, either an ETag or a Last-Modified date. On the next request the client echoes the validator in If-None-Match or If-Modified-Since, and the server answers 304 Not Modified with headers only, no body. For a typical API payload of a few hundred kilobytes, the saving is nearly the entire transfer. This tutorial covers how validators work, how to generate an ETag that is stable across server instances, how weak and strong validators differ, how Vary interacts with validation, and how to test the whole flow so it survives refactors. The examples use Node.js, but the semantics are protocol-level and apply to any stack.

How validation works

Caching has two phases. In the freshness phase, governed by Cache-Control directives like max-age, the client uses its stored copy without contacting the origin at all. Once the copy expires, the validation phase begins: the client sends a conditional request carrying the validator it stored. If the server computes the same validator, it returns 304 with the same cache-control headers so the client restarts the freshness clock, and the body transfer is skipped entirely. The ETag header is an opaque quoted string such as “33a64df5”. Last-Modified is a date with one-second granularity, which is why ETags are preferred for anything that can change more than once per second or where exact byte equality matters. A conditional request is just a normal GET with an extra header, so conditional logic sits in front of the normal handler rather than replacing it. This placement matters: validation must happen before any expensive body serialization, or the 304 saves client bandwidth but not server CPU.

Generate a stable ETag

An ETag is only useful if it is a deterministic function of the response. Hash the exact bytes the server would send, after compression is applied or before it, but pick one point in the pipeline and hash there on every instance. A hash computed over the uncompressed body is more stable, because intermediaries may re-negotiate compression. Never mix in random values, process identifiers, or timestamps of the response generation itself, or every replica and every restart will produce different validators and 304 rates will collapse.

import { createHash } from 'node:crypto';

function etagFor(body) {
 const hash = createHash('sha256').update(body).digest('base64url').slice(0, 27);
 return '"' + hash + '"';
}

function respond(res, req, body) {
 const etag = etagFor(body);
 const inm = req.headers['if-none-match'];
 if (inm && inm.split(',').map(v => v.trim()).includes(etag)) {
  res.writeHead(304, { etag, 'cache-control': 'public, max-age=60' });
  res.end();
  return;
 }
 res.writeHead(200, { etag, 'cache-control': 'public, max-age=60' });
 res.end(body);
}

The matching rule is list-based: If-None-Match may carry several validators, and a hit on any of them triggers the 304. If-None-Match takes precedence over If-Modified-Since when both are present, so implement ETag matching first and treat the date header as the fallback path.

Weak versus strong validators

A strong ETag means the bytes are identical: two responses with the same strong validator can be substituted for each other in range requests and partial-content logic. A weak validator, written with the W/ prefix such as W/“0815”, means the representations are semantically equivalent but may differ in bytes, typically because of whitespace or re-serialization. Weak comparison is what If-None-Match uses for GET revalidation, so weak ETags are safe and often more practical for generated HTML. Strong comparison matters for If-Range: when a client resumes a download with a Range request, the server answers with the remaining bytes only if the representation has not changed, and that decision requires byte-level identity. The practical guidance is to emit weak validators for templated documents and strong validators for immutable assets and API payloads where the body is serialized deterministically. When in doubt, strong validators are never wrong for correctness, only occasionally slower to hit.

Vary and negotiation

Validation is per-representation, and a URL can have several representations at once. A gzip-encoded body and a brotli-encoded body of the same document are different byte sequences, so they need different ETags. The Vary header tells caches which request headers select the representation, and omitting it is the classic production bug: a cache stores the brotli copy and serves it to a client that only advertised gzip support. Emit Vary: Accept-Encoding on every compressible response. If the server varies on Accept-Language or Accept for content negotiation, those belong in Vary too, though each additional Vary dimension fragments the cache and lowers hit rates, so negotiate on as few dimensions as the product actually needs. When the ETag is computed over the compressed bytes, the Vary and the validator stay consistent automatically; when it is computed over the uncompressed body, the same ETag legitimately appears on multiple encodings and must then be weak, because the encodings differ in bytes while agreeing in meaning.

Combine with Cache-Control

A common misconception is that ETags and Cache-Control compete. They operate on different questions. Cache-Control with max-age=300 says the copy is fresh for five minutes and no request happens during that window. After expiry, the conditional request fires, and the ETag decides between a 304 and a full 200. The no-cache directive does not disable caching despite its name; it requires validation on every use, which is exactly the pattern for HTML documents: cache-control: no-cache plus an ETag means every page view costs one conditional request and one 304 response, roughly a few hundred bytes, instead of the full document. For versioned assets with fingerprinted URLs, use immutable caching with a long max-age and skip validation entirely, because the URL itself guarantees the content never changes. The two strategies coexist on one site: fingerprinted assets on immutable, dynamic documents on no-cache with validators.

Test the whole flow

Validation logic fails silently: a broken implementation returns 200 every time and the site still works, just slower. Tests must therefore assert the 304 path explicitly. A three-step curl sequence covers the protocol behavior end to end.

ETAG=$(curl -sD - -o /dev/null https://example.com/api/report | awk -F': ' '/^etag:/ {gsub(/\r/, "", $2); print $2}')
curl -s -o /dev/null -w 'status=%{http_code} size=%{size_download}\n' \
 -H "If-None-Match: $ETAG" https://example.com/api/report
curl -s -o /dev/null -w 'status=%{http_code} size=%{size_download}\n' \
 -H "If-None-Match: \"deadbeef\"" https://example.com/api/report

The expected sequence is a first 200 with a validator, a second request returning 304 with a download size of zero, and a request with a deliberately wrong validator returning a full 200. In integration tests, mutate the underlying data between requests and assert the ETag changes, then assert that two identical serializations produce identical validators across separate process instances, which catches nondeterministic hashing. Also assert the 304 response carries the same cache-control and vary headers as the 200, because caches refresh those headers from the 304.

Common pitfalls

  • Per-instance validators. Random seeds or process data in the hash make replicas disagree and destroy 304 hit rates behind load balancers.
  • Hashing before final serialization. Late template whitespace or compression changes the bytes after hashing, so the ETag no longer represents the body sent.
  • Missing Vary: Accept-Encoding. Caches serve the wrong encoding to clients that cannot decode it.
  • Validating after serialization. The 304 then saves client bandwidth but not server CPU, which is often the expensive half.
  • Treating no-cache as disabled caching. It means revalidate every use, which pairs perfectly with ETags.
  • Dropping headers from the 304. Caches refresh their stored headers from the 304 response, so omitting cache-control silently shortens or breaks reuse.

Conclusion

Conditional requests are the cheapest performance feature in HTTP: a validator, a comparison, and a 304 with no body. Generate the ETag from the final serialized bytes with a deterministic algorithm shared by every replica, match If-None-Match as a list before doing expensive work, declare Vary dimensions honestly, and choose weak validators for templated output where byte equality is not meaningful. Pair validators with a Cache-Control strategy that fits the content type, fingerprinted assets on immutable and documents on no-cache. Then test the 304 path explicitly, because when it breaks nothing crashes, it only costs bandwidth quietly. Done correctly, a warm client refetches almost nothing.

Sources: MDN: HTTP conditional requests, MDN: ETag header, RFC 9110: HTTP semantics.

FAQ

Why did my ETag change even though the content did not?
The validator covers the bytes sent, so a different compression level, template whitespace, or per-instance randomness changes the ETag. Hash after final serialization and keep the algorithm identical across replicas.
Should I use weak or strong ETags?
Weak validators with the W/ prefix survive semantically equal byte differences and are sufficient for If-None-Match revalidation. Strong validators are required by If-Range and by any cache that must byte-match partial responses.
Do ETags replace Cache-Control?
No. Freshness via max-age decides whether the client contacts the server at all; validation decides whether the answer is a 304 or a full body. The two headers solve different halves of caching and work best together.

Related Examples