Cache key

On this page 7

A cache key is the identifier that a cache derives from an incoming request to decide whether a stored response can be reused. In content delivery across the Internet, every edge cache, origin shield and reverse proxy computes a key for each request, looks it up in its storage and either serves the matching object as a cache hit or forwards the request to the origin server as a cache miss.

The design of the key is a balance between reuse and correctness. A key that includes too little information can serve the wrong content to the wrong user, while a key that includes too much splits identical content into many copies and lowers the cache hit ratio. Getting this balance right is one of the most consequential configuration decisions in any CDN deployment.

How a cache key is built from a request

A cache key is built by concatenating selected request attributes into a string, which the cache then usually hashes into a fixed-length value for fast lookup. The default key on most CDNs combines the scheme, host and path, and often the full query string, because these together identify a resource as described by the URL semantics of HTTP.

Beyond the URL, a cache can add secondary key components. The HTTP specification for caching, RFC 9111, defines the Vary response header as the standard mechanism: when the origin answers with Vary: Accept-Encoding, the cache must store separate variants for each distinct value of that request header. Many CDNs also let operators add headers, cookies, device classes or geolocation to the key through configuration rather than through Vary.

The table below lists the components most often found in a cache key and what each one distinguishes.

ComponentExample valueWhat it distinguishes
SchemehttpsSecure and plain HTTP copies
Hoststatic.example.comDifferent sites on shared infrastructure
Path/img/logo.pngIndividual resources
Query string?w=800&fmt=webpResource variants and parameters
Request headerAccept-Encoding: brCompressed or uncompressed variants
Cookie valuelang=deLanguage or user segment
Device or geo classmobile, EUDevice-specific or regional content
Common cache key components

Cache key normalization and its effect on hit ratio

Cache key normalization is the practice of rewriting request attributes into a canonical form before the key is computed, so that requests for the same content produce the same key. Without normalization, trivial differences such as parameter order, letter case in the host or a tracking parameter create duplicate cache entries that each require a separate origin fetch.

Typical normalization steps include sorting query parameters, removing marketing parameters such as utm_source, lowercasing the host, collapsing Accept-Encoding values into a small set such as br, gzip and identity, and grouping hundreds of User-Agent strings into two or three device classes. Each step reduces key cardinality, which is the number of distinct keys a cache must store for the same underlying content.

The following table shows how specific normalization rules change the number of variants for a single resource.

RuleVariants beforeVariants afterMain benefit
Sort query parametersMany orderingsOne orderingRemoves ordering duplicates
Strip tracking parametersOne per campaignOneHigher reuse of landing pages
Normalize Accept-EncodingDozens of stringsTwo or threeFewer compressed variants
Classify User-AgentThousands of stringsTwo or three classesPrevents key explosion
Lowercase hostTwo or moreOneRemoves case duplicates
Effect of normalization on key cardinality

Normalization must stay semantically safe. Stripping a parameter that the origin actually uses to select content, such as a page number or an image width, causes the cache to return one variant for all requests, which is a correctness failure rather than an optimization.

The cache key decides which object a request maps to, while neighboring concepts decide how long that object lives, how it is grouped and how it is removed. Confusing these roles leads to misconfiguration, for example trying to fix stale content by changing the key rather than by purging or adjusting freshness rules.

ConceptQuestion it answersRelation to the cache key
Cache keyWhich stored object matches this requestPrimary lookup identifier
Vary headerWhich request headers create variantsAdds header values to the key
Cache-ControlHow long and where an object may be storedGoverns objects stored under a key
Cache tagWhich objects belong to one logical groupGroups many keys for purging
Cache purgeHow objects are removed before expiryTargets one key, a prefix or a tag
Request collapsingHow concurrent misses are mergedMerges requests sharing one key
How the cache key relates to neighboring terms

Request collapsing shows why key design matters beyond hit ratio. When many clients request the same key during a miss, the cache sends only one request to the origin and holds the others until the response arrives; a key that is needlessly unique for each user defeats this protection and exposes the origin to load spikes.

Designing a cache key in practice

A sound cache key includes every attribute that changes the response and excludes every attribute that does not. In practice, engineers start from the URL, inspect which request headers, cookies and parameters the origin really reads, and then add exactly those to the key, either through Vary or through explicit CDN key rules.

Content typeRecommended keyReason
Versioned static assetsHost and path onlyFile name already encodes the version
Responsive imagesPath, width and formatEach size and format is distinct
Localized HTML pagesPath and language valueContent differs by language
API responses with filtersPath and normalized queryParameters select the data
Personalized pagesNot cached or edge-assembledPer-user keys give no reuse
Recommended key choices for typical content

For mixed pages, a common pattern is to cache the shared shell under a broad key and assemble personalized fragments separately, for example with Edge Side Includes or client-side requests. This keeps the high-traffic portion under a single reusable key while the small personalized part bypasses the cache.

Risks and common cache key mistakes

The most serious cache key failure is web cache poisoning, in which an attacker sends a request with an unkeyed input, such as an X-Forwarded-Host header, that the origin reflects into the response. Because that header is not part of the key, the poisoned response is stored under a normal key and served to every later visitor.

  • Key too narrow: private or localized content leaks between users when cookies or authorization are ignored.
  • Key too broad: including session cookies or full User-Agent strings drives the hit ratio toward zero.
  • Unkeyed inputs: headers the origin reads but the key omits enable poisoning and inconsistent responses.
  • Inconsistent tiers: an edge cache and an origin shield using different keys cause unexpected misses in tiered caching.
  • Vary: User-Agent: this single header can create thousands of variants and should be replaced by device classification.

A reliable safeguard is to treat the key as part of the application contract: document which inputs the origin uses, align the CDN key with that list, and test with crafted headers to confirm that unkeyed inputs do not change responses.

The simple explanation

Think of a cache as a cloakroom and the cache key as the ticket number. When a request arrives, the cache reads its ticket and looks for the coat with the same number. If it finds one, it hands it over immediately. If not, it fetches the item from the original source and stores it for next time.

The trick is deciding what goes on the ticket. If the ticket is too simple, two different people might receive the same coat. If it is too detailed, nobody ever matches and every coat must be fetched again. A good cache key is just detailed enough to keep different content apart and no more.

How it is used in practice

An online retailer serves product pages and images through a CDN and notices that its hit ratio for images is only 41 percent. Analysis of the logs shows that every marketing email adds utm_campaign and utm_medium parameters to image links, and that the parameter order varies between email tools. Each combination produces a separate cache key, so the same product photo is fetched from the origin dozens of times.

The operations team adds rules that strip tracking parameters and sort the rest before the key is computed, and keeps only the w and fmt parameters that the image service actually uses. Within a week, the image hit ratio rises above 90 percent, origin egress traffic falls by roughly three quarters and median image load time drops noticeably for shoppers far from the origin data center.