article
Cache SSR pages at the edge and purge them by tag from a CMS webhook
TL;DR Rendered pages cached with the Workers Cache API can be purged by tag when a CMS publishes, but not by URL. A purge that answers 200 can still evict nothing, and a zone's browser cache setting can serve stale HTML for four hours. The cache saves latency, not money: purge by tag, and check cache-control.
A purge that Cloudflare answers with 200 can still evict nothing. In one of my runs the page stayed a HIT for over a minute after a successful webhook. This is part 4 of the series: part 1 is the overview, part 2 sets up the Workers and part 3 moves the content.
The cache is per data center and per build
Without a cache, every page view costs an Astro render and one to three Storyblok API calls. The production Worker stores rendered pages with the Workers Cache API (caches.default).
Cache hit, miss and purge
A GET or HEAD for a page. The Worker runs on every request, hit or miss, before the cache lookup.
The key is the page URL without its query plus ?__build=<build id>. A new deploy has a new id, so it starts with an empty cache.
The stored response goes out with X-Edge-Cache: HIT. No render and no Storyblok call.
Astro renders from Storyblok, the Worker adds Cache-Control and a Cache-Tag, stores the page for 3600 seconds and answers with X-Edge-Cache: MISS.
A Storyblok publish fires a webhook. The Worker asks Cloudflare to purge the page's tags, and the next request is a MISS again.
Each page carries tags: post-<slug> for an article, series-<slug> for a series, page-<slug> for pages, index, and feed for the RSS and sitemap. The cache does not replicate. Cloudflare's Cache API docs say the contents "do not replicate outside of the originating data center", so each data center pays for its own first render.
Run the probe and guess which data center answers before you read the result.
Live request to this site's own edge
A cached page from outside, headers filtered:
$ curl -sI https://blog.mikepenz.dev/a/adb-tricks/ | grep -i -E "^(HTTP|cache-control|x-edge-cache|cf-cache-status|age)" HTTP/2 200 cf-cache-status: HIT age: 483 cache-control: public, max-age=0, must-revalidate, s-maxage=3600 x-edge-cache: HIT
A HIT carries no cache-tag header, and the Cache API docs say cache.match() does not return it either. So the Worker has to set it on every put().
Purge by tag, because a purge by URL misses the key
Cloudflare's how the cache works page warns: "Based on cache API implementation, not all cache purge endpoints function for purging assets stored by the Cache API." The same page says it is not possible to purge a URL that uses a custom cache key set by a Worker. Entries here live under a key with ?__build= in it, so a purge by URL would miss them. The code only purges by tag.
Purge by tag does work on Cache API entries. Here is the webhook end to end on a settled entry:
19:01:48 HIT age=80 19:01:59 HIT age=91 (pre-check) 19:01:59 webhook 200 {"purged":true,"tags":["index","feed","post-adb-tricks"],"status":200} 19:02:00 GET 200 x-edge-cache=MISS cf-cache-status=null age=null cache-tag=post-adb-tricks
In my runs, a purge evicted within six seconds. One run did not: the webhook arrived in the same second the entry was stored by a MISS, and the page stayed a HIT for over a minute. The cause is unknown, and I did not repeat that case. Cloudflare's purge docs say a successful purge request "does not confirm that Cloudflare cached the targeted content or evicted any content", and Storyblok's webhook docs say webhooks don't retry on failure, so a failed purge is not repeated.
A cache you cannot purge reliably should have a short TTL. In the same-second case, a stale page lasts up to the 3600 second TTL.
Without a webhook secret, the key goes in the URL
The Storyblok docs say "Webhook secrets are only available in paid plans". This space has no webhook secret, and without a secret there is nothing shared to check a signature against. So the handler accepts either proof, and either alone is enough:
the
webhook-signatureheader, a hex HMAC-SHA1 of the raw body, ora
?key=query parameter equal toWEBHOOK_SECRET, put into the webhook URL in Storyblok.
The concepts page does not name the signature algorithm. Storyblok's webhook secret tutorial uses createHmac('sha1', secret) with a hex digest, and the handler does the same. The unit tests pass, but a real signature from Storyblok needs a paid plan, so it has not been seen here. Both proofs are compared in constant time, and an empty or missing secret denies everything. A wrong or missing proof returns 401 and purges nothing. The handler reads at most 256 KiB of body and answers 413 above that, because an early version accepted and hashed a 20 MB body.
A key in the URL has costs:
Anyone with access to the Storyblok space can read the webhook URL and so the key. A leaked key can only trigger purges for this site's tags, which means extra Storyblok API load until the cache fills again.
URLs end up in logs. Cloudflare's Workers Logs docs say a fetch invocation log message is
<Method> <URL>, so invocation logs are off inwrangler.jsonc.A webhook has no timestamp, so a captured request can be replayed to trigger purges and Storyblok calls.
The ?key= path works through the real Storyblok webhook: a republish of the license story turned its cached page from HIT to MISS within 9 to 30 seconds. The timing fits the webhook as the cause.
A zone setting can override the Worker's cache header
The first live reading of a cached page had cache-control: public, max-age=14400, s-maxage=300, while the Worker sent max-age=0. The zone setting Browser Cache TTL is 14400 seconds, Cloudflare's default of four hours. Cloudflare's Browser Cache TTL docs say Cloudflare overrides the origin header when its value is lower than the zone setting, and "Respect Existing Headers" turns that off. A purge cannot reach a visitor's browser, so repeat visitors could keep stale HTML for four hours.
The Worker also sends must-revalidate, and the capture above shows max-age=0, must-revalidate with the zone setting still at 14400. Whether that is what stops the override is not proven. Setting the zone to "Respect Existing Headers" is the documented way out.
The cache saves latency and Storyblok calls, not dollars
Measured from one location that reached one data center (VIE), so cross-data-center misses are not in these numbers:
Hit ratio. 240 of 240 GETs on six URLs were HITs. A poll found exactly one MISS per URL per TTL window, at expiry.
A HIT costs no Storyblok call. Cloudflare analytics showed 0 subrequests in HIT-only minutes. A MISS costs 1 call for a standalone article or the sitemap, 2 for the index or the RSS feed, 3 for a series article or series page.
CPU. About 1.2 to 1.6 ms per HIT, 6 to 21 ms for an uncached render (sampled on HEAD and 404 requests, not a clean GET MISS), and 100 to 262 ms for the first render in a cold isolate.
The Worker still runs on every request. The cache saves the render and the Storyblok calls, not the request.
Cloudflare's Workers pricing page lists the Free plan at 100,000 requests a day and 10 ms of CPU per invocation. The paid plan costs at least $5 a month with 10 million requests and 30 million CPU ms included, then $0.30 per million requests and $0.02 per million CPU ms. Subrequests are not billed. A simple model (one data center, 300-second TTL, 30 URLs, one Worker request per view, 20 ms per MISS) gives:
Views a month | With cache | Without cache |
|---|---|---|
10,000 to 1 million | $5.00 | $5.00 |
10 million | $5.00 | about $8.40 (CPU overage) |
At 100 million views the requests alone cost about $27 on top of the $5 minimum, with or without the cache. With the cache, 100 million views add about $2 of CPU overage. Without it they add about $39. The paid plan is an assumption: production served requests at 11 to 262 ms of CPU without errors, and the Free plan's 10 ms limit would stop them.
The tighter limit is Storyblok's. Its rate limit page allows 6 requests per second for "Listings with 75 to 100 entries", while cached CDN requests get 1000 per second. The docs do not say whether the 6 per second applies to uncached requests only. The site's lists use per_page=100, the slowest tier, and a MISS can need two lists, so about 3 cold renders per second reach the ceiling.
Purges have a limit too. Cloudflare's purge docs give Free accounts 5 purge requests per minute, and each webhook is one purge. Publishing more than 5 stories within a minute would exceed that on a Free zone. I do not know this zone's plan, so it may not apply here.
Failures that got cached, and the fixes
Degraded renders got cached. A failed series lookup, a feed built from a failed list or a partial index was stored as a normal 200. A render where a Storyblok call failed carries
no-storeand is not cached.404, HEAD and POST each cost a Storyblok call. HEAD is answered from the GET copy, genuine 404s are cached for 60 seconds, and any method other than GET, HEAD or OPTIONS is rejected before rendering.
The purge returned 500. The production Worker had no purge token. The token is a Worker secret, and the purge deserves a test after every deploy.
No protection at expiry. There is no lock, so concurrent requests at expiry can each render. The Cache API does not support
stale-while-revalidate, per its docs. This one is still open.workers.devis not a cache no-op. A note in the code said it was. The second GET of an article there was a HIT. The Cache API docs also say it is not available for Workers fronted by Cloudflare Access.
Try it yourself
You need three values: a webhook key, your zone id and a purge-only API token. Keep them in a secret store and out of chats and shared terminals. Then:
Step 1 of 5
Generate the key
openssl rand -hex 32Store the output as WEBHOOK_SECRET.
Create the purge token
In the Cloudflare dashboard: My Profile > API Tokens > Create, permission Zone > Cache Purge > Purge, resources limited to your one zone. Store it as CLOUDFLARE_PURGE_TOKEN, next to the zone id from the zone's Overview page.
Give the Worker the secrets
Set all three as secrets on the production Worker and deploy. Without the purge token, the webhook answers 500.
Add the webhook in Storyblok
Space > Settings > Webhooks. The URL is https://<your-host>/api/webhook?key=<WEBHOOK_SECRET>. Triggers: story published, unpublished, deleted and moved.
Publish something and read the response
Request the page with curl -sI before and after: x-edge-cache switches from HIT to MISS. The handler answers 200 with {"purged":true,...} on success. 500 means the zone id or purge token is missing on the Worker. 502 means Cloudflare rejected the purge. 401 means the key in the URL differs from WEBHOOK_SECRET.
To rotate the key, set the new value, deploy, then edit the webhook URL. Between those two steps the webhook gets 401 and the cache keeps its pages until they expire.
Requirements: a Cloudflare zone with a Worker on a custom domain (the Cache API is functional there), and a Storyblok space with a Content Delivery API token.
Honest limits
The Cache API is per data center, and Cloudflare confirms receipt of a purge, not eviction. Both the webhook key and the preview token travel in query strings, which is why invocation logs stay off. blog-mikepenz-dev.<account>.workers.dev serves the whole site publicly, and there is no WAF rate limit. The lists use per_page=100 without pagination, so past 100 articles or 100 series, entries would drop from the index, RSS and sitemap. Run curl -sI on one of your pages twice and read cache-control before you trust it.