Cache and purge¶
How a CMS response gets cached, and how to invalidate it (AISD-244, epic AISD-242).
The four caches¶
A visitor request passes through up to four caches. Knowing which one is holding a stale page is most of the work, because they are purged by different means and two of them are not purgeable from cms-api at all.
| # | Cache | Keyed by | Purged by |
|---|---|---|---|
| 1 | Cloudflare zone edge (in front of the worker) | URL, and on these zones the query string is ignored | Cloudflare API, by URL (zone aspect) |
| 2 | Worker Cache API (caches.default, per-colo) |
host + pathname + search | POST /__cms/purge (worker aspect) |
| 3 | Worker KV (authoritative, listable) | host + pathname | POST /__cms/purge (worker aspect) |
| 4 | cms-api read cache (local filesystem) | site id + resource + params | the purge endpoints (api_cache aspect) |
Two consequences worth internalising before debugging:
- The zone edge ignores the query string on these zones. That is what made
Load More repeat in AISD-237 -- three correct worker fixes never ran because the
edge answered from a key that dropped
?cursor=. The fix was moving partials to a/_lm/path. - Bulk worker purges clear the bare-pathname entry only. KV records no search,
so a site or page-type purge cannot enumerate
?page=2variants. Pass explicit paths to reach one.
The cms-api read cache¶
Before AISD-244 there was no server-side cache: public/cache.py computed an ETag
and could answer 304, but only after the store had done all its database
work, so a 304 saved bandwidth and not one query.
What the cache actually saves -- measured, and smaller than it first looked¶
An early measurement of "/settings takes ~690 ms on every call" was misattributed.
Broken down from a laptop against stage:
| Component | Cost |
|---|---|
network round trip (a 304, or /public/v2/ping, is this floor) |
~320 ms |
| transferring the settings body (79 KB -- the hydrated shell is baked in) | ~320 ms |
| server-side build, which is what the cache removes | ~50 ms |
So a cold read is ~690 ms and a warm read ~640 ms: the cache saves roughly 50 ms, not 690 ms. Two things follow.
- Do not measure this endpoint from a laptop and read the total as server cost.
Compare a
200against a304on the same route: the304does the same server work with no body, so the gap between them is transfer, not computation. - The saving matters more to the real consumer than the number suggests. The worker runs inside Cloudflare's network, far closer to the load balancer, so its network floor is a fraction of a laptop's -- the same ~50 ms is a much larger share of its request, and it pays it on every page render that misses the edge.
If a bigger win is wanted, the 79 KB payload is the target, not the query.
Cached resources and their TTLs come from CACHE_HINTS (public/store/v2_common.py),
so cache lifetime stays declared in one place:
| Resource | TTL | Scope |
|---|---|---|
settings |
300s | per site |
pages |
300s | per site |
authors |
300s | per site |
lists |
120s | per site |
sitemap |
3600s | per site |
content_types |
86400s | global (not site-scoped) |
How it stores things¶
Entries live at <root>/<scope>/<resource>/<fingerprint>.json, where <root> is
CMS_READ_CACHE_DIR (default: a directory under the system temp dir). The
directory layout is the index -- a scope purge removes one tree, a resource purge
a subtree, so there is no separate key registry to drift out of step with the data.
Three properties that are easy to break and are covered by tests:
- The canonical JSON string is cached, not the payload dict. The ETag is a
sha256 of that string, so a warm response is byte-identical to a cold one by
construction. Caching the dict would make parity depend on
default=strrendering adatetimethe same way twice. - Keys use the resolved site id, never the ref as given. One site is reachable by id, acronym, and domain; keying on the ref would store three entries and leave two of them stale after a purge.
- Versioned reads are never cached.
?versionis gated byX-CMS-Preview; caching one would let a later unauthenticated request be served a draft from the cache, bypassing the gate.
Failure behaviour¶
Reads degrade, purges do not. Any filesystem error on a read is logged and
treated as a miss, so the cache can never turn a working read into a 5xx. A purge
that could not run raises, and the endpoint reports api_cache: failed -- a
silent failed purge would leave you trusting stale data, which is worse than an
error.
Growth is bounded by an expired-entry sweep on write plus a per-scope cap
(MAX_ENTRIES_PER_SCOPE). This matters because lists and sitemap are keyed
partly by cursor, so a crawler walking pagination mints one entry per cursor that
is never read again.
Known limitation: the cache is per-instance¶
cms-api runs one instance per environment today, so a purge clears the only cache that exists. Behind two or more instances that stops holding: a purge reaches whichever instance serves the request and the others keep serving cached data until the TTL expires, bounded by the table above but no longer an authoritative purge. Revisit before scaling cms-api out. A shared cache (Redis) would not have this property.
The cache also starts cold after every deploy or container restart, since it lives under the container's temp dir. That is correct for a cache and keeps the image stateless.
The purge endpoints¶
Four routes, one per level. All are POST, all sit under the
globally-authenticated /admin/v1 mount, and all accept the site as a numeric id
or an acronym.
POST /admin/v1/sites/{site_ref}/purge whole site
POST /admin/v1/sites/{site_ref}/purge/pages page_types OR paths
POST /admin/v1/sites/{site_ref}/purge/articles/{slug} one article
POST /admin/v1/purge/global non-site-scoped resources
Separate routes rather than one endpoint with a level field: each level takes
different inputs, and a distinct path makes the granularity visible in an access
log and to whoever wires up publishing.
Response, and the partial-failure contract¶
{
"site_id": 206, "acronym": "WK", "host": "dev.wantskicks.com",
"api_cache": {"status": "ok", "purged": 12},
"worker": {"status": "ok", "purged": 66, "truncated": false},
"zone": {"status": "ok", "purged": 3}
}
200 only when no aspect failed. A failed aspect returns 502 with the same breakdown, so a purge that half-worked can never read as success -- that is the most expensive failure mode to diagnose. Every aspect is attempted even when an earlier one fails, so the breakdown always shows the full picture.
skipped is not a failure. Common reasons:
| Aspect | skipped because |
|---|---|
worker |
no cf_worker URL or no purge secret configured for this environment |
worker |
the level is not site-scoped (global purge) |
zone |
no usable Cloudflare token |
zone |
the worker returned no page URLs to purge |
truncated: true on the worker aspect means the site holds more cached pages than
one call can clear -- repeat the purge until it is false.
Per-level notes¶
Site. Clears every api-cache entry for the site, a worker site: true purge,
and a zone purge of the URLs the worker reports. It also drops the in-process
site-ref map, since a site-wide purge is exactly when an acronym or domain may have
been reassigned.
Pages. Exactly one of page_types or paths is required; both, or neither, is
a 400. Valid page types are the worker's own 13: homepage, category,
article, author, authors, contact_us, about, privacy_policy,
terms_of_use, do_not_sell, search, sitemap, 404. An unknown one is a 400
naming it.
On the api-cache side each page type maps to the resource that backs it
(category -> lists, article -> pages, a static page -> settings); the
worker applies the exact page-type filter on its side.
Article. Only the slug is needed. The worker resolves /{category}/{slug}
itself and follows cms-api's canonical-slug 301, so a truncated or junk-suffixed
slug still purges the canonical article -- the response echoes the slug actually
purged.
Global. Reaches resources with no site scope (content_types), which no
per-site purge can touch. Without it they would be the one cached resource with no
invalidation path.
Alias hosts are purged alongside the canonical one¶
A site has exactly one domain in the database, but the same site can be served
on more than one host -- preprod runs fashionradar.net's content at
preprod.fashionradar.net. The worker keys its cache on the request host, so
purging only the database domain leaves those entries untouched: the purge
reports ok and the stale page stays up, which is the worst failure here because
it looks like success.
So every worker purge fans out to the canonical host plus any configured aliases
(cms_api.purge.worker_client.aliases_for). The canonical host decides the
reported status; an alias can only add to the purged count, and an alias
that fails is logged rather than surfaced -- a rehearsal host's outage must not
make a production purge read as failed.
Aliases live in the same Parameter Store JSON as the other service URLs, keyed by canonical host:
Unset means no aliases, which is correct for an environment whose sites are served only on their canonical domain.
A whole-zone purge is never issued¶
Cloudflare zones are shared between environments: dev.wantskicks.com and the
production wantskicks.com are one zone. So purge_everything is refused outright
-- a stage site purge that flushed production's edge cache is exactly what happened
before this was fixed. Every zone purge is by explicit URL, driven by what the
worker reports having purged, batched at 30 URLs per Cloudflare call.
If a zone purge is ever needed at a broader scope, it must be a deliberate, separately-authorised action -- not a side effect of purging one site.
No auto-purge on writes¶
Purging is explicit. A write through /admin/v1 does not invalidate anything,
so a change is invisible until something purges or the TTL expires. Publishing is
expected to call these endpoints.
This is a deliberate decision, not an omission: auto-purge is what editors expect, but it widens the change into every admin write path and risks purge storms on bulk operations. If it is wanted later, content writes are the narrow place to start.
Configuration¶
| Setting | Source | Absent means |
|---|---|---|
CMS_READ_CACHE_DIR |
env | a directory under the system temp dir |
cf_worker |
Parameter Store /{env}/cms-api/urls |
worker aspect reports skipped |
purge_host_aliases |
same Parameter Store JSON | only the canonical host is purged |
| purge bearer | Secrets Manager /common/cms-cf-worker/admin-purge-secret |
worker aspect reports skipped |
| Cloudflare token | Secrets Manager /common/cloudflare |
zone aspect reports skipped |
The purge bearer is the same value the worker validates, so nothing new is provisioned for it. The worker URL is provisioned idempotently:
Config is read at import time, so cms-api must restart (redeploy or container
restart) before a newly provisioned value takes effect. A purge run before that
restart correctly reports worker: skipped.
Debugging a stale page¶
- Which cache? Request the page and read the headers.
X-CMS-Cache: hitis the worker's cache;X-CMS-Render-Mspresent means the worker actually rendered. No worker header at all withcf-cache-status: HITmeans the zone edge answered and the request never reached the worker. - Purge narrowly first -- the article or the path -- then re-request.
- Do not pre-purge immediately before measuring a hit. Pre-purging each URL right before reading it manufactured two false passes during AISD-237. When a purge is the setup for a cold read, say which is which.
- If
workerreportsskipped, the fan-out never happened -- check the config table above before concluding the purge failed.
See also¶
- Postman / API collection -- the Purge (cache invalidation) folder has all four endpoints with runnable examples
- Public v2 API -- the cached read surface
- Request lifecycle