HTTP cache practical

Vary Header

Test the returned representation before celebrating a cache hit. A single URL can select different content from request headers, and storage policy decides a separate part of the behavior.

Executed browser
Chromium 151.0.7922.34 with Playwright 1.62.1
Compared cases
10 scenarios, 50 default-fetch observations
Broken control
No Vary returned the requested representation only 3 of 5 times
Validation boundary
No-cache contacted the origin 5 times, including 2 responses with status 304
A librarian stops a blue-book handoff to a reader holding an amber request card. Separate shelf compartments behind them contain blue and amber books.
Story illustration: reusing an available answer can still give the reader the wrong requested variant.

First, make the cache return a wrong answer

Request the same URL with language preferences en, en, fr, fr, en. Our local origin selects an English or French JSON representation from Accept-Language. With Cache-Control: max-age=600 and no Vary, Chromium contacted the origin once and returned English for all five fetches. The French requests received the wrong representation even though every fetch returned status 200.

That is the first assertion to add to a localized SaaS endpoint: compare the returned representation with the requested one. Counting cache hits alone would favor this broken case. The fixture uses public synthetic labels, not customer data or an actual authentication boundary.

The Vary response header tells a cache which request fields influenced representation selection beyond the usual method and target URI. It does not ask the client to send those fields. It also does not grant permission to store a response. Selection and storage are separate decisions. The HTTP semantics definition supplies that contract.

Declare the inputs that change the representation

Example response for a cacheable language variant; choose freshness and privacy policy for the actual resource.
HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: max-age=600
Vary: Accept-Language

Use a comma-separated list when more than one request field changes the selected response, for example Vary: Accept, Accept-Language. HTTP field names are case-insensitive. A literal * is a special value: selection can depend on something a cache cannot match from the named request fields. It prevents reuse through an ordinary field-value match.

Keep the declaration consistent for the default representation and conditional responses. A request with no preferred language still needs a defined default response. Leaving Vary off that default can let the fallback representation become an inappropriate match for later requests. The Vary reference calls out consistency across responses, including 304.

Compare ten scenarios on the same sequence

The browser lab runs five response policies for each of two selectors: Accept-Language chooses en or fr, and the invented X-View field chooses compact or expanded. Each route receives A, A, B, B, A in a fresh browser context. This gives ten scenarios and fifty fetch observations. Both selectors produced the counts below.

Observed per five-fetch route in Chromium 151.0.7922.34. The same outcomes occurred for both header dimensions.
Response policyCorrect representationsOrigin contactsOrigin status trace
No Vary, max-age=6003 of 51200
Named Vary, max-age=6005 of 53200, 200, 200
Vary: *, max-age=6005 of 55Five 200 responses
Named Vary, no-store5 of 55Five 200 responses
Named Vary, no-cache + ETag5 of 55200, 304, 200, 304, 200
For five language fetches, omitted Vary gave three correct responses and one origin contact; named Vary gave five correct and three contacts; wildcard, no-store and no-cache gave five correct and five contacts each.
Counts from the saved language scenario. The separate custom-header scenario repeated these results. Contacts and correct representations are counts, not latency or a reliability score. View full-size figure.

The second and fourth requests reused a matching cached response under named Vary. Returning to A on the fifth request contacted the origin again. Do not turn the phrase "part of the cache key" into a promise that this browser retains every earlier variant. The observed browser behavior is narrower than a multivariant CDN storage design.

Match the representation before reusing it

The observed A,A,B,B,A sequence returns A,A,A,A,A without Vary, making the third and fourth responses wrong. Named Vary returns A,A,B,B,A with origin contacts on requests one, three and five.
Observed sequence for either synthetic selector. Red outlines mark wrong returned representations, not network failures. View full-size figure.

The cache matching rules compare the fields named by the stored response with the corresponding fields of a later request. When a listed request field was absent, a later request must also lack it to match that aspect. An empty field value is not automatically equivalent to an absent field.

Caches may apply the normalization allowed by a field's semantics. That does not authorize your application to collapse inputs that select different outputs. If an edge reduces language preferences to a supported language set, the origin must select consistently with that reduction. A query-string language parameter already changes the target URI; a header-selected language can change the representation while the URI stays the same.

Our executed values are deliberately simple and present on every request. The lab does not test absent versus empty fields, equivalent language preference lists or a multi-header combination. Those are additional matching fixtures to add when your selection logic uses them.

Choose storage policy separately

Named Vary with a positive freshness lifetime allowed matching reuse in the lab. Vary: * forced an origin contact on every fetch. It is a selection signal, not a substitute for an explicit sensitive-data storage policy. Use Cache-Control to state that policy.

no-store tells caches not to store the response. no-cache allows storage but requires successful validation before reuse. In the executed no-cache route, every fetch contacted the origin, while two responses validated an existing body with 304. These outcomes distinguish avoiding storage from reusing stored data after checking it.

private prevents a shared cache from storing the response while allowing a private cache, such as a browser cache, to store it. It does not mean "do not cache anywhere." The Cache-Control directives define these separate controls. Private caching was not another executed route here.

Changing the origin policy is not proof that old fresh copies have disappeared from other layers. A browser or edge that serves an existing fresh object may not contact the origin to learn the new headers. Plan the expiry, cache-key change or relevant invalidation with the layer that actually holds the response.

Read the origin status and the browser result separately

The no-cache fixture gives each representation its own stable ETag. The second A request and second B request sent If-None-Match and received 304 from the origin. The browser fetch still exposed status 200 and the appropriate stored JSON body to the page. Our runner records origin traces separately from the page's response.

The fixture includes the same selection field on its successful validation response.
HTTP/1.1 304 Not Modified
Cache-Control: no-cache
Vary: Accept-Language
ETag: "language-en"

Returning 304 without a body is useful only when the selected stored representation is the one being validated. Keep validators representation-specific and maintain the selection metadata. The fixture does not send an ETag on the omitted-Vary control, so that control cannot accidentally hide its wrong-answer problem behind a validation path.

If-None-Match on a read is distinct from If-Match on an update. For preventing lost writes, use the separate ETag optimistic concurrency guide. A correct read-cache selector does not establish a write precondition.

Keep cache selection outside the authorization decision

An invented X-Tenant or account field is not proof of who may read the selected data. The server must authenticate the caller and enforce access before returning a tenant-specific representation. Adding a header name to Vary does not perform either check.

Review the storage contract explicitly when cookies or authorization affect a response. A private response and a no-store response have different rules, and shared-cache handling of an Authorization request has additional restrictions in HTTP caching. Do not treat Vary: Cookie or Vary: Authorization as a complete security policy.

Our X-View fixture contains only public display labels. It establishes custom-field selection in one browser context, not cross-user isolation, logout cleanup or revocation. The SaaS authorization matrix owns access decisions. Keep identity and permission assertions in that layer rather than inferring them from a cache hit.

Keep the selector as narrow as the output allows

A raw User-Agent or entire Cookie field can have many values even when the application has only a few useful response variants. More distinct inputs can fragment reuse. That is an architectural risk to measure in your own cache, not a cache-size statistic measured by this small lab.

Accept-Encoding selects an encoded representation, while Accept can select a media type. They are different dimensions from language. Preserve the relevant dimension when serving different bytes, and let the actual compression layer own its encoding contract. This experiment always sends uncompressed JSON and supplies no compression or content-negotiation parser implementation.

Normalize to a bounded supported set only when the origin and cache agree on the resulting representation. If a distinction changes authorization or response content, removing it from the selector can merge responses that must remain separate.

Verify the actual edge contract

A local Chromium trace does not establish what a CDN stores. Current Cloudflare Vary documentation describes per-header actions such as normalize, passthrough and bypass when Vary behavior is configured. The origin still needs to emit the applicable Vary field. Review the current product configuration instead of assuming every cache implements the same policy.

Check cache eligibility and privacy rules as well as key selection. Confirm what reaches the origin after normalization, what the edge considers a match and which responses it bypasses. An example header on an origin response is not evidence that a deployed edge used it.

No Cloudflare rule, Worker or Dreamtsoft cache policy was changed for this article. The CDN discussion is documentation-backed deployment guidance, not an executed CDN test.

Keep the browser cache enabled while testing it

In DevTools, an enabled "Disable cache" option can hide the reuse you are investigating. Likewise, Playwright routing disables the HTTP cache. A test that installs page.route to mock or intercept requests is unsuitable for proving ordinary browser cache reuse.

The runner starts a real local HTTP origin and uses page-context fetch with its default cache mode. It installs no route interception. Service workers are blocked so they cannot supply a second cache implementation. The origin records actual request arrivals and status codes outside the response body.

Use a fixed sequence with adjacent repeats and a return to the first value. Record requested and returned representation, whether the origin was contacted and any conditional-request fields. Inspect response headers with a tool such as curl, but do not mistake repeated curl calls for a browser HTTP-cache experiment.

A status-200 assertion alone misses the omitted-Vary failure. The useful acceptance check is that the returned representation matches the request under the intended storage policy. Retain the deliberately broken control so the test also proves caching was active.

Run the real-browser fixture

Download the Node experiment and saved results. Run it from an isolated scratch directory with the tested Playwright version and browser installed:

Local reproduction; the origin binds only to an automatically allocated 127.0.0.1 port and closes after the run.
npm install playwright@1.62.1
npx playwright install chromium
node experiment.mjs > actual.json

The recorded environment was Node 24.20.0, Playwright 1.62.1 and Chromium 151.0.7922.34. Two executions produced byte-identical JSON. Port numbers and wall-clock dates are omitted from the saved data. The ten scenarios each contain five fetches, giving fifty observations, not fifty independent production users.

The origin, browser and assertion runner are real. The language and view labels are synthetic. The fixture measures no response time, throughput, eviction policy, disk persistence or cross-browser behavior. Another installed browser build can change cache retention behavior, so retain its version alongside any new result.

Keep neighboring cache problems in their owning tests

Vary: Origin can matter when an approved cross-origin response differs by Origin. It does not grant CORS permission by itself, and this same-origin lab runs no preflight request. The CORS completed-write cases explain the separate problem of a browser error after a server has performed a write.

An application-level feature decision cache needs an appropriate tenant key even if no HTTP response cache is involved. Use the feature flag decision-cache guide for that boundary. The current test instead asks whether one URL and a declared request selector return the intended HTTP representation.

Framework recipes for Nginx, Apache, Express or Django, service-worker caches and other CDN vendors need their own configuration review. Use the downloaded fixture to state the behavior you require, then verify it through the actual layers in your delivery path.

Sources

Documentation checked .

  1. HTTP semantics: Vary
  2. HTTP caching: matching variants and Cache-Control
  3. MDN Vary response header
  4. Cloudflare Vary behavior
  5. Playwright routing and HTTP cache caveat

Continue the conversation

Comments (0)

    Leave a comment

    Your name and comment stay in this page and are cleared after the spam check.

    10–2,000 characters. Keep the discussion relevant to this article.

    Spam protection verification
    Spam protection loads when you begin the form.

    JavaScript is required to use this form and its spam protection.