SkillByAIOpen interactive version →

Lesson 20 / 25

Cache Keys and Purging

Design cache keys that maximise hit ratio and purge content precisely.

What makes two requests "the same"?

A CDN stores each response under a cache key, by default usually the scheme, host and path plus the query string. Everything in the key splits the cache: if ?utm_source=email and ?utm_source=ad are part of the key, the same page is cached many times and the hit ratio falls. Good key design removes irrelevant variation: strip or ignore tracking parameters, sort query parameters, normalise case, and include only headers or cookies that truly change the response (often none). Do not include cookies wholesale; a session cookie in the key makes every user's copy unique. For updates, CDNs support purging: by URL, by prefix or wildcard, or by tag (Cloudflare cache tags, Fastly surrogate keys, Akamai cache tags), where responses carry a header listing the entities they depend on and one purge clears them all. Purges take time to propagate and some providers limit or charge for them, so combine purges with sensible TTLs.

Tagging responses and purging by tag

The origin labels the response; one API call purges every page containing product 42.

HTTP/1.1 200 OK
Cache-Control: public, max-age=60, s-maxage=3600
Cache-Tag: product-42, category-7, homepage      # name differs by provider (e.g. Surrogate-Key)
Content-Type: text/html

# when product 42 changes, the application calls the CDN's purge API, e.g.
# POST /zones/{zone}/purge_cache   {"tags": ["product-42"]}
# every cached page tagged product-42 (product page, category page, home page) is purged

Labels on boxes in a warehouse

If every box carries labels for what it contains, a recall of one product means finding boxes by label rather than opening every box. Cache tags are those labels.

Quick check: Marketing links add different utm_ parameters to the same URL, and the CDN hit ratio drops. What is the best fix?

  • Disable the CDN
  • Set no-store on all pages
  • Shorten every TTL to one second
  • Exclude tracking parameters from the cache key
Answer

Exclude tracking parameters from the cache key — Removing irrelevant parameters from the key lets all variants share one cached object.