Cloudflare Worker fleet cost cut
Measure each meter first. Then change the code that drives the biggest meter.
Keep a measured saving apart from a target. A target is a plan, not a result.
Read cloudflare-cost-audit first for the billing baseline. This skill covers
what to change after the baseline exists, and how to roll it out to many repos.
Read optimizations.md for each measured cut, grouped by meter.
Each entry gives the signal to search for, the change, the proof and the trap.
The meters and what they cost
Allowances are per account, shared by every Worker in it. Check current prices before you
quote a number.
| Meter |
Price over the allowance |
Allowance |
| Worker requests |
$0.30 per million |
10M |
| Worker CPU |
$0.02 per million ms |
30M ms |
| D1 rows read |
$0.001 per million |
25B |
| D1 rows written |
$1 per million |
50M |
| KV writes |
$5 per million |
1M |
| KV reads |
$0.50 per million |
10M |
| KV storage |
$0.50 per GB |
1 GB |
| Durable Object requests |
$0.15 per million |
1M |
One KV write costs about as much as reading 5,000 D1 rows ($0.000005 against
$0.000000001 a row). Weigh a change in both directions: a change that saves a write but
adds 10,000 row reads loses money. A cached read also costs the KV read fee, about 500 row
reads. Net rows saved per hit = rows saved per read minus 500. Reads to pay back one write =
5,000 divided by that net (ESTIMATE). A hit that reads N cached entries pays the fee N times,
and W entries written cost W times 5,000: hits needed = W x 5,000 / (rows saved - N x 500).
Saving 1,000 rows a read with one entry needs about 10 reads in the window. A bigger load pays
back sooner. optimizations.md shows the arithmetic.
KV writes per hour is the check for any KV change. Query kvOperationsAdaptiveGroups
with the dimension datetimeHour. The hourly reading (MEASURED) showed no write spike after a fleet deploy.
So the idea that a deploy empties the data cache and causes a write wave is not supported.
To find which D1 queries read the rows, query d1QueriesAdaptiveGroups and sort by rows
read. Families found: a category-tree CTE with json_each, a full scan of one table, and
per-request COUNT facets. See optimizations.md.
In the fleet this was learned on, the order was: Worker CPU, KV writes, D1 rows read,
requests, KV reads, containers, Durable Objects, subscriptions. Rank yours before you act.
Measure first
- Billing API.
accounts/{id}/billable-usage?from=YYYY-MM-DD&to=YYYY-MM-DD returns daily rows.
- Each row is ONE DAY of use and that day's cost (
ConsumedQuantity, BilledCost). Cloudflare
applies the monthly free allowance to the cumulated quantity, so a day that crosses the
allowance shows a part-free cost. Sum BilledCost per day and per service line.
- The feed returns only the NEW billing period's rows when
from lies inside the old period, and to
is exclusive. Ask 35 days back and one day past the end, then keep the days you want.
- A new billing period (
BillingPeriodStart changes) restores the allowance. The first day of a
period looks cheaper than it is. Do not compare it with the last day of the old period.
- The newest day is published late and in pieces. A partial day shows only some lines, often
D1 first and Workers CPU and KV writes later. Mark it
partial. Never call a partial sum a
daily total.
- Check the feed against analytics. A full-day D1 analytics sum matched the bill to the row
(63,325,168,002 against 63,325,168,224: 222 rows apart, under one part in 100 million), and Workers CPU matched within 0.01% (576,338,444 ms against 576,290,354 ms billed). Analytics gives usage, not cost: to get cost, apply the monthly allowance to the period's cumulated quantity. Once they agree,
analytics usage can stand in for the bill's usage on a day the feed has not published.
- GraphQL analytics gives the same day as usage, not dollars. Useful datasets:
workersInvocationsAdaptive (requests, CPU), d1AnalyticsAdaptiveGroups and
d1QueriesAdaptiveGroups (rows read, per query), kvOperationsAdaptiveGroups
(reads, writes, deletes per namespace), httpRequestsAdaptiveGroups (per zone).
Group by namespace or script, then map ids to names with the list APIs.
- Per request CPU.
wrangler tail --format json shows cpuTime, wallTime,
request headers, status and scriptVersion. Sample one site for a few minutes per
path. Workers Observability can also read logs. The tail writes pretty-printed objects back to
back, not one per line: decode the stream. cf-traffic-probe ua-cpu <files> (scripts repo) does
that and splits CPU by crawler name and route kind. Its other probes read hourly CPU per Worker,
KV operations and storage per namespace, the top D1 queries by rows read, and zone traffic.
- Per site spread. Writes per request varied 40 times between sites (0.09 to 2.15).
A fleet average hides the two or three sites that make half the bill. Rank by site.
- Heavy tail. Ask analytics for
quantiles { cpuTimeP50 cpuTimeP99 } per script. CPU minus
(requests times the script's own p50), divided by all CPU, is the heavy-tail share. A share
above 50% means a few requests cost far more than the rest. On this fleet it was 71%, and the
likely cause was cold starts (inferred from the cold and warm samples; see lever 0). A trivial request that costs a second or more of CPU, such
as a redirect or a health check, is the signature.
- Cold versus warm, measured on the real Worker. Run
wrangler tail <script> --format json
in the background. Send a request with a unique query string to a quiet site, again two
seconds later, and again after a pause. Read cpuTime for each from the tail by URL. The
first request of an isolate cost 917 ms, the next 48 ms, and a request that landed in a new
isolate cost 992 ms. Local measurement alone misled us: it measured the warm path.
- Compare like with like. Compare the same hour of the day, before and after.
Traffic and bots change a day-on-day comparison. Find the hour a step happened and set it
against the merge and deploy times. Our big drop (D1 reads 97B to 2.5B a day) happened 12
hours before the PRs that we first credited. The cause was a search pause.
- A usage-based run rate is an estimate. A billing row is a measurement. Label each.
Levers, ranked by value
Apply them in this order. Each has the meter it cuts. Measure before and after each one; the
measured effects below are from one fleet and may differ on yours.
0. Cut what a cold start costs (CPU)
On a fleet of many small Workers, cold starts can be most of the CPU bill. Check the heavy-tail
share first (Measure, item 5). Here it was 71% of all CPU: a cold request cost about 920 to 990 ms
and a warm one about 50 ms, so the bill followed (number of cold starts) times (cost of one).
Each site is its own Worker and each Cloudflare location starts its own isolate, so you mostly cannot
cut how often they start (fewer, larger Workers would share isolates, which is a bigger change). You can cut what a start costs.
Bytes may matter, but two measurements disagree. In a fresh local process the first request had a median of 589 ms (the next 20 had 6.6 ms). In a profiled first request of 642 ms, about 350 ms (55%) was V8 compiling the 25.7 MB OpenNext handler (a plain Node compile took 290 to 300 ms, about 11.5 ms per MB) and the rest was real start-up work. A plain Node compile suggests about 230 ms more for 20 MB more code. The slope test below measured about 70 to 90 ms more. Treat bytes as a possible lever, not the main one.
Lazy import() does not help: OpenNext inlines dynamic imports into the same file.
A bundle-size slope test, so far unproven either way. I appended 10 MB and 20 MB of never-called
functions to a 25.8 MB handler, then timed one cold request per fresh local D1. The first request moved
from about 1.26 s with no extra code to 1.23 to 1.33 s with the function arms and 1.35 to 1.38 s with the
data arms (wall time; the local worker reports CPU only as 0 or 1000 ms, a one-second resolution). That test was weak (7 of 15 runs got the local 429 and measured
nothing, one or two valid samples per arm, and lazy parsing may hide a real cost), and the profile
of the first request put 48% in V8 "(program)" time. Run a clean slope test before you spend
a week on bytes, and read the V8 profile with scripts/startup-profile.ts.
Find what fills the bundle. On this fleet Turbopack copied shared modules into each route group
(zod core 20 times, an app schema module 20 times), better-auth, drizzle and kysely were bundled
once per rsc and ssr layer, and a 0.94 MB block of legacy encoding tables came from Next's body
parser. Try a webpack build, which shares chunks. Keep client-only libraries (maps, editors) out
of server-evaluated code.
Test minify (unconfirmed). One local sample found the first request about 40% cheaper with
Wrangler's minify off (530 ms against 900 ms), at the price of a larger gzip. That sample came from a different local build
than the 589 ms median above (one with minify on, one with it off), so do not compare the two numbers. That goes against
the bytes lever above. A small production A/B (4 cold requests on the old bundle, 5 on the new)
showed a large drop. It is MEASURED, but the samples are few and the kept logs cannot reproduce it.
But fleet CPU per request did not change: 71.5 ms on both days, same hours (MEASURED).
Keep it unconfirmed.
Compare the same hours across days before you credit a change. Deploy it to one
site and read cpuTime from the tail before you roll it out.
A region pin per site is a switch, and its benefit is unproven. An early test set a placement region
through the API; it was rewritten as mode: targeted and the home page went from 0.2 s to 3.3 s.
A later per-site variable that writes placement.region into the rendered config gave mixed one-hour
results (CPU per request fell on three sites, was flat on two and rose on one). A same-hours, cross-day
check over 27 pinned and 22 unpinned sites could not separate the pin from the crawler blocks made in the
same days (optimizations.md). Pin one site, compare the same hours against an unpinned control, and
undo it where it does not help. Save the old setting first.
1. Stop bot and router noise (CPU, requests, D1)
Turn off link prefetch. Next prefetches RSC payloads for every visible link. Bots and
crawlers multiply it. Make the shared Link component default to prefetch={false}.
Measured on one site: _rsc requests fell from 9% of traffic to 0.
Refuse a bare _rsc request. A real router request sends ?_rsc= and an RSC
header. A request with the parameter and no header is a bot replay. Answer 404 with
Cache-Control: no-store before the cache and before any render, for GET and HEAD.
Put the guard first in the Worker entry. A WAF rule is cheaper still, but it needs a token
with Zone WAF permission (see the token bullet below).
Pause staging and search jobs. Staging sweeps and search jobs burn requests with no user.
A per-minute cron for every site was about 1% of CPU on this fleet (ESTIMATE).
Measure before you spend a PR on it.
Block a client by what it sends, on the Cloudflare edge, before the Worker runs. Traffic was very
concentrated: one IP with an empty User-Agent sent 43% of a site's requests and another 60% of a
second site's. A zone custom rule (http.user_agent eq "" and not starts_with(http.request.uri.path, "/api/"))
with action block stops them with no Worker run. Do it safely, zone by zone:
- Check analytics first for empty-user-agent traffic outside
/api/ that you want. Examples are
an uptime monitor, a webhook and a health check. They can send no user agent.
GET /zones/{id}/rulesets/phases/http_request_firewall_custom/entrypoint and save the answer to
a file. A PUT to that entrypoint REPLACES every custom rule on the zone: send back all the
existing rules plus yours, or add yours with POST .../rulesets/{ruleset_id}/rules. The free plan
allows 5 custom rules per zone; check there is room.
If the GET returns 404 (a zone with no custom rules yet), create the entrypoint with a PUT that holds
only your rule.
- Give the rule a stable
ref so it can be found and removed later, and record the zones.
- To undo,
DELETE .../rulesets/{ruleset_id}/rules/{rule_id} for the rule with your ref, or PUT the
saved entrypoint back.
- Verify on each zone: an empty user agent gets 403, a normal request and the AI crawlers you want
get 200, and
/api/ still answers.
The free plan refuses a custom block response ("not entitled to use a custom response"), so a block
cannot carry a pointer to your API; use the Worker for that.
Do not block AI crawlers by user agent if your product tells owners to let them in. Our own
audit tool told site owners to let GPTBot, ClaudeBot and similar agents reach the homepage.
Rate-limit by behaviour, or leave them.
The token needs permission. The fleet token had no WAF permission (request is not authorized).
All 50 token slots were in use. Do not revoke a live deploy token to make room. Prefer a separate,
narrow WAF token when a slot is free. If none is free, extend the existing zone-wide policy of the
token that already has zone access, with a token that can edit tokens: PUT /user/tokens/{id}
REPLACES the whole token, so (1) GET the full token object and save it to a file; (2) send back
the same object with only Zone WAF Read and Zone WAF Write added to a policy that already covers
all zones, keeping name, status, condition (IP limits), not_before and expires_on exactly (look up the
group ids with GET /user/tokens/permission_groups; a policy names groups by id); (3) read it
back and compare name, status, condition, expiry and every permission by NAME, not by position
(the API reorders policies); (4) to undo, PUT the saved object. Verify the token still works.
Note that this gives that token WAF write on every zone: that is the cost of not using a new token.
2. Cut KV writes (KV writes)
KV writes in an OpenNext app come from the incremental cache. Each cache miss writes an
entry. Pages that are force-dynamic still write the data cache through unstable_cache.
- Do not cache the long tail. A key built from the full filter JSON, a page number above
1, a free-text query or a rare place and category pair is read once, if ever. Measured:
98% of geo page requests were unique within 3 minutes. Call the loader directly for these.
Keep the cache for head pages that many visitors read.
- Use fewer, coarser keys. Merge small counts that one page reads together. Do not merge
if a head key grows past about 25 KB or if the data has different invalidation.
- Raise the data cache window. A short window rewrites long-lived keys every few
minutes. If data changes only by import and every write path calls
revalidateTag, use a
day. Keep the edge page cache window separate. A constant shared by both turns a data
decision into a stale page decision. The KV retention must be at least the window.
- Skip a write when the value is unchanged. Read the stored value first. A read costs a
tenth of a write. Refresh the entry before it is about half its retention age, or a
valid entry can expire while it is in use.
- Audit every write path before you lengthen a window: claim, edit, tier change,
import, delete, admin tools, webhooks. Each must call the revalidate helper.
- Add a check to local CI that fails when a new cached key embeds
JSON.stringify of a
free-form object without an explicit opt-in comment. Without it the pattern returns.
3. Cut D1 rows read (D1 rows read)
- Put a per-request row budget at the Worker entry. Count rows read per request. Run it in
log-only mode first. Then set a cap for each route from the measured maximum rows. One query
family read up to 190,000 rows in one run. A cap below the real maximum turns a valid page or
sitemap build into a 503.
- Store counts at import. Counts for facets, places and categories rarely change. Write
them to a table when you import. Do not compute them with a group query per request.
- Beware head-of-line blocking. D1 runs queries one after another. One sitemap build ran
nine queries that read 300,000 to 693,000 rows each and took 1 to 1.7 s each. Every other
request queued behind them and was refused as overloaded. Find the one heavy burst; do
not blame the row cap without a log line that names the cause.
- Prove a count needs no query. The sitemap index needs only the shard count.
A cheap upper bound, such as the published listing count, proves one shard. Run the heavy
count only when the bound exceeds the shard size.
- Cache the sitemap index in KV with a hash. Serve a fresh copy with no D1 read. Serve a
stale copy at once and rebuild in the background behind a short lock. If the build fails and
nothing is stored, serve a degraded index built from config alone, with a header that
marks it and
no-store. Never let the edge cache store the degraded copy.
4. Cut warm Worker CPU (CPU)
Do this after lever 0. Measure on cold, uncached pages in production (a unique query string per
request, read cpuTime from wrangler tail), not on a warm local server.
- A markdown page cost about 24 ms against about 67 ms for HTML on cold pages (median), so serving
markdown to AI agents would save about 40 ms a request. That is an estimate of about $0.04 a day
on a site where AI crawlers were 42% of requests (the 40 ms comes from a small cold sample). An older sample had said 8 to 12 times; it compared different pages. Do not
build a feature on a saving you have not measured on matched pages.
- Cutting the HTML and RSC payload by 42% and 68% left warm render time about 10% lower, measured locally on demo data. Payload
bytes are not CPU. They cost bandwidth, which Workers do not bill.
- Dynamic
robots.txt and llms.txt cost about 200 ms a hit on one site, but this too was mostly
cold start; serving static files helps only for files that were not edge cached.
5. Publish the long tail as static files (CPU, requests, D1, KV)
Workers Static Assets serve files with no Worker run. Requests for static assets are free.
This removes the CPU, the D1 reads and the KV write for those pages.
- Pilot on one site first. Learn the limits before a full build: file count, total size,
and generation time (estimated 2.2 to 5.7 hours serial for one large site).
- Use
_headers for cache headers and a trailing slash rule so URLs match the dynamic ones.
- Keep dynamic routes for pages that need data per visitor.
6. Block named crawlers and facet crawls (requests, CPU, D1)
A tail split by crawler name found QlyzeBot at 33% of the sampled CPU on six heavy sites and GPTBot on
/search facet links at about one request a second. Put the polite ones in robots.txt and the
rest behind an edge rule that runs before any Worker. Details, proof and traps in optimizations.md
("Name the crawlers that cost money"). Add the rule to the site launch step.
7. Clean KV storage and read the KV cache through the regional cache (KV storage, KV reads)
KV storage was 38.6 GB, 34 GB of it legacy cache entries that never expire and that no deploy reads. Swap the
namespace; do not delete the keys one by one. A regional Cache API wrapper cut repeat KV reads on a page
from 6 to 0. Details and traps in optimizations.md ("KV storage", "Read the KV cache through the regional Cache API").
Process traps (rolled out as checks where possible)
- Honest targets. An adversarial review refuted a "$50 a month" claim: the run rate was
about $520 a month. Say what is measured, what is an estimate and what is a target.
- Judge a delegated job on its diff. A worker can exit 0 and write nothing. Rerun the
tests yourself. A test that cannot fail proves nothing. Mutation-test it: break the code
on purpose and watch the test fail, then restore the code.
- Write the failing test first and show it fail. Register tests with
if (!REMOTE) { ... }. A repo policy may reject test.skip.
- Do not trust "completed". Check the exit code of every build and test.
- E2E hygiene. Two worktrees run on the same default ports and collide. Pass your own
ports. A Miniflare cache that is not empty can fail a spec with
STALE: clear it between
runs. Production-build test servers set ENVIRONMENT=production, so a test hook gated on
"not production" never runs there.
- Test hooks in production code need a guard that no Worker secret can turn on, and a
local CI check that scans configs for the hook name.
- Do not rerun an old run's failed deploy jobs. They can redeploy an older commit. A
newer push redeploys. A
fetch failed in a deploy job was transient.
- Merge gate. Read both the reviews and the review comments. Check the review is for
the head SHA, that the SHA has its own check runs and that no Critical or Major is open.
Merge with
--match-head-commit.
- Prompts. Pass a long prompt to a CLI by stdin. A variadic
--allowedTools flag
swallows a prompt given as an argument: claude -p --allowedTools A B C "prompt" reads the
prompt as a tool name. Write prompt files with the Write tool, since a
hook can block prompt text typed in a shell.
- Commit messages with a dollar sign. In double quotes,
$0.000025 becomes
/bin/zsh.000025. Use single quotes.
- GraphQL errors in
gh. gh pr edit and gh pr review can fail with a GraphQL error.
Use the REST API: gh api -X PATCH repos/OWNER/REPO/pulls/N -F body=@file, and
POST repos/OWNER/REPO/pulls/N/reviews.
- Assert the one counter that proves the claim. A spec that compares D1 read counts
between two views can pass for other reasons. Assert the counter for the query you
changed, such as the listing query count.
- Review the callers of a cache rule you change. A cache rule that skips the long tail
can make a head page uncached if that page shares the key shape.
- A review gate may read plain lines. A gate can match
Reviewed-by: and Verdict:
lines only. A bold verdict line is not matched.
- Sandboxes (Boat). A box needs the right language runtime version, the site setting,
and a real copy of any folder that is a symlink in the repo. Agent logins inside a box can
expire. A new repository may need its environment created first, and the repo list may need
a refresh in the dashboard.
- Billing reads need a clear window. A frozen feed is often a misread: check the row
date, not only the number.
Traps from running many workers at once
- Write briefs with a file tool or a quoted heredoc (
<<'EOF'). An unquoted heredoc runs every
backticked command in the brief in your own shell and leaves the worker a brief with holes.
- In zsh,
set -- $var does not split words. Use a function with explicit arguments or an array.
pkill -f kills other jobs. Kill by process id. Killing the wrapper of a CLI agent does not
kill the agent: find live agents by their working directory (lsof -p <pid> | grep cwd) before you
start a second one in the same worktree, or the two collide and both stop.
- One log file per run. A later run that writes the same log file overwrites or interleaves with
an earlier one that is still alive.
- Disk and worktrees. A full disk (125 MiB free) made hooks fail closed and worktree creation fail
silently; a failed
cd then ran bun install in the main checkout. Check df when anything fails
oddly. Worktree folders can disappear; keep every branch pushed and rebuild from the remote.
- A Playwright spec in serial mode hides later tests after the first failure. Run each new test
alone against the old source when you prove it fails there, and print
did not run counts.
- Phone numbers or ids derived from a run id collide across specs in one run, and a new check
that reads the shared table then refuses a number another spec opted out. Give each spec its own prefix.
- A spec that writes its result artifact in
afterAll loses it on a retry (a fresh worker
overwrites the file). Write one file per test, inside the test.
- Admin routes answer 404 to an anonymous caller and 401 to a bad token. Do not guess 401.
- A merge gate counts an unanswered bot comment as a block. Reply, even if the code is fixed.
- Migration numbers collide. Other sessions take the next number within the hour. Check main's
migration list right before each merge, drop your SQL, journal and snapshot, and regenerate with
the generator so the snapshot chain stays right. Check the SQL is byte for byte the same.
- Never edit
.github/workflows/ in a cost PR where a policy check demands an owner label, and do
not delete test files where a check forbids it. Find another route.
- Check for
gh in a command that has an unset variable. $G pr view with $G empty ran an
unrelated pr program and printed a file instead of failing.
What it adds up to
Do the arithmetic before you promise a number. On this fleet, with 3.8M Worker requests a day, the
request fee alone was about $1 a day ($0.30 per million over 10M a month), before CPU, KV, D1 or
containers. A $50 a month target needs most requests answered without a Worker run: static assets,
an edge block, or fewer visitors. State the floor your levers can reach, with a label that says it is an
estimate, and report measured days beside it.
Measured days on this fleet (billing feed): $126.85 on 2 Nov, $55.50 on 3 Nov (a new period), $17.23 on 4 Nov and
$9.00 on 5 Nov, a 93% cut in three days. Part of that is traffic and billing lumps, not only the levers: requests fell by about
half between 4 and 5 Nov, and the KV write line shows $5.00 on days over one million writes and $0.00 below that. The 5 Nov row was CPU $4.34, D1 rows $1.62, KV reads $1.00, requests $0.90,
container memory $0.60 and KV storage $0.50. Analytics put fleet CPU at $6.98 on 4 Nov and $4.35 on 5 Nov.
The run rate after the levers above is about $7 a day (ESTIMATE), about $210 a month. A $100 month
(about $3.3 a day) and a $50 month (about $1.6 a day) were not reached. My floor estimate on Workers is
$4 to $5 a day, because a Workers plan alone charges $5 a month and traffic is mostly bots that still reach a
Worker unless an edge rule stops them. Reaching $50 needs a change of platform or of traffic, see below.
Leaving Cloudflare (verdict, with numbers)
I priced a move for a fleet of 49 sites: 1.95M requests a day (about 23 a second), 20.7 GB a day served
(0.62 TB a month, 11 KB a request, 6% cached), about 1.1 busy cores at 50 ms per warm request (ESTIMATE),
about 17 GB of memory for 49 Next processes, D1 data near 0.15 GB (the API field may under-report), R2 22 GB.
Prices came from provider pages and third-party summaries on 6 Nov 2026 (the GCP and AWS ones are unverified).
Monthly cost at about $1.10 to the euro (ESTIMATE):
| Option |
Total |
Why |
| Cloudflare now |
about $270 |
measured daily rate times 30 |
| Cloudflare after the levers |
about $190 to 210 |
CPU about $75 to 90 plus D1, KV and requests |
| Hetzner dedicated AX42, one box |
about $95 |
79 euro a month plus a 49 euro setup, unlimited traffic, local SQLite; no failover |
| Hetzner AX42, two boxes |
about $185 |
the same, with failover |
| GCP Cloud Run |
about $350 |
per-request billing like Workers, plus egress at $0.12 a GB and a database |
| GCP VM (8 vCPU, 32 GB) |
about $200 to 270 |
2 to 3 times Hetzner, plus egress |
| AWS Lambda |
about $250 to 300 |
duration, egress at $0.09 a GB, a database; cold starts stay |
| AWS EC2 (8 vCPU) |
about $350 |
plus egress |
Verdict: GCP and AWS cost the same or more than Cloudflare. Only Hetzner dedicated hardware is cheaper, because a
flat rate removes the meters that remain: CPU, rows read, KV operations and cold starts. A move is a rewrite: about
150 files read the Cloudflare environment, 38 use D1, 20 use KV, 11 use R2, and 5 side Workers (cron, fleet, inbound
mail, queue consumer, Stripe router) must move or stay. Estimate 12 to 20 PRs and several weeks, with one-box and
data-loss risk (back up SQLite to R2 with Litestream). The saving today is $0 to $175 a month. It grows with
sites: Cloudflare adds about $0.13 per site per day (ESTIMATE), so at 100 sites it is about $400 to $470 against
$95 to $185 on Hetzner. Even one box (about $95) is above $50 a month. A $50 month on Workers is not reachable
without cutting most traffic at the edge.
Do this before you decide: run one heavy site on one Hetzner box (Next standalone, SQLite) for two weeks and
measure CPU, memory and effort. Decide again at about 80 sites. Hetzner Cloud dedicated-vCPU plans cost more
per core than the dedicated AX line and showed "currently unavailable" when I checked.
Rolling out to many repos
- Run
cf-usage-report for the account. Rank the namespaces and the sites. (Both tools are in the
scripts repo; without them, use the billing call and the GraphQL queries in Measure first, items 1 and 2.)
- Run
cf-cost-scan over every repo. It lists which levers each repo still lacks.
- Do one repo end to end. Prove the saving in the next billing row.
- Open one issue and one PR per lever per repo, under 500 lines each. Do not batch levers.
- After each deploy, compare the same hour of usage. Record MEASURED and TARGET apart.
- Add the local CI checks to each repo so the pattern does not return.
Done when
- Each lever has a PR, a failing test shown first and a passing run.
- The next billing row, not an estimate, shows the change, or the report says it is not yet known.
- The rollout table lists every repo with each lever marked done, not needed, or open.
1---2name: cloudflare-worker-cost-cut3description: Cut the Cloudflare bill of a fleet of Next.js sites on Workers (OpenNext, D1, KV). Use when the bill is high, Worker CPU, KV writes or D1 rows read dominate usage, or you must roll the same savings out to many repos. Covers measuring each meter, the levers ranked by value, and the process traps from a real cut.4metadata:5 source: https://skillmd.com/skills/pooriaarab/cloudflare-worker-cost-cut6---78# Cloudflare Worker fleet cost cut910Measure each meter first. Then change the code that drives the biggest meter.11Keep a measured saving apart from a target. A target is a plan, not a result.1213Read `cloudflare-cost-audit` first for the billing baseline. This skill covers14what to change after the baseline exists, and how to roll it out to many repos.1516Read [optimizations.md](optimizations.md) for each measured cut, grouped by meter.17Each entry gives the signal to search for, the change, the proof and the trap.1819## The meters and what they cost2021Allowances are per account, shared by every Worker in it. Check current prices before you22quote a number.2324| Meter | Price over the allowance | Allowance |25|---|---|---|26| Worker requests | $0.30 per million | 10M |27| Worker CPU | $0.02 per million ms | 30M ms |28| D1 rows read | $0.001 per million | 25B |29| D1 rows written | $1 per million | 50M |30| KV writes | $5 per million | 1M |31| KV reads | $0.50 per million | 10M |32| KV storage | $0.50 per GB | 1 GB |33| Durable Object requests | $0.15 per million | 1M |3435One KV write costs about as much as reading 5,000 D1 rows ($0.000005 against36$0.000000001 a row). Weigh a change in both directions: a change that saves a write but37adds 10,000 row reads loses money. A cached read also costs the KV read fee, about 500 row38reads. Net rows saved per hit = rows saved per read minus 500. Reads to pay back one write =395,000 divided by that net (ESTIMATE). A hit that reads N cached entries pays the fee N times,40and W entries written cost W times 5,000: hits needed = W x 5,000 / (rows saved - N x 500).41Saving 1,000 rows a read with one entry needs about 10 reads in the window. A bigger load pays42back sooner. `optimizations.md` shows the arithmetic.4344KV writes per hour is the check for any KV change. Query `kvOperationsAdaptiveGroups`45with the dimension `datetimeHour`. The hourly reading (MEASURED) showed no write spike after a fleet deploy.46So the idea that a deploy empties the data cache and causes a write wave is not supported.4748To find which D1 queries read the rows, query `d1QueriesAdaptiveGroups` and sort by rows49read. Families found: a category-tree CTE with `json_each`, a full scan of one table, and50per-request COUNT facets. See `optimizations.md`.5152In the fleet this was learned on, the order was: Worker CPU, KV writes, D1 rows read,53requests, KV reads, containers, Durable Objects, subscriptions. Rank yours before you act.5455## Measure first56571. **Billing API.** `accounts/{id}/billable-usage?from=YYYY-MM-DD&to=YYYY-MM-DD` returns daily rows.58 - Each row is ONE DAY of use and that day's cost (`ConsumedQuantity`, `BilledCost`). Cloudflare59 applies the monthly free allowance to the cumulated quantity, so a day that crosses the60 allowance shows a part-free cost. Sum `BilledCost` per day and per service line.61 - The feed returns only the NEW billing period's rows when `from` lies inside the old period, and `to`62 is exclusive. Ask 35 days back and one day past the end, then keep the days you want.63 - A new billing period (`BillingPeriodStart` changes) restores the allowance. The first day of a64 period looks cheaper than it is. Do not compare it with the last day of the old period.65 - The newest day is published late and in pieces. A partial day shows only some lines, often66 D1 first and Workers CPU and KV writes later. Mark it `partial`. Never call a partial sum a67 daily total.68 - Check the feed against analytics. A full-day D1 analytics sum matched the bill to the row69 (63,325,168,002 against 63,325,168,224: 222 rows apart, under one part in 100 million), and Workers CPU matched within 0.01% (576,338,444 ms against 576,290,354 ms billed). Analytics gives usage, not cost: to get cost, apply the monthly allowance to the period's cumulated quantity. Once they agree,70 analytics usage can stand in for the bill's usage on a day the feed has not published.712. **GraphQL analytics** gives the same day as usage, not dollars. Useful datasets:72 `workersInvocationsAdaptive` (requests, CPU), `d1AnalyticsAdaptiveGroups` and73 `d1QueriesAdaptiveGroups` (rows read, per query), `kvOperationsAdaptiveGroups`74 (reads, writes, deletes per namespace), `httpRequestsAdaptiveGroups` (per zone).75 Group by namespace or script, then map ids to names with the list APIs.763. **Per request CPU.** `wrangler tail --format json` shows `cpuTime`, `wallTime`,77 request headers, status and `scriptVersion`. Sample one site for a few minutes per78 path. Workers Observability can also read logs. The tail writes pretty-printed objects back to79 back, not one per line: decode the stream. `cf-traffic-probe ua-cpu <files>` (scripts repo) does80 that and splits CPU by crawler name and route kind. Its other probes read hourly CPU per Worker,81 KV operations and storage per namespace, the top D1 queries by rows read, and zone traffic.824. **Per site spread.** Writes per request varied 40 times between sites (0.09 to 2.15).83 A fleet average hides the two or three sites that make half the bill. Rank by site.845. **Heavy tail.** Ask analytics for `quantiles { cpuTimeP50 cpuTimeP99 }` per script. CPU minus85 (requests times the script's own p50), divided by all CPU, is the heavy-tail share. A share86 above 50% means a few requests cost far more than the rest. On this fleet it was 71%, and the87 likely cause was cold starts (inferred from the cold and warm samples; see lever 0). A trivial request that costs a second or more of CPU, such88 as a redirect or a health check, is the signature.896. **Cold versus warm, measured on the real Worker.** Run `wrangler tail <script> --format json`90 in the background. Send a request with a unique query string to a quiet site, again two91 seconds later, and again after a pause. Read `cpuTime` for each from the tail by URL. The92 first request of an isolate cost 917 ms, the next 48 ms, and a request that landed in a new93 isolate cost 992 ms. Local measurement alone misled us: it measured the warm path.947. **Compare like with like.** Compare the same hour of the day, before and after.95 Traffic and bots change a day-on-day comparison. Find the hour a step happened and set it96 against the merge and deploy times. Our big drop (D1 reads 97B to 2.5B a day) happened 1297 hours before the PRs that we first credited. The cause was a search pause.988. A usage-based run rate is an estimate. A billing row is a measurement. Label each.99100## Levers, ranked by value101102Apply them in this order. Each has the meter it cuts. Measure before and after each one; the103measured effects below are from one fleet and may differ on yours.104105### 0. Cut what a cold start costs (CPU)106107On a fleet of many small Workers, cold starts can be most of the CPU bill. Check the heavy-tail108share first (Measure, item 5). Here it was 71% of all CPU: a cold request cost about 920 to 990 ms109and a warm one about 50 ms, so the bill followed (number of cold starts) times (cost of one).110Each site is its own Worker and each Cloudflare location starts its own isolate, so you mostly cannot111cut how often they start (fewer, larger Workers would share isolates, which is a bigger change). You can cut what a start costs.112- **Bytes may matter, but two measurements disagree.** In a fresh local process the first request had a median of 589 ms (the next 20 had 6.6 ms). In a profiled first request of 642 ms, about 350 ms (55%) was V8 compiling the 25.7 MB OpenNext handler (a plain Node compile took 290 to 300 ms, about 11.5 ms per MB) and the rest was real start-up work. A plain Node compile suggests about 230 ms more for 20 MB more code. The slope test below measured about 70 to 90 ms more. Treat bytes as a possible lever, not the main one.113114 Lazy `import()` does not help: OpenNext inlines dynamic imports into the same file.115- **A bundle-size slope test, so far unproven either way.** I appended 10 MB and 20 MB of never-called116 functions to a 25.8 MB handler, then timed one cold request per fresh local D1. The first request moved117 from about 1.26 s with no extra code to 1.23 to 1.33 s with the function arms and 1.35 to 1.38 s with the118 data arms (wall time; the local worker reports CPU only as 0 or 1000 ms, a one-second resolution). That test was weak (7 of 15 runs got the local 429 and measured119 nothing, one or two valid samples per arm, and lazy parsing may hide a real cost), and the profile120 of the first request put 48% in V8 "(program)" time. Run a clean slope test before you spend121 a week on bytes, and read the V8 profile with `scripts/startup-profile.ts`.122- **Find what fills the bundle.** On this fleet Turbopack copied shared modules into each route group123 (zod core 20 times, an app schema module 20 times), better-auth, drizzle and kysely were bundled124 once per rsc and ssr layer, and a 0.94 MB block of legacy encoding tables came from Next's body125 parser. Try a webpack build, which shares chunks. Keep client-only libraries (maps, editors) out126 of server-evaluated code.127- **Test `minify` (unconfirmed).** One local sample found the first request about 40% cheaper with128 Wrangler's `minify` off (530 ms against 900 ms), at the price of a larger gzip. That sample came from a different local build129 than the 589 ms median above (one with `minify` on, one with it off), so do not compare the two numbers. That goes against130 the bytes lever above. A small production A/B (4 cold requests on the old bundle, 5 on the new)131 showed a large drop. It is MEASURED, but the samples are few and the kept logs cannot reproduce it.132 But fleet CPU per request did not change: 71.5 ms on both days, same hours (MEASURED).133 Keep it unconfirmed.134 Compare the same hours across days before you credit a change. Deploy it to one135 site and read `cpuTime` from the tail before you roll it out.136- **A region pin per site is a switch, and its benefit is unproven.** An early test set a placement region137 through the API; it was rewritten as `mode: targeted` and the home page went from 0.2 s to 3.3 s.138 A later per-site variable that writes `placement.region` into the rendered config gave mixed one-hour139 results (CPU per request fell on three sites, was flat on two and rose on one). A same-hours, cross-day140 check over 27 pinned and 22 unpinned sites could not separate the pin from the crawler blocks made in the141 same days (`optimizations.md`). Pin one site, compare the same hours against an unpinned control, and142 undo it where it does not help. Save the old setting first.143144### 1. Stop bot and router noise (CPU, requests, D1)145146- **Turn off link prefetch.** Next prefetches RSC payloads for every visible link. Bots and147 crawlers multiply it. Make the shared `Link` component default to `prefetch={false}`.148 Measured on one site: `_rsc` requests fell from 9% of traffic to 0.149- **Refuse a bare `_rsc` request.** A real router request sends `?_rsc=` and an `RSC`150 header. A request with the parameter and no header is a bot replay. Answer 404 with151 `Cache-Control: no-store` before the cache and before any render, for GET and HEAD.152 Put the guard first in the Worker entry. A WAF rule is cheaper still, but it needs a token153 with Zone WAF permission (see the token bullet below).154- **Pause staging and search jobs.** Staging sweeps and search jobs burn requests with no user.155 A per-minute cron for every site was about 1% of CPU on this fleet (ESTIMATE).156 Measure before you spend a PR on it.157158- **Block a client by what it sends, on the Cloudflare edge, before the Worker runs.** Traffic was very159 concentrated: one IP with an empty `User-Agent` sent 43% of a site's requests and another 60% of a160 second site's. A zone custom rule `(http.user_agent eq "" and not starts_with(http.request.uri.path, "/api/"))`161 with action `block` stops them with no Worker run. Do it safely, zone by zone:162 1. Check analytics first for empty-user-agent traffic outside `/api/` that you want. Examples are163 an uptime monitor, a webhook and a health check. They can send no user agent.164 2. `GET /zones/{id}/rulesets/phases/http_request_firewall_custom/entrypoint` and save the answer to165 a file. A `PUT` to that entrypoint REPLACES every custom rule on the zone: send back all the166 existing rules plus yours, or add yours with `POST .../rulesets/{ruleset_id}/rules`. The free plan167 allows 5 custom rules per zone; check there is room.168 If the GET returns 404 (a zone with no custom rules yet), create the entrypoint with a `PUT` that holds169 only your rule.170 3. Give the rule a stable `ref` so it can be found and removed later, and record the zones.171 4. To undo, `DELETE .../rulesets/{ruleset_id}/rules/{rule_id}` for the rule with your `ref`, or `PUT` the172 saved entrypoint back.173 5. Verify on each zone: an empty user agent gets 403, a normal request and the AI crawlers you want174 get 200, and `/api/` still answers.175176 The free plan refuses a custom block response ("not entitled to use a custom response"), so a block177 cannot carry a pointer to your API; use the Worker for that.178- **Do not block AI crawlers by user agent if your product tells owners to let them in.** Our own179 audit tool told site owners to let GPTBot, ClaudeBot and similar agents reach the homepage.180 Rate-limit by behaviour, or leave them.181- **The token needs permission.** The fleet token had no WAF permission (`request is not authorized`).182 All 50 token slots were in use. Do not revoke a live deploy token to make room. Prefer a separate,183 narrow WAF token when a slot is free. If none is free, extend the existing zone-wide policy of the184 token that already has zone access, with a token that can edit tokens: `PUT /user/tokens/{id}`185 REPLACES the whole token, so (1) `GET` the full token object and save it to a file; (2) send back186 the same object with only `Zone WAF Read` and `Zone WAF Write` added to a policy that already covers187 all zones, keeping `name`, `status`, `condition` (IP limits), `not_before` and `expires_on` exactly (look up the188 group ids with `GET /user/tokens/permission_groups`; a policy names groups by id); (3) read it189 back and compare name, status, condition, expiry and every permission by NAME, not by position190 (the API reorders policies); (4) to undo, `PUT` the saved object. Verify the token still works.191 Note that this gives that token WAF write on every zone: that is the cost of not using a new token.192193### 2. Cut KV writes (KV writes)194195KV writes in an OpenNext app come from the incremental cache. Each cache miss writes an196entry. Pages that are `force-dynamic` still write the data cache through `unstable_cache`.197198- **Do not cache the long tail.** A key built from the full filter JSON, a page number above199 1, a free-text query or a rare place and category pair is read once, if ever. Measured:200 98% of geo page requests were unique within 3 minutes. Call the loader directly for these.201 Keep the cache for head pages that many visitors read.202- **Use fewer, coarser keys.** Merge small counts that one page reads together. Do not merge203 if a head key grows past about 25 KB or if the data has different invalidation.204- **Raise the data cache window.** A short window rewrites long-lived keys every few205 minutes. If data changes only by import and every write path calls `revalidateTag`, use a206 day. Keep the edge page cache window separate. A constant shared by both turns a data207 decision into a stale page decision. The KV retention must be at least the window.208- **Skip a write when the value is unchanged.** Read the stored value first. A read costs a209 tenth of a write. Refresh the entry before it is about half its retention age, or a210 valid entry can expire while it is in use.211- **Audit every write path** before you lengthen a window: claim, edit, tier change,212 import, delete, admin tools, webhooks. Each must call the revalidate helper.213- **Add a check** to local CI that fails when a new cached key embeds `JSON.stringify` of a214 free-form object without an explicit opt-in comment. Without it the pattern returns.215216### 3. Cut D1 rows read (D1 rows read)217218- **Put a per-request row budget** at the Worker entry. Count rows read per request. Run it in219 log-only mode first. Then set a cap for each route from the measured maximum rows. One query220 family read up to 190,000 rows in one run. A cap below the real maximum turns a valid page or221 sitemap build into a 503.222- **Store counts at import.** Counts for facets, places and categories rarely change. Write223 them to a table when you import. Do not compute them with a group query per request.224- **Beware head-of-line blocking.** D1 runs queries one after another. One sitemap build ran225 nine queries that read 300,000 to 693,000 rows each and took 1 to 1.7 s each. Every other226 request queued behind them and was refused as overloaded. Find the one heavy burst; do227 not blame the row cap without a log line that names the cause.228- **Prove a count needs no query.** The sitemap index needs only the shard count.229 A cheap upper bound, such as the published listing count, proves one shard. Run the heavy230 count only when the bound exceeds the shard size.231- **Cache the sitemap index** in KV with a hash. Serve a fresh copy with no D1 read. Serve a232 stale copy at once and rebuild in the background behind a short lock. If the build fails and233 nothing is stored, serve a degraded index built from config alone, with a header that234 marks it and `no-store`. Never let the edge cache store the degraded copy.235236### 4. Cut warm Worker CPU (CPU)237238Do this after lever 0. Measure on cold, uncached pages in production (a unique query string per239request, read `cpuTime` from `wrangler tail`), not on a warm local server.240- A markdown page cost about 24 ms against about 67 ms for HTML on cold pages (median), so serving241 markdown to AI agents would save about 40 ms a request. That is an estimate of about $0.04 a day242 on a site where AI crawlers were 42% of requests (the 40 ms comes from a small cold sample). An older sample had said 8 to 12 times; it compared different pages. Do not243 build a feature on a saving you have not measured on matched pages.244- Cutting the HTML and RSC payload by 42% and 68% left warm render time about 10% lower, measured locally on demo data. Payload245 bytes are not CPU. They cost bandwidth, which Workers do not bill.246- Dynamic `robots.txt` and `llms.txt` cost about 200 ms a hit on one site, but this too was mostly247 cold start; serving static files helps only for files that were not edge cached.248249250### 5. Publish the long tail as static files (CPU, requests, D1, KV)251252Workers Static Assets serve files with no Worker run. Requests for static assets are free.253This removes the CPU, the D1 reads and the KV write for those pages.254255- Pilot on one site first. Learn the limits before a full build: file count, total size,256 and generation time (estimated 2.2 to 5.7 hours serial for one large site).257- Use `_headers` for cache headers and a trailing slash rule so URLs match the dynamic ones.258- Keep dynamic routes for pages that need data per visitor.259260### 6. Block named crawlers and facet crawls (requests, CPU, D1)261262A tail split by crawler name found QlyzeBot at 33% of the sampled CPU on six heavy sites and GPTBot on263`/search` facet links at about one request a second. Put the polite ones in `robots.txt` and the264rest behind an edge rule that runs before any Worker. Details, proof and traps in `optimizations.md`265("Name the crawlers that cost money"). Add the rule to the site launch step.266267### 7. Clean KV storage and read the KV cache through the regional cache (KV storage, KV reads)268269KV storage was 38.6 GB, 34 GB of it legacy cache entries that never expire and that no deploy reads. Swap the270namespace; do not delete the keys one by one. A regional Cache API wrapper cut repeat KV reads on a page271from 6 to 0. Details and traps in `optimizations.md` ("KV storage", "Read the KV cache through the regional Cache API").272273## Process traps (rolled out as checks where possible)274275- **Honest targets.** An adversarial review refuted a "$50 a month" claim: the run rate was276 about $520 a month. Say what is measured, what is an estimate and what is a target.277- **Judge a delegated job on its diff.** A worker can exit 0 and write nothing. Rerun the278 tests yourself. A test that cannot fail proves nothing. Mutation-test it: break the code279 on purpose and watch the test fail, then restore the code.280- **Write the failing test first** and show it fail. Register tests with281 `if (!REMOTE) { ... }`. A repo policy may reject `test.skip`.282- **Do not trust "completed".** Check the exit code of every build and test.283- **E2E hygiene.** Two worktrees run on the same default ports and collide. Pass your own284 ports. A Miniflare cache that is not empty can fail a spec with `STALE`: clear it between285 runs. Production-build test servers set `ENVIRONMENT=production`, so a test hook gated on286 "not production" never runs there.287- **Test hooks in production code** need a guard that no Worker secret can turn on, and a288 local CI check that scans configs for the hook name.289- **Do not rerun an old run's failed deploy jobs.** They can redeploy an older commit. A290 newer push redeploys. A `fetch failed` in a deploy job was transient.291- **Merge gate.** Read both the reviews and the review comments. Check the review is for292 the head SHA, that the SHA has its own check runs and that no Critical or Major is open.293 Merge with `--match-head-commit`.294- **Prompts.** Pass a long prompt to a CLI by stdin. A variadic `--allowedTools` flag295 swallows a prompt given as an argument: `claude -p --allowedTools A B C "prompt"` reads the296 prompt as a tool name. Write prompt files with the Write tool, since a297 hook can block prompt text typed in a shell.298- **Commit messages with a dollar sign.** In double quotes, `$0.000025` becomes299 `/bin/zsh.000025`. Use single quotes.300- **GraphQL errors in `gh`.** `gh pr edit` and `gh pr review` can fail with a GraphQL error.301 Use the REST API: `gh api -X PATCH repos/OWNER/REPO/pulls/N -F body=@file`, and302 `POST repos/OWNER/REPO/pulls/N/reviews`.303- **Assert the one counter that proves the claim.** A spec that compares D1 read counts304 between two views can pass for other reasons. Assert the counter for the query you305 changed, such as the listing query count.306- **Review the callers of a cache rule you change.** A cache rule that skips the long tail307 can make a head page uncached if that page shares the key shape.308- **A review gate may read plain lines.** A gate can match `Reviewed-by:` and `Verdict:`309 lines only. A bold verdict line is not matched.310- **Sandboxes (Boat).** A box needs the right language runtime version, the site setting,311 and a real copy of any folder that is a symlink in the repo. Agent logins inside a box can312 expire. A new repository may need its environment created first, and the repo list may need313 a refresh in the dashboard.314- **Billing reads need a clear window.** A frozen feed is often a misread: check the row315 date, not only the number.316317### Traps from running many workers at once318319- **Write briefs with a file tool or a quoted heredoc (`<<'EOF'`).** An unquoted heredoc runs every320 backticked command in the brief in your own shell and leaves the worker a brief with holes.321- **In zsh, `set -- $var` does not split words.** Use a function with explicit arguments or an array.322- **`pkill -f` kills other jobs.** Kill by process id. Killing the wrapper of a CLI agent does not323 kill the agent: find live agents by their working directory (`lsof -p <pid> | grep cwd`) before you324 start a second one in the same worktree, or the two collide and both stop.325- **One log file per run.** A later run that writes the same log file overwrites or interleaves with326 an earlier one that is still alive.327- **Disk and worktrees.** A full disk (125 MiB free) made hooks fail closed and worktree creation fail328 silently; a failed `cd` then ran `bun install` in the main checkout. Check `df` when anything fails329 oddly. Worktree folders can disappear; keep every branch pushed and rebuild from the remote.330- **A Playwright spec in serial mode hides later tests after the first failure.** Run each new test331 alone against the old source when you prove it fails there, and print `did not run` counts.332- **Phone numbers or ids derived from a run id collide across specs in one run**, and a new check333 that reads the shared table then refuses a number another spec opted out. Give each spec its own prefix.334- **A spec that writes its result artifact in `afterAll` loses it on a retry** (a fresh worker335 overwrites the file). Write one file per test, inside the test.336- **Admin routes answer 404 to an anonymous caller and 401 to a bad token.** Do not guess 401.337- **A merge gate counts an unanswered bot comment as a block.** Reply, even if the code is fixed.338- **Migration numbers collide.** Other sessions take the next number within the hour. Check main's339 migration list right before each merge, drop your SQL, journal and snapshot, and regenerate with340 the generator so the snapshot chain stays right. Check the SQL is byte for byte the same.341- **Never edit `.github/workflows/` in a cost PR** where a policy check demands an owner label, and do342 not delete test files where a check forbids it. Find another route.343- **Check for `gh` in a command that has an unset variable.** `$G pr view` with `$G` empty ran an344 unrelated `pr` program and printed a file instead of failing.345346## What it adds up to347348Do the arithmetic before you promise a number. On this fleet, with 3.8M Worker requests a day, the349request fee alone was about $1 a day ($0.30 per million over 10M a month), before CPU, KV, D1 or350containers. A $50 a month target needs most requests answered without a Worker run: static assets,351an edge block, or fewer visitors. State the floor your levers can reach, with a label that says it is an352estimate, and report measured days beside it.353354Measured days on this fleet (billing feed): $126.85 on 2 Nov, $55.50 on 3 Nov (a new period), $17.23 on 4 Nov and355$9.00 on 5 Nov, a 93% cut in three days. Part of that is traffic and billing lumps, not only the levers: requests fell by about356half between 4 and 5 Nov, and the KV write line shows $5.00 on days over one million writes and $0.00 below that. The 5 Nov row was CPU $4.34, D1 rows $1.62, KV reads $1.00, requests $0.90,357container memory $0.60 and KV storage $0.50. Analytics put fleet CPU at $6.98 on 4 Nov and $4.35 on 5 Nov.358The run rate after the levers above is about $7 a day (ESTIMATE), about $210 a month. A $100 month359(about $3.3 a day) and a $50 month (about $1.6 a day) were not reached. My floor estimate on Workers is360$4 to $5 a day, because a Workers plan alone charges $5 a month and traffic is mostly bots that still reach a361Worker unless an edge rule stops them. Reaching $50 needs a change of platform or of traffic, see below.362363## Leaving Cloudflare (verdict, with numbers)364365I priced a move for a fleet of 49 sites: 1.95M requests a day (about 23 a second), 20.7 GB a day served366(0.62 TB a month, 11 KB a request, 6% cached), about 1.1 busy cores at 50 ms per warm request (ESTIMATE),367about 17 GB of memory for 49 Next processes, D1 data near 0.15 GB (the API field may under-report), R2 22 GB.368Prices came from provider pages and third-party summaries on 6 Nov 2026 (the GCP and AWS ones are unverified).369Monthly cost at about $1.10 to the euro (ESTIMATE):370371| Option | Total | Why |372|---|---|---|373| Cloudflare now | about $270 | measured daily rate times 30 |374| Cloudflare after the levers | about $190 to 210 | CPU about $75 to 90 plus D1, KV and requests |375| Hetzner dedicated AX42, one box | about $95 | 79 euro a month plus a 49 euro setup, unlimited traffic, local SQLite; no failover |376| Hetzner AX42, two boxes | about $185 | the same, with failover |377| GCP Cloud Run | about $350 | per-request billing like Workers, plus egress at $0.12 a GB and a database |378| GCP VM (8 vCPU, 32 GB) | about $200 to 270 | 2 to 3 times Hetzner, plus egress |379| AWS Lambda | about $250 to 300 | duration, egress at $0.09 a GB, a database; cold starts stay |380| AWS EC2 (8 vCPU) | about $350 | plus egress |381382Verdict: GCP and AWS cost the same or more than Cloudflare. Only Hetzner dedicated hardware is cheaper, because a383flat rate removes the meters that remain: CPU, rows read, KV operations and cold starts. A move is a rewrite: about384150 files read the Cloudflare environment, 38 use D1, 20 use KV, 11 use R2, and 5 side Workers (cron, fleet, inbound385mail, queue consumer, Stripe router) must move or stay. Estimate 12 to 20 PRs and several weeks, with one-box and386data-loss risk (back up SQLite to R2 with Litestream). The saving today is $0 to $175 a month. It grows with387sites: Cloudflare adds about $0.13 per site per day (ESTIMATE), so at 100 sites it is about $400 to $470 against388$95 to $185 on Hetzner. Even one box (about $95) is above $50 a month. A $50 month on Workers is not reachable389without cutting most traffic at the edge.390391Do this before you decide: run one heavy site on one Hetzner box (Next standalone, SQLite) for two weeks and392measure CPU, memory and effort. Decide again at about 80 sites. Hetzner Cloud dedicated-vCPU plans cost more393per core than the dedicated AX line and showed "currently unavailable" when I checked.394395## Rolling out to many repos3963971. Run `cf-usage-report` for the account. Rank the namespaces and the sites. (Both tools are in the398 scripts repo; without them, use the billing call and the GraphQL queries in Measure first, items 1 and 2.)3992. Run `cf-cost-scan` over every repo. It lists which levers each repo still lacks.4003. Do one repo end to end. Prove the saving in the next billing row.4014. Open one issue and one PR per lever per repo, under 500 lines each. Do not batch levers.4025. After each deploy, compare the same hour of usage. Record MEASURED and TARGET apart.4036. Add the local CI checks to each repo so the pattern does not return.404405## Done when406407- Each lever has a PR, a failing test shown first and a passing run.408- The next billing row, not an estimate, shows the change, or the report says it is not yet known.409- The rollout table lists every repo with each lever marked done, not needed, or open.