HTTP caching headers and cache keys
Read Cache-Control the way a shared cache does: s-maxage, CDN-Cache-Control, heuristic freshness and the stale-while-revalidate and stale-if-error extensions; design cache keys and Vary so variants neither split nor merge; see why Authorization and Set-Cookie need care; and read what a cache did from Cache-Status.
Contentsand lesson path
On this page
- Why it matters
- How long a shared cache may reuse a response
- Cache keys and Vary
- Authorization, Set-Cookie and poisoned entries
- Reading what a cache did: Cache-Status and Age
- Check your understanding
- Apply it
- Review prompt
Lessons of CDN & Edge Delivery
- How a CDN request is served: edge, tiers and origin Concept · 20 min
- HTTP caching headers and cache keys Concept · 20 min
- Invalidation, versioned assets and signed URLs Concept · 15 min
- Putting a CDN in front of an origin and reading cache status Lab · 25 min
- Offload ratio, egress cost and edge compute Worked example · 20 min
- Edge delivery check Knowledge check · 6 questions
What you will learn
- Choose pull or push CDN delivery and set Cache-Control, cache keys and TTLs for static, media and personalized responses.
Prerequisites: Caching Strategies
01. Why it matters
Your origin talks to every cache on the path through response headers: the browser's own cache, which serves one user (a private cache), and the CDN's edges and tiers, which serve everyone (shared caches). The CDN cannot see what a response means, only the URL, the headers and its configuration. A wrong header either wastes the CDN or shows one user's response to another.
Invalidation, TTLs, HTTP revalidation and the staleness budget introduced no-cache, no-store, private, public, ETags and the 304 response. This lesson looks at headers from the shared cache's side, using HTTP Caching (RFC 9111), HTTP Semantics (RFC 9110) and four smaller RFCs.
03. Cache keys and Vary
The cache key is what a cache uses to find a stored response. RFC 9111 section 2 says it contains at least the request method and the target URI; since most caches store only GET responses, the key is usually the full URL, query string included. CDNs let you drop query parameters from the key or add a header or cookie value to it. A good key has one entry per distinct response; it can go wrong in two directions:
- Too wide: the key holds something that does not change the response, such as
?utm_source=newsletter, so one page is stored many times and the hit ratio falls. This is a split. - Too narrow: the key leaves out something that does change the response, so different responses share one entry and users get the wrong one. This wrong merge is the more dangerous mistake. You will cause both in lesson 4.
The origin declares extra inputs with Vary. A response with Vary: Accept-Encoding tells caches that the Accept-Encoding request header helped choose it (RFC 9110 section 12.5.5), and a cache must not reuse it, without asking the origin, for a request whose value differs (RFC 9111 section 4.1). Raw header values vary a lot. Vary: User-Agent creates a copy for almost every browser version, and Vary: Cookie one for almost every user. Vary: * never matches, so every request goes forward. The usual fix is to normalise at the edge: turn a long header into one of a few values, such as avif, webp or jpeg for images, and key on that value. CloudFront lists this as a typical job for edge functions.
04. Authorization, Set-Cookie and poisoned entries
Authorization. RFC 9111 section 3.5 says a shared cache must not reuse a response to a request that carried Authorization, unless the response contains public, s-maxage or must-revalidate. The protection disappears when someone adds s-maxage=30 to an authenticated endpoint "to take load off the API": with a URL-only key, the first caller's private response goes to every caller for 30 seconds.
Set-Cookie. Section 7.3 notes that Set-Cookie does not stop caching: a cacheable response that sets a cookie can be stored and replayed, and a stored session cookie handed to other users can sign them in as someone else. CDNs differ: Cloudflare, for example, does not cache such a response when it follows the origin's Cache-Control (the default on its Free, Pro and Business plans), but removes the cookie and caches the response in some other configurations. Do not rely on any of these defaults: mark responses that set cookies or contain personal data private or no-store, and keep cookies off cacheable URLs.
Section 7.1 warns about cache poisoning: getting a harmful response stored so that a shared cache serves it to many users. One common route in practice is an input that changes the response but is not in the key, such as a forwarding header used to build links. An attacker sends a crafted value once, and everyone with the same key gets the result. The same gap leaks data between customers when a multi-tenant app picks the tenant from a header or cookie the key ignores. Put every input that changes the response into the key, or stop the origin from using it.
The script below applies these rules to nine typical responses. It is a teaching subset of RFC 9111 for shared caches, not a complete implementation, and needs only Python 3.12.
"""cache_lint.py: what may a shared cache, such as a CDN, do with a response?
A teaching subset of RFC 9111 for shared caches, plus warnings for common risks.
"""
import textwrap
SHARED_OK = {"public", "s-maxage", "must-revalidate"} # RFC 9111 section 3.5
def directives(value: str) -> dict[str, str]:
found = {}
for part in value.split(","):
name, _, arg = part.strip().lower().partition("=")
if name:
found[name] = arg.strip('"')
return found
def verdict(resp: dict[str, str], request_has_auth: bool = False) -> str:
cc = directives(resp.get("Cache-Control", ""))
if "no-store" in cc:
return "do not store (no-store)"
if "private" in cc:
return "do not store in a shared cache (private)"
if request_has_auth and not SHARED_OK & cc.keys():
return "do not store: the request carried Authorization (RFC 9111 3.5)"
if resp.get("Vary", "").strip() == "*":
return "storing is pointless: Vary: * never matches a later request"
if "no-cache" in cc:
text = "store, but revalidate with the origin before every reuse"
elif "s-maxage" in cc:
text = f"fresh here for {cc['s-maxage']} s (s-maxage overrides max-age)"
elif "max-age" in cc:
text = f"fresh for {cc['max-age']} s"
elif "Last-Modified" in resp:
text = "no explicit lifetime: the cache may choose a heuristic one"
else:
text = "no lifetime and no validator: many caches will not keep it"
if "stale-while-revalidate" in cc:
text += f"; up to {cc['stale-while-revalidate']} s stale while refreshing"
if "stale-if-error" in cc:
text += f"; up to {cc['stale-if-error']} s stale if the origin fails"
if "Vary" in resp:
text += f"; one copy per value of {resp['Vary']}"
if "Set-Cookie" in resp:
text += "; WARNING: the stored Set-Cookie may reach other users"
return text
CASES = [
("hashed JS bundle", {"Cache-Control": "public, max-age=31536000, immutable"}),
("HTML page", {"Cache-Control": "no-cache", "ETag": '"r42"'}),
("category page", {"Cache-Control": "max-age=0, s-maxage=600"}),
("price list API", {"Cache-Control": "public, max-age=60, "
"stale-while-revalidate=30, stale-if-error=600"}),
("account JSON", {"Cache-Control": "max-age=60"}, True),
("product page", {"Cache-Control": "public, max-age=300",
"Set-Cookie": "sid=8f2c41; Secure; HttpOnly"}),
("search results", {"Cache-Control": "private, max-age=30"}),
("old PDF", {"Last-Modified": "Tue, 01 Sep 2026 10:00:00 GMT"}),
("photo, AVIF or JPEG", {"Cache-Control": "public, max-age=86400",
"Vary": "Accept"}),
]
for label, resp, *auth in CASES:
print(textwrap.fill(f"{label}: {verdict(resp, *auth)}", width=80,
subsequent_indent=" ", break_on_hyphens=False))python3 cache_lint.pyhashed JS bundle: fresh for 31536000 s
HTML page: store, but revalidate with the origin before every reuse
category page: fresh here for 600 s (s-maxage overrides max-age)
price list API: fresh for 60 s; up to 30 s stale while refreshing; up to 600 s
stale if the origin fails
account JSON: do not store: the request carried Authorization (RFC 9111 3.5)
product page: fresh for 300 s; WARNING: the stored Set-Cookie may reach other
users
search results: do not store in a shared cache (private)
old PDF: no explicit lifetime: the cache may choose a heuristic one
photo, AVIF or JPEG: fresh for 86400 s; one copy per value of AcceptNote the product page: nothing in HTTP stops a CDN from storing it, cookie and all. The old PDF has no Cache-Control, yet may be cached for a lifetime the cache chooses. The photo gets one stored copy per distinct Accept value.
05. Reading what a cache did: Cache-Status and Age
When a response looks wrong, ask each cache what it did. Age (RFC 9111 section 5.1) gives the seconds since the origin produced or last validated the response. Cache-Status (RFC 9211) is a standard header for the rest. Its value is a list with one member per cache: the first member is the cache closest to the origin, the last the one closest to the user. Each member names a cache and adds parameters:
hitmeans the cache answered from storage without going forward.fwd=says why it went forward:uri-miss(nothing stored for the URL),vary-miss(stored, butVarydid not match),stale,request(the request asked to bypass the copy), and a few more.fwd-status=304shows that the next server (the origin or a parent cache) confirmed the stored copy, while the user still received a 200.ttlis the remaining freshness in seconds,storedsays whether the response was kept, andkeyshows the cache key.
For example, Cache-Status: EdgeCache; fwd=stale; fwd-status=304 means the edge held a stale copy, asked the next server, and was told with a 304 that the copy was still current, so it served the copy it had. Many CDNs use their own header instead, such as Cloudflare's cf-cache-status, and some send these headers only in a debug mode, because RFC 9211 section 6 warns that they help attackers probe what is cached.
06. Check your understanding
07. Apply it
For the practice project, write a header plan before you deploy:
- HTML:
Cache-Control: no-cachewith anETag, so every reuse is checked. - Fingerprinted CSS, JavaScript and images:
Cache-Control: public, max-age=31536000, immutable. - Anything that sets a cookie or depends on who is asking:
privateorno-store. - The cache key for each path: which query parameters and headers really change the response?
After deploying, copy the real response headers from curl -s -D - -o /dev/null <url> into a new case in cache_lint.py and check that the verdicts match your plan.
08. Review prompt
Without looking back, answer in your own words:
- In what order does a shared cache look for a freshness lifetime, and what happens when there is none?
- What do
stale-while-revalidateandstale-if-erroradd to the oldest data a user can see? - Give one example of a cache key that splits entries and one that wrongly merges them.
- When may a shared cache reuse a response to a request with
Authorization, and why isSet-Cookieon a cacheable response risky? - In a
Cache-Statuslist with two members, which cache does the first member describe?
References
- RFC 9111: HTTP Caching (sections 2, 3.5, 4.1, 4.2, 5.2.2 and 7)
- RFC 9110: HTTP Semantics (section 12.5.5, Vary)
- RFC 9211: The Cache-Status HTTP Response Header Field
- RFC 5861: HTTP Cache-Control Extensions for Stale Content
- RFC 9213: Targeted HTTP Cache Control (CDN-Cache-Control)
- RFC 8246: HTTP Immutable Responses
- HTTP caching (MDN)
- Head requests and Set-Cookie headers (Cloudflare Cache documentation)
- Differences between CloudFront Functions and Lambda@Edge
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.