Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Concept · 20 min · revision 1

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

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.

02. How long a shared cache may reuse a response

A stored response is fresh while its age is lower than its freshness lifetime; after that it is stale, and it should be revalidated before reuse. RFC 9111 section 4.2.1 gives the order in which a cache finds the lifetime, using the first rule that matches:

  1. In a shared cache, s-maxage (section 5.2.2.10). Browsers ignore it, so Cache-Control: max-age=0, s-maxage=600 lets the CDN reuse a page for ten minutes while every browser checks with the CDN each time. s-maxage also tells a shared cache not to serve the response stale without revalidating it first.
  2. max-age (section 5.2.2.1), for every other cache.
  3. The Expires header minus the Date header.
  4. Otherwise a heuristic lifetime (section 4.2.2). A 200 response with no lifetime at all may still be stored, and the cache may choose a lifetime itself; the RFC mentions 10% of the time since Last-Modified as a typical setting. So a file last changed 100 days ago may be reused for about 10 days: missing headers do not mean "not cached".

Three extensions change this picture. immutable (RFC 8246) promises that the response will not change while fresh, so browsers skip revalidation on reload; use it only on versioned URLs. CDN-Cache-Control (RFC 9213) uses the same directives as Cache-Control, written as a Structured Field (a stricter standard header syntax, RFC 9651), but is aimed at CDNs: a CDN that implements it uses it instead of Cache-Control (section 2.2), so the CDN can keep a long lifetime that you end with purges while browsers keep a short one. And the two stale directives of RFC 5861 widen what may be served:

  • stale-while-revalidate=30 (section 3) lets a cache serve a stale copy for up to 30 more seconds while it revalidates in the background, so no user waits for the origin.
  • stale-if-error=600 (section 4) lets a cache serve a stale copy for up to 600 more seconds when the origin cannot be reached or answers 500, 502, 503 or 504.

Both directives are part of your staleness contract: with max-age=60, stale-while-revalidate=30, users can see data up to 90 seconds old, and up to 660 seconds during an origin failure with stale-if-error=600.

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.

Python · cache_lint.py
"""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))
Terminal
python3 cache_lint.py
Expected output
hashed 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 Accept

Note 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:

  • hit means the cache answered from storage without going forward.
  • fwd= says why it went forward: uri-miss (nothing stored for the URL), vary-miss (stored, but Vary did not match), stale, request (the request asked to bypass the copy), and a few more.
  • fwd-status=304 shows that the next server (the origin or a parent cache) confirmed the stored copy, while the user still received a 200.
  • ttl is the remaining freshness in seconds, stored says whether the response was kept, and key shows 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

Practice check · 3 questions

Headers and keys from the shared cache's side

Each question is about a CDN that follows RFC 9111 and keys on the full URL. Pick the best answer.

Q1. A team adds `Vary: User-Agent` to all its CSS responses "just in case some browser needs different styles". The CSS is identical for every browser. What happens at the CDN?
Q2. To cut load, an API adds `Cache-Control: s-maxage=30` to `GET /v1/me`, which returns the caller's profile. Callers send `Authorization: Bearer <token>`. What happens?
Q3. A response carries `Cache-Status: OriginCache; hit; ttl=40, "ExampleCDN"; fwd=uri-miss; stored`. Which reading is right?
Practice only: not graded, not saved, not evidence.

07. Apply it

For the practice project, write a header plan before you deploy:

  1. HTML: Cache-Control: no-cache with an ETag, so every reuse is checked.
  2. Fingerprinted CSS, JavaScript and images: Cache-Control: public, max-age=31536000, immutable.
  3. Anything that sets a cookie or depends on who is asking: private or no-store.
  4. 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:

  1. In what order does a shared cache look for a freshness lifetime, and what happens when there is none?
  2. What do stale-while-revalidate and stale-if-error add to the oldest data a user can see?
  3. Give one example of a cache key that splits entries and one that wrongly merges them.
  4. When may a shared cache reuse a response to a request with Authorization, and why is Set-Cookie on a cacheable response risky?
  5. In a Cache-Status list with two members, which cache does the first member describe?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check