Vary Header and Cache Keys
You'll learn how the Vary header controls when CDNs and caches store multiple versions of the same URL based on request differences.
The Problem: One URL, Many Responses
By default, a cache uses the URL as its cache key—the unique identifier for storing and retrieving content. But what if your server returns different content for the same URL based on request headers? For example:
- Mobile vs desktop users (based on
User-Agent) - Different languages (based on
Accept-Language) - Compressed vs uncompressed (based on
Accept-Encoding)
Without guidance, the cache might serve the wrong version—like delivering desktop HTML to a mobile user.
How Vary Works
The Vary header tells the cache: "Include these request headers in the cache key." This creates separate cache entries for different header combinations.
Vary: User-Agent
Now the cache key becomes: URL + User-Agent value. A request from Chrome and Safari would create two separate cache entries for the same URL.
Vary: Accept-Encoding, User-Agent
This creates cache keys like: URL + Accept-Encoding + User-Agent, multiplying cached versions further.
When to Use Vary
Use Vary when:
- Content actually differs based on request headers
- You serve device-specific versions
- You support content negotiation (language, encoding)
Avoid overusing Vary:
- Each added header fragments your cache, reducing hit rates
Vary: User-Agentis particularly problematic—thousands of different user agents exist- More variations = more storage, less efficient caching
Practical Consideration
Most sites use Vary: Accept-Encoding (safe—only a few values exist) but avoid Vary: User-Agent, instead using responsive design or device detection at the origin.
Key Takeaway:
The Vary header extends cache keys beyond just URLs, enabling correct multi-version caching—but each variation fragments your cache, so use it judiciously only when content truly differs.