PREP WITH PROOF
Menu
HTTP & WEB CACHING / PRACTICAL GUIDE

HTTP Vary Header: Fix Wrong Language or Encoding in Cache

Diagnose incorrect cached language or compression variants. Reproduce missing Vary with a local HTTP lab and test the origin and cache separately.

THE QUICK ANSWER

Vary names the request headers that a cache must consider before reusing a stored response without revalidation. If language or encoding changes the representation at the same URL, send the relevant Vary field consistently and verify that the cache separates the variants. Check the actual body, not just the status.

When the first request picks the language for everyone

An origin returns English for a request without a language preference and French for Accept-Language: fr. Direct requests look correct. Through a cache, the French request gets English after someone warms the URL with the default request. Both responses can be HTTP 200. The bug is which stored representation the cache reused.

Start by asking what actually selects the representation. If the same URI and method can produce different public representations based on a request header, the cache needs to know that dimension. The Vary response field names the request fields that mattered. Content-Language describes the response you received; it does not instruct the cache how to select a later response.

This guide isolates that selection bug with real loopback HTTP requests. It then shows how to diagnose the same pattern on an authorized test endpoint without confusing representation selection with freshness, validation, or a broken compression layer.

Source: RFC 9110: Vary and HTTP semantics ↗

Read Vary as a condition for reusing a stored response

Think of the method and target URI as the starting identity. If the stored response says Vary: Accept-Language, a cache must consider the original request’s language field when deciding whether it can reuse that response without revalidation. A stored English response from a request with no language field is not a match for a request that supplies fr.

If several names appear, each nominated field matters. HTTP permits normalization that preserves a field’s meaning, so this is not a universal raw-string comparison algorithm. An absent field matches another absence, while a Vary value containing an asterisk cannot match a later request under the normal selection rule. An asterisk is not a synonym for Cache-Control: no-store.

Emit the relevant Vary field on the default response as well as negotiated responses. If you only send it when a visitor requests French, a default response stored earlier may still be eligible for the French request. Inspect the entire response family, including the case where the request field is missing.

Source: RFC 9111: HTTP caching and Vary matching ↗

Reproduce the problem on localhost

Save the following as vary_lab.py and run python vary_lab.py. The HTTP server binds to a random port on 127.0.0.1 and the client disables ambient proxies. The origin route selects a fresh response each time. Two separate routes model a cache with and without a language dimension. No public service is contacted.

The language function intentionally understands only the exact value fr; all other values choose English. This is not a full Accept-Language parser. The small cache matches exact values for the one named field and does not implement freshness, validation, cache directives, eviction or general proxy semantics. X-Lab-Cache is a label defined by this example, not a standard field.

On Python 3.12.14 the exact block completed twelve real requests and checked each status, cache label, Content-Language, Vary and body. It tests a request with the field absent separately from one with a present but empty field. Both select English at the origin, but the teaching cache stores them separately when Vary is present.

from http.server import BaseHTTPRequestHandler, HTTPServer
from threading import Thread
from urllib.request import Request, ProxyHandler, build_opener

class Lab(BaseHTTPRequestHandler):
    def log_message(self, *_):
        pass

    def do_GET(self):
        route = self.path
        if route not in {"/origin", "/missing-vary", "/with-vary"}:
            self.send_error(404)
            return

        language_header = self.headers.get("Accept-Language")
        vary = "Accept-Language" if route == "/with-vary" else None
        bypass = route == "/origin"
        # Exact field-value matching for this fixture only.
        key = (route, language_header if vary else None)
        entry = self.server.entries.get(key) if not bypass else None
        if entry is None:
            language = "fr" if language_header == "fr" else "en"
            body = b"bonjour\n" if language == "fr" else b"hello\n"
            entry = language, body
            if not bypass:
                self.server.entries[key] = entry
            outcome = "BYPASS" if bypass else "MISS"
        else:
            outcome = "HIT"

        language, body = entry
        self.send_response(200)
        self.send_header("Content-Type", "text/plain; charset=utf-8")
        self.send_header("Content-Language", language)
        self.send_header("Content-Length", str(len(body)))
        self.send_header("X-Lab-Cache", outcome)
        if vary:
            self.send_header("Vary", vary)
        self.end_headers()
        self.wfile.write(body)

def run():
    with HTTPServer(("127.0.0.1", 0), Lab) as server:
        server.entries = {}
        thread = Thread(target=server.serve_forever, daemon=True)
        thread.start()
        base = f"http://127.0.0.1:{server.server_port}"
        client = build_opener(ProxyHandler({}))

        def check(route, field, expected_cache, expected_language):
            headers = {} if field is None else {"Accept-Language": field}
            with client.open(Request(base + route, headers=headers), timeout=3) as res:
                assert res.status == 200
                assert res.headers["X-Lab-Cache"] == expected_cache
                assert res.headers["Content-Language"] == expected_language
                assert res.headers.get("Vary") == (
                    "Accept-Language" if route == "/with-vary" else None
                )
                assert res.read() == (
                    b"bonjour\n" if expected_language == "fr" else b"hello\n"
                )
            print(route, repr(field), expected_cache, expected_language)

        try:
            check("/origin", None, "BYPASS", "en")
            check("/origin", "fr", "BYPASS", "fr")
            check("/missing-vary", None, "MISS", "en")
            check("/missing-vary", "fr", "HIT", "en")
            check("/with-vary", None, "MISS", "en")
            check("/with-vary", "fr", "MISS", "fr")
            check("/with-vary", "fr", "HIT", "fr")
            check("/with-vary", None, "HIT", "en")
            check("/with-vary", "", "MISS", "en")
            check("/with-vary", "", "HIT", "en")
            check("/with-vary", "en", "MISS", "en")
            check("/with-vary", "en", "HIT", "en")
        finally:
            server.shutdown()
            thread.join()
    print("PASS: 12 loopback HTTP requests")

if __name__ == "__main__":
    run()

Read the four requests that expose the mistake

On the missing-Vary route, the first request stores hello. The next request asks for French and gets that stored English response. The origin route already proved that the same French field value can produce bonjour when reuse is bypassed. That rules out the toy language selector as the cause.

On the corrected route, the first French request misses the English entry and gets bonjour. A repeated French request then hits the French entry. Switching back to an absent language field hits the English entry. The intended result is reuse within each variant, without reuse across unmatched requests.

RouteRequest fieldObserved lab outcome
Missing VaryAbsentMISS, English
Missing VaryfrHIT, English: wrong variant
With VaryAbsentMISS, English
With VaryfrMISS, French
With Varyfr againHIT, French
With VaryAbsent againHIT, English

Collect paired requests through the same cache layer

Use a safe test URL that can serve different public representations. Keep the method and URL identical. Send English, then French, then repeat both. A random query string on every request would test different targets and could conceal the reuse problem. Capture the first response and its repeat instead of relying on a single request.

The command saves headers and bodies separately so you can compare the chosen language and content. Replace the reserved example URL before running it. If you suspect compression rather than language, repeat the method with controlled Accept-Encoding values, inspect Content-Encoding and compare the decoded bodies with an appropriate decoder. The related gzip guide covers how curl’s decoding options affect what you see.

Cache-Status, when available, can identify cache handling at one or more layers. Age and vendor diagnostics can provide additional clues, but a missing field does not prove the request reached the origin. Compare the same request directly against the origin only through an authorized route that preserves the intended host and representation behavior. If the origin itself returns the wrong body, fix selection there before tuning reuse.

# Replace this reserved example URL with an authorized test endpoint.
url='https://example.test/help'
work=$(mktemp -d)
n=0
for language in en fr en fr; do
  n=$((n + 1))
  curl --silent --show-error \
    --header "Accept-Language: $language" \
    --dump-header "$work/$n.headers" \
    --output "$work/$n.body" "$url" || exit
  printf '\nRequest %s: %s\n' "$n" "$language"
  grep -Ei '^HTTP/|^(vary|age|cache-status|cache-control|content-language|content-encoding|etag):' \
    "$work/$n.headers"
done
printf 'Compare the captured headers and bodies in %s\n' "$work"

Source: RFC 9211: Cache-Status diagnostics ↗

Align the origin response, cache configuration and validators

At the origin, identify every request field that selects a cacheable public representation. If language and compression both change it, preserve both dimensions rather than replacing one Vary value with the other at a later layer. Compare origin and edge headers as well as bodies; a proxy or middleware can rewrite headers after the application has responded.

Verify that your cache actually respects the required variation. A managed cache may use a configured key or restrict which headers participate. Inspect that policy and repeat the paired test rather than assuming the presence of Vary on a response proves correct reuse. If old entries were stored before the correction, use your supported invalidation or expiry process and retest cold and warm requests.

Keep conditional responses consistent. When a server returns 304, it must include Vary if it would have sent that field on the equivalent 200 response. Validate the selected representation rather than using one strong validator for different representation bytes. Our conditional request guide explains how 304 and validators fit into that separate decision.

Source: RFC 9110: 304 response fields ↗

Separate a variant mismatch from a stale or undecodable response

The wrong variant often follows request order: after the first response is stored, another preference returns the same body. Run the sequence in the opposite order with a fresh test cache. If the first preference now wins instead, that is stronger evidence of a missing key dimension. If the origin always returns one language regardless of the header, investigate negotiation rather than cache matching.

Compare language and encoding separately. A body may decode successfully and still be the wrong translation. A client can also get the intended language but fail to decode bytes because the Content-Encoding header and payload disagree. The first problem concerns selection; the second requires inspecting the transfer and any transformations by the origin or intermediary.

An old version of the right representation points to freshness or invalidation instead. Check the response’s cache policy and validators, then see whether the origin would return newer bytes for the same request. In a multilayer setup, record where the first incorrect response appears. A browser refresh cannot repair an incorrect shared cache key.

What you observeCheck first
Language flips with the first warm requestVariant matching and Vary on the default response
Language is wrong even at the originNegotiation and request header forwarding
Correct language but decoding failsContent-Encoding and actual bytes
Correct variant but old contentFreshness, invalidation and validation

Do not use more variants to solve a different cache problem

Adding every incoming header to a key can make reuse ineffective. Many different Accept-Language strings can map to the same rendered language. If explicit locale paths such as /en/help and /fr/help fit the product, they give those representations distinct URLs. Verify what still varies within each path; moving language to the URL does not remove an independent encoding dimension.

Private or personalized output is a different problem. Do not treat Vary on Cookie or Authorization as a privacy policy. Choose appropriate cache directives and access controls for the content, then verify what each shared layer is permitted to store and serve. Vary describes selection among representations; it does not determine freshness or grant permission to cache private content.

The acceptance test is concrete: each request gets the representation the origin would choose for it, and an eligible repeat can reuse the right variant. Test the default response, each supported representation, and any conditional response separately. Fix the first layer where those observations diverge.

Source: RFC 9111: HTTP caching and Vary matching ↗

KEEP THESE THREE THINGS

Your next steps

  1. Use paired requests to distinguish wrong origin selection from wrong cached reuse.
  2. Verify Vary on the default response as well as negotiated and conditional responses.
  3. Keep variant selection separate from freshness, validation and permission to cache.

Sources & official resources

Linked resources checked on 2026-11-08. Technical behavior and provider guidance can change; check the documentation for the version you use.

About this guide and its recommendations

Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.

Suggest a correction →