CodePark/ questions / Headers & HTTP caching
START PRACTICINGPRACTICE
Backend question · HTTP & API design › Headers & HTTP caching

What does the Vary header do, and what goes wrong if you forget it?

Vary lists request headers that also change the response. The cache then adds those header values to its cache key (the value it uses to find a stored response). If you forget it, a cache may serve one client's version to another client.

By default, a cache keys stored responses by method and URL only. Examples of Vary:

  • Vary: Accept-Encoding keeps the gzip and Brotli versions apart.
  • Vary: Accept-Language keeps the English and French versions apart.

What goes wrong without it, in a shared cache such as a CDN:

  • The CDN could send a Brotli body to a client that cannot decode Brotli.
  • The CDN could send a French page to an English user.
  • With CORS, you may copy the request's Origin into Access-Control-Allow-Origin. Then you need Vary: Origin. Without it, the browser blocks a cached response made for one origin when other origins receive it.

Do not vary on high-cardinality headers, meaning headers with very many different values, like User-Agent or Cookie. The cache splits into many tiny entries, and the hit rate collapses.

  • Vary adds request headers to the cache key.
  • Common Vary headers are Accept-Encoding, Accept-Language and Origin.
  • A missing Vary header makes the cache serve the wrong version.
  • Headers with very many values, like User-Agent, destroy the hit rate.