← Lessons

quiz vs the machine

Silver1130

Networking

Cache Key And The Vary Header

What identifies a cached response and how Vary splits variants.

4 min read · intro · beat Silver to climb

What A Cache Key Is

A cache stores a response under a cache key. By default the key is the request URL, so two requests for the same URL share one cached entry.

When One URL Is Not Enough

Sometimes the same URL can return different content depending on the request. A page may differ by language or by whether the client accepts compression. If the cache ignored this, it could serve the wrong variant.

The Vary Header

The Vary response header lists request headers that change the response. The cache then includes those header values in the key.

  • Vary Accept Encoding: separate entries for compressed and plain responses.
  • Vary Accept Language: separate entries per language.
  • Each listed header multiplies the number of stored variants.

Designing The Key

CDNs let you customize the cache key beyond the URL.

  • Include query strings that matter and strip ones that do not.
  • Add specific cookies or headers only when they truly change content.
  • Keep the key narrow, because every extra dimension splits the cache and lowers hit rate.

A bloated key from a high cardinality header such as a user identifier can make the cache nearly useless.

Key idea

The cache key identifies a stored response, and Vary adds request header values to that key so distinct variants are cached separately without bloating the key needlessly.

Check yourself

Answer to earn rating on the learn ladder.

1. What does the Vary header do?

2. Why is varying on a per user header usually harmful to caching?

3. What is the default cache key for most responses?