Lesson 4 of 9 · 26m
Cache Keys, TTLs, and Invalidation Without Regret
Design cache keys around intentional variation, choose TTLs from business risk, and use purge strategies that do not collapse under real traffic.
Caching is easy in demos and unforgiving in production because every mistake becomes consistency behavior. I have seen one malformed cache key serve a signed-in customer dashboard to anonymous traffic, and I have seen another include a random analytics header that reduced the hit ratio to almost zero. Cache design is not “turn on caching.” It is contract design.
The cache key is the privacy boundary
A cache key says: all requests matching this shape may share a response. Therefore the key must include every dimension that changes the representation and exclude dimensions that do not.
include deliberately:
host
path
relevant query parameters
content negotiation
language or market
device class only when output truly differs
usually exclude:
cookies unless explicitly needed
analytics headers
irrelevant tracking query parameters
unstable ordering of equivalent query paramsIf personalized output is cached under a shared key, you have a data leak. If static output varies by random tracking headers, you have no cache. Both are architecture failures.
Normalization is cache correctness
Normalize before lookup. Sort query parameters, remove tracking noise, canonicalize case where appropriate, and decide which cookies matter:
const url = new URL(request.url)
const keep = ["page", "sort", "lang"]
const params = new URLSearchParams(
[...url.searchParams]
.filter(([key]) => keep.includes(key))
.sort(([a], [b]) => a.localeCompare(b)),
)
const key = new Request(`${url.origin}${url.pathname}?${params}`, request)The exact policy is application-specific. What is not optional is making it explicit.
TTL is a business decision encoded in seconds
A product listing might tolerate 60 seconds of staleness. Inventory cannot blindly do the same. Security policy cannot. Use response directives intentionally:
Cache-Control: public, max-age=60, stale-while-revalidate=300
Cache-Control: private, no-store
Cache-Control: public, max-age=31536000, immutableImmutable caching is for content-addressed assets such as app.7f31c9.js, not for HTML whose URL remains stable while content changes. no-store and no-cache are not synonyms: no-store means do not retain; no-cache means revalidate before reuse.
Invalidation strategies scale differently
There are three practical approaches:
short TTL simple, eventually consistent, low purge dependency
explicit purge precise, operationally fragile at scale
versioned object names robust for assets, poor fit for user-visible mutable URLsPurging by tag or prefix can be effective, but purges are control-plane operations with propagation time and rate limits. Do not design a hot user write path that depends on instant global purge completion.
Stampede protection matters
When a popular object expires, hundreds of concurrent requests can miss together and hammer the origin. This is a cache stampede. Use stale-while-revalidate, request coalescing, or lock-style origin behavior where available:
Cache-Control: public, max-age=30, stale-while-revalidate=120The stale response keeps users fast while one revalidation path refreshes the object. That is often better than pretending freshness is absolute.
Field notes
- Never cache
Set-Cookieresponses unless you deeply understand the platform behavior and the response semantics. Session creation and cache reuse are a dangerous pair. - Vary on as little as possible. Every variation multiplies cache fragmentation.
- Log or expose cache status in controlled internal testing; debugging hit ratio without visibility is astrology.
- Treat query parameters from marketing campaigns as hostile cache fragmentation until explicitly normalized.
Was this lesson helpful?