Vary Header Caching
The Vary header tells the cache that the response varies by the listed request headers, so two clients with different Accept-Encoding get separate cache entries rather than a wrong shared one.
Definition
The Vary header lists the request headers that influence the response representation, so that a cache stores a separate entry per combination of those header values — preventing a gzipped response from being served to a client that does not accept gzip, or a language variant to the wrong locale.
Context and scope
Applied in content-negotiated responses — encoding, language, device — where the cache must key on more than the URL to avoid serving the wrong variant.
Common misconceptions
- Vary: * disables caching — it does; it means the response varies by something unrepresentable, so every request goes to the origin
- Listing every header in Vary is safe — it is safe but it fragments the cache; over-listing reduces hit rate without improving correctness
Anti-patterns
- Omitting Vary when the response depends on Accept-Encoding, so a compressed variant is cached and served to a client that cannot decode it
- Varying on User-Agent, which has near-infinite values and explodes the cache into one entry per browser version
Related concepts
Authoritative source
What it is
The Vary header lists the request headers that influence the response representation, so that a cache stores a separate entry per combination of those header values — preventing a gzipped response from being served to a client that does not accept gzip, or a language variant to the wrong locale. Applied in content-negotiated responses — encoding, language, device — where the cache must key on more than the URL to avoid serving the wrong variant. The protocol’s semantics — safe versus unsafe, idempotent versus non-idempotent, cacheable versus non-cacheable — are contracts the client and intermediary rely on, and violating them breaks the web.
How it works
Headers carry the negotiation: content type, encoding, caching directives, and conditional request validators together let a client and server reach the cheapest correct response. Connection reuse eliminates handshake overhead; multiplexing removes head-of-line blocking; streaming avoids buffering the entire body. Each feature has a failure mode — keep-alive on a broken proxy, multiplexing with a misbehaving server — that must be detected and handled.
When to apply and pitfalls
Apply whenever a client and server communicate across a trust boundary the protocol already spans. The pitfall is treating HTTP as a transport and ignoring its semantics — POSTing a retrieval, marking a mutating request cacheable, or omitting the validator that would enable a 304. Intermediaries — CDNs, proxies — implement the standard literally, so semantic violations produce surprising behavior far from the origin.