Back to Cloudflare

Design Cache Rules Without Leaking Personalized Content

November 4, 2026 Updated November 5, 2026 Wasil Zafar 20 min read

Make cache keys and bypass policy match application behavior

Table of Contents

  1. The Cache Key Defines Who Shares a Response
  2. Origin Headers and Cache Rules Interact
  3. Cookies, Authentication, and Personalized Pages
  4. A Cache Policy for Public Pages and Private APIs
  5. Separate Public Asset Caching From Signed-In Responses
  6. Prove Two Test Users Cannot Receive Each Other's Content

The Cache Key Defines Who Shares a Response

At a theater coat check you get a numbered ticket, not a memory of your face. Two people holding the same number get the same coat.

A CDN cache is that coat room. It does not know who a visitor is; it looks up a string and returns whatever is stored under it.

Picture shop.example.com/account returning HTML with the signed-in user's email. Alice requests it; the edge asks the origin and stores it. Bob requests the same URL and receives Alice's page. The key never distinguished them.

Terms:

  • A cache key is the identifier used to store and find a response. Same key means same bytes.
  • A TTL (time to live) is how long a stored response stays fresh.
  • A hit returns a fresh copy without the origin; a miss asks the origin; a bypass skips the cache or refuses storage. The CF-Cache-Status header reports which one happened (cache responses).
  • Personalization is any part of a response that changes with the requester: name, email, cart, tenant, or permissions. The origin is your server behind Cloudflare.

The default key is short, and identity is not on it. Cloudflare builds it from the request URL plus a few headers (Cache keys):

Key inputDefault keyCache Rule key options
Full URL: scheme, host, path, queryIncludedQuery string can be ignored or sorted on any plan; specific parameters included or excluded on Enterprise
Origin request headerIncludedEnterprise: can be excluded from a custom key
Method-override and forwarding headersIncludedFixed; not removable
Cookie, Authorization, other headers, host, userNot includedEnterprise only
Device typeNot includedAll plans
Cache Deception ArmorNot applicableAll plans

Identity is either in the key or refused by policy. Those are the only two safe answers; the rest of this article chooses between them.

Ask three questions: may this request use the cache, what key identifies the object, and may this response be stored. A hit is safe only when every input that changed the body is in the key (Figure 1).

The Cache Key Defines Who Shares a Response
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    A["Alice: GET /account
Cookie: session=alice"] --> B{"Cache Rule matches?"} A2["Bob: GET /account
Cookie: session=bob"] -.->|"same key: cookie omitted"| C B -->|"Bypass"| O["Origin every time
CF-Cache-Status: DYNAMIC"] B -->|"Eligible"| C["Build key:
scheme + host + path + query"] C --> D{"Fresh entry?"} D -->|"yes"| H["HIT: stored response returned"] D -->|"no"| E["Fetch from origin"] E --> F{"Response storable?"} F -->|"no: private, no-store,
Set-Cookie, Vary: *"| X["BYPASS: nothing stored"] F -->|"yes"| S["Store under key for TTL"] S --> H classDef primary fill:#132440,color:#ffffff,stroke:#0b172b; classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a; classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f; classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420; classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f; class A,A2,O,E primary; class B,C,D,S secondary; class H,F ok; class X danger;

Figure 1 shows why the cache cannot detect personalized content; it only compares strings. Figure 2 shows the same failure as layers.

Two visitors collapse into one cache key and share one stored response Different session cookies produce the same default key, so Bob receives Alice's stored page. Same key, same stored response Alice GET /account Cookie: session=alice Bob GET /account Cookie: session=bob Cloudflare edge: one shared cache Cache key https:// shop.example.com /account cookie: not included One entry Alice's HTML alice@example.com TTL: 600 s HIT returned to both visitors

Origin Headers and Cache Rules Interact

A Cache Rule answers a request-time question: may this request use the cache, with what settings? The origin answers a response-time question: may this response be stored? Leaks happen when the answers disagree.

A rule can make a request eligible, but eligibility does not make a private response safe to share; a correct origin header cannot rescue a request a rule already made cacheable with an overridden TTL.

DecisionControlled byEvaluation pointExampleWhat it cannot do
May this request use the cache?Cache Rules, Cache eligibilityRequest phaseBypass /accountMake a no-store response storable
How long may the edge keep it?Cache Rules, Edge TTLRequest phase, applied to the responseOverride origin TTL to 600 sPreserve Set-Cookie; an override strips it
Which string identifies the object?Default key or custom Cache KeyRequest phaseIgnore utm_* parametersAdd headers, cookies, or host on non-Enterprise plans
May this response be stored?Origin Cache-Control, Set-Cookie, VaryResponse phaseCache-Control: private, no-storeForce caching after a rule bypassed the request
Which variants exist?Origin Vary plus Cache Rules VaryResponse phaseNormalize Accept-LanguageHelp if the origin never sends Vary

Eligibility is the request-phase answer; storage is the response-phase answer. Four responses to the same eligible /pricing request end in different places:

Origin responseEdge behaviorWhy
public, max-age=600, no cookieMISS, then HIT; identical bytesSharing is correct
private, no-storeBYPASSThe request was eligible, but the origin refused storage
public, max-age=600 plus Set-CookieMISS on every request; cookie preservedThe default TTL does not store a response that sets a cookie
The same response with Edge TTL Ignore cache-control headerStored, cookie stripped, HITA protected response becomes a shared one; if the body names a user, it is a leak

Order decides, because Cache Rules stack. Multiple rules can match one request; settings combine, and when two rules set the same setting, the later rule wins (Page Rules migration). Put broad rules first and narrow exceptions later: cache /assets/*, bypass the account area, then bypass any request with a session cookie.

Cache Rules ship on every plan: 10 on Free, 25 on Pro, 50 on Business, and 300 on Enterprise (Cache Rules).

resource "cloudflare_ruleset" "cache" {
  zone_id = var.zone_id
  name    = "asset and private lanes"
  phase   = "http_request_cache_settings"
  kind    = "zone"

  rules {
    ref         = "CR-1"
    description = "Asset lane: long edge TTL"
    expression  = "(starts_with(http.request.uri.path, \"/assets/\"))"
    action      = "set_cache_settings"
    action_parameters {
      cache = true
      edge_ttl {
        mode    = "override_origin"
        default = 86400
      }
      browser_ttl {
        mode    = "override_origin"
        default = 31536000
      }
    }
  }

  rules {
    ref         = "CR-2"
    description = "Public HTML lane: short edge TTL"
    expression  = "(http.request.uri.path eq \"/pricing\")"
    action      = "set_cache_settings"
    action_parameters {
      cache = true
      edge_ttl {
        mode    = "override_origin"
        default = 300
      }
    }
  }

  rules {
    ref         = "CR-3"
    description = "Private lane: bypass cache"
    expression  = "(starts_with(http.request.uri.path, \"/account\"))"
    action      = "set_cache_settings"
    action_parameters {
      cache = false
    }
  }
}
# Asset: expect MISS, then HIT with a rising Age.
curl -sSI https://lab.example.com/assets/app.js | grep -iE '^(cf-cache-status|age):'
curl -sSI https://lab.example.com/assets/app.js | grep -iE '^(cf-cache-status|age):'

# Private page: expect DYNAMIC, no Age, and a preserved cookie.
curl -sSI -H 'Cookie: session=alice' https://lab.example.com/account \
  | grep -iE '^(cf-cache-status|age|set-cookie):'

Figure 3 traces how origin headers and rule settings decide whether a response is stored.

Origin Headers and Cache Rules Interact
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    A["Cache Rule: Eligible for cache"] --> B["Request sent to origin"]
    B --> C{"Cache-Control present?"}
    C -->|"no-store or private"| D["BYPASS
unless Edge TTL overrides"] C -->|"public, max-age > 0"| E{"Set-Cookie present?"} C -->|"absent"| E E -->|"yes, default TTL"| F["Not stored
cookie preserved"] E -->|"yes, Edge TTL override"| G["Stored
cookie stripped"] E -->|"no"| H{"Vary: * or bypass?"} H -->|"yes"| I["BYPASS"] H -->|"no"| J["Stored under key for TTL"] G --> K["Risk: one user's body
served to another"] classDef primary fill:#132440,color:#ffffff,stroke:#0b172b; classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a; classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f; classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420; classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f; class B,C primary; class A,E,G,J secondary; class F,K ok; class D,H,I danger;

Cookies, Authentication, and Personalized Pages

Cookies carry identity; the default key cannot see them.

Bypass on a cookie name, not on any cookie. Match http.cookie contains "session=" and set Bypass cache; anonymous traffic stays cacheable. Bypassing on any cookie also works, but analytics cookies appear on almost every request and can disable caching site-wide.

The alternative is putting the cookie in the key, one entry per session. That option is Enterprise-only: cookie, header, host, and user components are not available on Free, Pro, or Business, which get the query-string controls, device type, and Cache Deception Armor (Cache keys).

Per-session keys cost more than they buy. They destroy reuse, and dashboard single-file purge cannot supply the cookie (Cache Rules).

resource "cloudflare_ruleset" "session_key" {
  zone_id = var.zone_id
  name    = "per-session cache key"
  phase   = "http_request_cache_settings"
  kind    = "zone"

  rules {
    ref         = "CR-4"
    description = "Enterprise: one entry per session"
    expression  = "(http.request.uri.path eq \"/app\")"
    action      = "set_cache_settings"
    action_parameters {
      cache = true
      cache_key {
        custom_key {
          cookie {
            include = ["session"]
          }
        }
      }
    }
  }
}
# Dashboard single-file purge cannot rebuild a cookie key.
# Purge by tag, host, or prefix instead.
curl -sS -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/purge_cache" \
  -H "Authorization: Bearer $CF_API_TOKEN" \
  -H "Content-Type: application/json" \
  --data '{"tags":["app-shell"]}'

What your plan can key on. Every plan can ignore or sort the query string, add device type, and enable Cache Deception Armor. Only Enterprise can key on specific query parameters, headers, cookies, host, or user features, so per-session keys are an Enterprise option (Cache keys).

Vary is not a partition

Cloudflare ignores Vary unless you configure the Cache Rules Vary setting, Vary for images applies, or the response varies on Accept-Encoding.

Vary: * always bypasses. Vary: Cookie without that setting partitions nothing (Vary).

Query strings are a third identity channel. The default key includes the whole query, so a campaign link like ?utm_source=newsletter creates its own entry: sharding, not a leak.

Ignoring the query string merges identities. With it on, ?user=alice and ?user=bob share one entry. Include and exclude lists are Enterprise-only; Ignore query string is on every plan.

Logged-in users are not special

The most consequential misconception is "Cloudflare does not cache pages for logged-in users." Cloudflare cannot know a user is logged in; it only reads what the response says. Set-Cookie protects you by default, but an explicit Edge TTL override removes that protection, strips the cookie, and stores the response — turning a private page into a shared one.

One unkeyed input is enough

Web Cache Deception dresses a private page as a static file. An origin treats /newsfeed/foo.jpg like the personalized /newsfeed; because the suffix is a cached extension by default, the edge stores the victim's page.

Cache Deception Armor compares the extension with the response content type and refuses the mismatch on every plan (Cache Deception Armor). An origin header or an Edge TTL override can still defeat it.

Cache poisoning is the same failure with a different input. Any value that changes the body but is absent from the key lets one visitor write an entry others read. The default key includes host-override headers to blunt host-header poisoning, custom keys should be paired with Normalize URLs to origin, and an unkeyed header must never be reflected into a cached response (Cache keys).

A Cache Policy for Public Pages and Private APIs

A workable policy has three lanes; authenticated content defaults to "do not share."

  • Immutable build assets. /assets/*, hashed filenames, and static extensions: Eligible for cache, a long edge TTL such as 30 days, a one-year browser TTL, and Ignore query string only if the query never selects a different file.
  • Public HTML that is identical for everyone. Marketing, docs, and status pages: eligible with a short edge TTL and stale-while-revalidate, cookie-free. HTML is not cached by default, so this lane needs an explicit path allowlist, never a catch-all.
  • Authenticated pages and APIs. The account area, /app/*, and /api/me: Bypass cache, and the origin returns a private, no-store response. No Edge TTL override, no cookie stripping, no session value in a custom key.

Ordering follows the same logic: broad assets first, account bypasses second, the session-cookie bypass last. Later matching rules win, so protections belong at the end; a catch-all "cache everything" rule added last undoes every exception above it.

For a private API, private, no-store is the cheapest correct default. If a response is identical for many users, cache it only after confirming that no header, cookie, or token changes the body; if it varies by tenant, use a Worker with an explicit tenant key rather than a wider CDN key.

Every protection has a price. Session-cookie bypasses cost hit ratio only for sessions; any-cookie bypasses can cost most of it. Custom keys raise granularity but cost purge simplicity: dashboard single-file purge cannot reproduce a key built from headers or cookies, so use API purge with all key values, or purge by tag, host, or prefix (Cache Rules).

Changing Vary does not purge old entries; requests miss and refill until they expire.

Figure 4 shows the shape: the left lane carries two kinds of content.

Before and after splitting one cache lane into asset, public, and private lanes One eligible rule makes every visitor share the account page; after the split, only assets and public pages share. Before: one lane Alice and Bob → GET /account Eligible for cache + Edge TTL key: /account (no cookie) One entry: Alice's HTML Bob receives Alice's page After: three lanes /assets/* hashed files shared long TTL /pricing public HTML shared 5 min TTL /account session cookie bypass origin only One lane per trust level.

Separate Public Asset Caching From Signed-In Responses

This exercise is design-only. It separates a cacheable asset from a personalized page on one controlled hostname, then proves two identities never share it. Nothing below was executed, so the observations are documented expectations, not measurements.

Prerequisites. A domain on Cloudflare with a proxied record; the Free plan suffices, and it includes Cache Rules with 10 rules. An origin you control — a small server, container, or PaaS app — returns the fixture. Use two invented identities and no real data; the examples use lab.example.com.

Guided exercise

Separate public asset caching from signed-in responses

Fixture

RouteOrigin responseCache Rule
/assets/app.jsFixed JavaScript, Content-Type: application/javascriptEligible, one-day edge TTL, ignore query string
/pricingFixed HTML, Cache-Control: public, max-age=300, no cookieEligible, 300-second edge TTL
/accountHTML naming the session user, private, no-store, echoes the identityBypass cache

Steps

  1. Deploy the asset rule, the /pricing rule, then the /account bypass last.
  2. Request the asset and /pricing twice each; expect a miss, then a hit, with Age on the second response.
  3. Request /account as Alice and as Bob; both responses must keep the cookie and name a different user.
  4. Read the decision in the Rules simulator or Cloudflare Trace, which exposes the generated cache key.

Expected results

RouteStatusHeaders and body
/assets/* and /pricingMISS, then HITAge rises; bodies byte-identical
/accountDYNAMICNo Age; cookie preserved; bodies differ

Failure check. Add a temporary rule after the bypass rule that makes the private route eligible with an Edge TTL override at 60 seconds. Expect a hit, no cookie, and Bob receiving Alice's body.

Record it, delete the rule, purge, then repeat the probe against /account/foo.jpg with Cache Deception Armor enabled.

Cost and cleanup. The Free plan covers Cache Rules and request volume is negligible; the cost is the domain, origin hosting, and roughly 30 to 45 minutes. Delete the rules and the temporary leak rule, purge the lab URLs, remove the test record or origin app, discard the invented sessions, and confirm the private route returns a dynamic response.

Run the probes with curl. Each comment states the documented expectation, not a measured result:

# Baseline: the private route must never be stored.
curl -sSI -H 'Cookie: session=alice' https://lab.example.com/account \
  | grep -iE '^(cf-cache-status|age|set-cookie):'

# Asset: expect MISS, then HIT with a rising Age.
curl -sSI https://lab.example.com/assets/app.js | grep -iE '^(cf-cache-status|age):'
curl -sSI https://lab.example.com/assets/app.js | grep -iE '^(cf-cache-status|age):'

# Public HTML: the same MISS-then-HIT pattern, shared by both identities.
curl -sSI https://lab.example.com/pricing | grep -iE '^(cf-cache-status|age):'

# Deception probe: an HTML body behind a .jpg suffix must not be a HIT.
curl -sSI https://lab.example.com/account/foo.jpg | grep -i '^cf-cache-status'

Prove Two Test Users Cannot Receive Each Other's Content

Pass/fail evidence comes from the response, not the dashboard. For each protected route, send requests as two identities and record the body, cache status, Age, and Set-Cookie.

  • Pass: both requests return DYNAMIC or BYPASS, neither carries Age, Set-Cookie is intact, and the bodies differ in the personalized field.
  • Pass: the public asset returns MISS then HIT, carries Age on the hit, and both bodies are byte-identical.
  • Fail: a HIT on /account, Age on a personalized response, a missing Set-Cookie, or two identities receiving the same body.
  • Inconclusive: both requests are MISS with different bodies but no rule is deployed; that may only mean the origin sends private.

Self-check: three edge cases, with explanations.

  1. The login page sets a cookie, the rule says Eligible for cache, yet every request is a MISS. Why? With the default edge TTL, Cloudflare preserves Set-Cookie and refuses storage. An Edge TTL override would strip the cookie and cache it — the wrong fix for a personalized page (Set-Cookie and cache).
  2. The origin sends Vary: Cookie. Is the cache partitioned now? Not necessarily. Cloudflare does not consider Vary by default; the Cache Rules Vary setting must be configured, and even then Vary: Cookie would shard per session rather than protect a shared page (Vary).
  3. Why did campaign links with ?utm_source= lower the hit ratio? The default key includes the whole query, so each variant is a separate entry. That is sharding, not a privacy bug — but ignoring query strings globally can merge content-selecting parameters.

Unresolved limitations. Documentation was verified on 2026-11-04 against the pages below; no hosted test, plan-specific test, or measured hit ratio is claimed, and no product versions were tested because no lab ran.

Scope is the edge cache only. Browser caches, service workers, origin proxies, and Worker caches are separate layers with their own keys. Enterprise accounts that disable Origin Cache Control change the Authorization behavior above.

Key and Vary changes carry purge consequences. Custom keys built from headers or cookies can make dashboard single-file purge ineffective; Vary changes do not purge existing entries, and Vary: * always bypasses. Cache Rules also interact with other rule phases, so use the simulator and Trace on the zone.

References: Cloudflare Cache, Cache Rules, Cache Rules settings, Cache keys, Vary, Cache responses, Origin Cache Control, Cache Deception Armor, Set-Cookie and cache, and Rules simulator.

Next in the Series

In Reduce Origin Load With Smart Shield and Resilient Delivery, we'll explore Connect cache hierarchy, routing, health, and traffic admission.