Caching: every layer, and how a change propagates¶
The worker is cache-first. A given response can be served from any of several independent cache layers, each with its own scope, lifetime, and key. Knowing which layer answered a request -- and which one can hold stale data -- is the key to reasoning about freshness and purge.
There are two families of cache to keep separate in your head:
- the site-settings cache chain (memMap -> Cache API -> KV -> origin), read
once per request in
resolveSite; and - the rendered-page caches (edge Cache API + KV envelope), plus the
Cloudflare edge cache of the worker's own HTTP responses driven by the
cache-controlheader the render emits.
Beneath both sits the cf subrequest cache on every call the worker makes
to cms-api. Getting a content or settings change fully live means clearing the
right ones in the right order -- see
the propagation recipe.
Source:
src/site/resolve.ts,src/cache/index.ts,src/cms/client.ts,src/assets/serve.ts,src/admin/purge.ts,src/index.ts.
The layers at a glance¶
| Layer | What it caches | Scope | TTL | Key | Source |
|---|---|---|---|---|---|
| L1 isolate memMap | Site settings | One Worker isolate (in-memory) | None -- lives as long as the isolate | host |
src/site/resolve.ts |
| L2 Cache API | Site settings | Per Cloudflare PoP | 300 s (CACHE_API_TTL) |
synthetic https://cms-cf-worker.internal/site/<host> |
src/site/resolve.ts |
| L2 Cache API | Rendered pages | Per Cloudflare PoP | per-descriptor ttl |
https://<host><pathname><search> |
src/cache/index.ts |
| L3 KV | Site settings (fallback) | Global (KV) | 86400 s (KV_TTL, 24 h) |
site:<host> |
src/site/resolve.ts |
| L3 KV | Page envelopes (fallback) | Global (KV) | 7 days | <host>:<pathname> |
src/cache/index.ts |
L4 cf subrequest cache |
cms-api responses (settings, CSS, page data) | Cloudflare edge | 30 s default; 86400 s for CSS | subrequest URL (incl. ?v=) |
src/cms/client.ts, src/assets/serve.ts |
| CF edge (CDN) | Worker HTTP responses | Cloudflare edge, per colo (see Tiered Cache) | s-maxage=3600, stale-while-revalidate=86400 |
request URL (tracking params normalized) | DOC_CACHE_CONTROL in src/index.ts |
The two L2 rows and the two L3 rows are the same physical store (Cache API and
KV respectively) holding two different kinds of value. The last row (CF edge) is
Cloudflare's CDN cache of the worker's own responses, driven by the
cache-control header each render emits -- distinct from the explicit Cache API
puts the worker makes.
Making a CMS change visible: the propagation recipe¶
/__cms/purge alone is NOT enough to fully publish a change
POST /__cms/purge clears only the KV tiers (page envelopes + the
site:<host> settings entry) and the best-effort Cache API settings entry.
It does not clear the isolate memMap (L1) of already-warm workers, and it
does not clear the Cloudflare edge cache of the worker's own rendered
HTML responses. A change can be live in the CMS and in KV yet still served
stale from a warm isolate or from the CF edge.
To make a cms-api change (settings, a style/CSS swap, a template edit, a new page descriptor) visible everywhere, now, do all three, in order:
POST /__cms/purgewith{"host": "...", "site": true}-- clears the KV page envelopes and the KV/Cache-API settings tiers for the host. This is the durable-tier reset. (See Deploy and purge.)- Redeploy the site worker (
wrangler deploy --env <env>) -- starts fresh isolates with an empty memMap (L1), so already-warm isolates stop serving the old in-memory settings. A purge cannot reach into a running isolate's in-memoryMap; only a redeploy (or natural isolate recycling) clears L1. purge_everythingthe Cloudflare zone (edge / CDN cache) -- clears the CF edge cache of the worker's own HTTP responses. Already-rendered pages sit at the edge with the old HTML (and, for a design change, the old stylesheet<link>) baked in; the edge keeps replaying them until they expire or the zone is purged. This is the layer/__cms/purgenever touches.
Verify with the PLAIN URL -- a ?query hides staleness
Always confirm propagation against the plain URL (for example
https://stg.wantskicks.com/some-article), not a cache-busted variant
like ?x=1. The CF edge cache key includes the query string, so any unique
?query bypasses the edge cache and renders fresh -- it will look
up-to-date even while the plain URL every real visitor hits is still serving
the stale edge copy. A ?query check tells you the origin is fixed; only the
plain URL tells you the change has actually propagated to visitors.
Which steps a given change needs:
| Change | 1. /__cms/purge site:true |
2. Redeploy worker | 3. Zone purge_everything |
|---|---|---|---|
| Content edit (article/page body) | yes | only if settings-cached in a warm isolate | yes |
| Site settings (nav, SEO, descriptors) | yes | yes (clears L1 memMap) | yes |
Style / CSS swap (template_style_id / active_style.version) |
yes | yes (baked <link> + memMap) |
yes |
| A code change to the worker itself | n/a | yes (that is the deploy) | yes |
The CSS/style asset bytes themselves (L4) are versioned by ?v=, so a new
slug/version is a fresh cache key and never needs a purge -- but the pages that
link them are HTML cached at L2/L3/edge, which is what steps 1-3 clear. See
Styles and CSS -> changing a design.
The settings cache chain (resolveSite)¶
Every request resolves the site's settings exactly once, through an ordered
chain in src/site/resolve.ts. Each tier is tried in turn; the first hit wins
and warms the tiers above it:
- L1 isolate memMap (in-memory, no TTL) -- read first. A hit returns
immediately (
source: "mem"). - L2 Cache API (
CACHE_API_TTL= 300 s, per PoP) -- on a hit, the payload is parsed, written back into the memMap, and returned (source: "cache-api"). - Origin fetch --
GET /public/v2/sites/<lookupKey>/settingsviacmsFetchwith a 1.5 s timeout. The subrequest itself is edge-cached (cacheTtl: CACHE_API_TTL,cacheEverything; the L4 layer). On success the payload is write-thru to both the Cache API (5 min) and KV (site:<host>, 24 h), and returned (source: "origin"). - L3 KV
site:<host>(KV_TTL= 86400 s, 24 h) -- consulted only when the origin fetch fails (not a 404). It replays the last-known-good settings so a transient cms-api outage does not take the site down (source: "kv-fallback", stampedX-CMS-Cache: site-kv-fallback).
A genuine origin 404 is never softened by KV: it throws SiteNotFoundError
and records a short in-isolate negative marker (see
Negative cache), so an unknown host returns
a clean 404 rather than a stale or wrong site.
All three site-settings tiers (L1, L2, L3) are keyed by host, not by the
resolved CMS site id, and that is true regardless of whether the site was
resolved by host or by the CMS_SITE_ID override (see
Routing). The
cache layout did not change when the worker gained multi-site resolution --
a single-site deploy and a multi-site deploy both cache one settings entry per
distinct Host they see.
L1 -- isolate memMap (no TTL)¶
resolveSite keeps a module-scoped Map of host to settings. It is the first
thing checked and the fastest:
// Module-scoped per-isolate map. Survives across requests in the same isolate.
const memMap: Map<string, SiteSettings> = new Map();
const memHit = memMap.get(host);
if (memHit) return { settings: memHit, source: "mem" };
There is no TTL on this map. An entry survives for the life of the Worker isolate -- across many requests. The only ways it goes away are the isolate being recycled or evicted by the runtime, or a redeploy starting fresh isolates. This is the layer that can serve stale settings; see Stale settings below.
Negative cache for unknown hosts¶
A separate, deliberately smaller map remembers hosts that origin has just confirmed have no site:
const NEGATIVE_TTL_MS = 30_000; // 30 seconds
const negativeMemMap: Map<string, number> = new Map();
On a 404 from cmsFetch, resolveSite records host -> now + 30s here and
throws SiteNotFoundError. A repeat request for the same host inside that
30-second window short-circuits straight to the same error without a second
origin round trip -- so a burst of traffic to a bad Host does not amplify
1:1 to cms-api. This map is separate from memMap (a negative marker is
never a SiteSettings, so it can never be mistaken for a real site) and is
in-isolate only -- it is never written to Cache API or KV, so an
unknown-host 404 can never poison the durable cache tiers. The short TTL means
a host that gets a site bound to it becomes resolvable again within seconds,
without needing a purge or redeploy.
L2 -- Cache API (per PoP)¶
The Cache API (caches.default) is the per-point-of-presence edge cache.
Site settings are cached here for CACHE_API_TTL:
const CACHE_API_TTL = 300; // 5 minutes
const KV_TTL = 86400; // 24 hours
resolveSite checks the Cache API after the memMap, and on an origin fetch
write-throughs to both the Cache API (5 min) and KV (24 h):
ctx.waitUntil(cache.put(cacheKey, new Response(payload, { headers })));
ctx.waitUntil(env.KV.put(`site:${host}`, payload, { expirationTtl: KV_TTL }));
Rendered pages are cached here per descriptor. The page cache key is the
full URL including the search string, so query-driven variants (for example
?page=2) cache independently:
export function pageCacheRequest(host: string, pathname: string, search = ""): Request {
const url = `https://${host}${pathname}${search}`;
return new Request(url, { method: "GET" });
}
The page's lifetime is the matched descriptor's ttl. On a render, getOrRender
sets a cache-control header from it when the response does not already carry
one:
headersForCache.set(
"cache-control",
`public, s-maxage=${ttlSeconds}, stale-while-revalidate=${ttlSeconds * 2}`,
);
Note that the page cache key strips the query string in
pageCacheKey(host, pathname) (used for KV and purge), while the page Cache API
request keeps the search string -- so trackers do not fragment the KV envelope,
but legitimate pagination variants stay distinct at the edge.
L3 -- KV (global fallback)¶
KV is a global store used as the durable fallback when origin or render fails.
Site settings are written to KV with a 24 h TTL on every successful origin
fetch (above). If a later origin fetch fails, resolveSite replays the KV copy
and reports the source as kv-fallback:
const fallback = await env.KV.get(`site:${host}`);
if (fallback) {
const settings = normalizeSiteSettings(JSON.parse(fallback) as SiteSettings, siteId);
memMap.set(host, settings);
return { settings, source: "kv-fallback" };
}
Page envelopes are written to KV on every successful render with a 7-day TTL. The envelope stores the status, headers, and body so the page can be replayed verbatim:
await env.KV.put(pageCacheKey(host, pathname), JSON.stringify(envelope), {
expirationTtl: 60 * 60 * 24 * 7,
});
If rendering later throws, getOrRender serves the KV envelope, stamped
X-CMS-Cache: kv-fallback, instead of failing the request:
const kvHit = await env.KV.get(pageCacheKey(host, pathname));
if (kvHit) {
const envelope = JSON.parse(kvHit) as KvPageEnvelope;
const headers = new Headers(envelope.headers);
headers.set("X-CMS-Cache", "kv-fallback");
headers.set("Cache-Control", "public, s-maxage=60");
return { response: new Response(envelope.body, { status: envelope.status, headers }), source: "kv-fallback" };
}
If both render and KV miss, the error propagates and src/index.ts serves a
static 503 stub.
L4 -- the cf fetch subrequest cache¶
Every call to the CMS API goes through cmsFetch (src/cms/client.ts), which
sets Cloudflare's subrequest cache on the outbound fetch:
const DEFAULT_CF_CACHE_TTL = 30;
// ...
resp = await fetch(url, {
...opts.init,
method: opts.init?.method ?? "GET",
headers,
signal: controller.signal,
cf: { cacheTtl, cacheEverything: true },
});
cacheEverything: true caches the upstream response at the edge keyed by the
subrequest URL. The default TTL is 30 s (DEFAULT_CF_CACHE_TTL), so API
data the worker re-fetches within 30 s comes from the edge rather than origin.
Template CSS overrides the TTL to 86400 s (24 h). serveTemplateCss
(src/assets/serve.ts) fetches the stylesheet from the CMS with a long
subrequest cache, and the ?v=<version> in the URL is what busts it:
const path = `/public/v2/templates/${encodeURIComponent(safeSlug)}/css?v=${encodeURIComponent(safeVersion)}`;
// Long edge cache on the subrequest; the versioned ?v busts it on change.
const resp = await cmsFetch(path, env, { cacheTtl: 86400 });
Because the version is in the cache key, bumping css_version changes the URL
and so fetches fresh CSS without waiting out the 24 h TTL. See
Styles and CSS.
The cache-first short-circuit¶
For non-preview requests, src/index.ts checks the page Cache API before doing
any work and returns the cached body immediately on a hit:
if (!isPreview) {
const cache = caches.default;
const cached = await cache.match(pageCacheRequest(host, pathname, url.search));
if (cached) {
const headers = new Headers(cached.headers);
headers.set("X-CMS-Cache", "hit");
headers.set("X-CMS-Render-Ms", String(Date.now() - startedAt));
return new Response(cached.body, { status: cached.status, headers });
}
}
This is the common path for public traffic: a warm page never touches the engine or the CMS API.
Preview bypass¶
A request with a valid ?_preview=<ADMIN_PURGE_SECRET> (optionally with
?_ver=) sets isPreview, which:
- skips the cache-first short-circuit (step 3);
- renders fresh and never reads or writes the Cache API or KV;
- stamps
X-CMS-Cache: preview(andX-CMS-Content-Versionwhen a version is given).
This lets editors see unpublished or specific-version content without polluting the public cache.
Observability headers¶
Every response that this worker generates carries:
X-CMS-Cache-- which layer answered:hit(page Cache API),miss(rendered fresh),kv-fallback(replayed from KV after a failure),preview(preview render),bypass(admin or asset endpoint), orsite-kv-fallback(settings came from the KV fallback tier).X-CMS-Render-Ms-- wall-clock milliseconds spent in the worker.
Their absence is itself a signal
These headers are stripped from the copy written to the edge cache, so a
response with no X-CMS-Cache at all was served by Cloudflare's outer
edge without running this worker -- the fastest path there is.
They describe a single render. Storing them made every later hit replay that
one render's numbers: a page served from cache in 40 ms reported
X-CMS-Cache: miss and X-CMS-Render-Ms: 885 indefinitely, which reads as
"caching is not working on every request" and is the opposite of the truth.
If you are debugging cache behaviour, trust cf-cache-status and age, and
read X-CMS-* only on responses that actually have them.
Tiered Cache (per zone, easy to forget)¶
Each Cloudflare colo caches independently. A colo holding no entry does not revalidate our documents -- it re-renders them through the worker (700-900 ms measured). Tiered Cache makes that colo fetch from an upper-tier colo instead.
Enable it once per zone, whenever a zone is brought online or transferred in:
hq/.venv/bin/python hq/scripts/enable_zone_caching.py --zone <apex> --apply
This is easy to skip because the symptom hides. The site is fast from wherever
you test it and slow from every colo you have not warmed -- which is exactly
where synthetic runs (PageSpeed, uptime checks) and first-in-region visitors
land. Raising s-maxage does not substitute for it: a longer TTL keeps an entry
alive longer in a colo that has one, and does nothing for a colo that never
did.
Document cache-control is public, s-maxage=3600, stale-while-revalidate=86400.
The hour is bounded by invalidation being by URL, not by cache tag: a
template or style change relies on a zone purge whose URL list is not guaranteed
to cover every page (purgeSite reports a truncated flag for this reason), so
an hour is the window in which anything a purge misses self-heals.
Why stale settings can persist¶
The L1 isolate memMap has no TTL. Once a host's settings are in an isolate's
memMap, that isolate keeps serving them until it is recycled -- regardless of
the 5 min Cache API TTL or the 24 h KV TTL beneath it. So:
- After a settings change in the CMS, a warm isolate can keep returning the old settings indefinitely. The lower tiers refresh on their own TTLs, but the memMap shortcut returns before they are consulted.
- A redeploy clears it. Deploying the worker starts fresh isolates with an empty memMap, so settings are re-fetched from origin (through the lower tiers).
- A purge clears the durable tiers, not L1 directly.
purgeSitedeletes the KV settings entry and the Cache API settings entry (and all page entries), but it cannot reach into a running isolate's in-memoryMap. New isolates pick up the change; already-warm ones do not until recycled.
The practical rule: a settings or CSS change that must be visible everywhere now needs the full three-step recipe -- purge, redeploy, zone edge purge -- not just a purge. See the propagation recipe above, plus Styles and CSS and Deploy and purge.