cloudflare-caution
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinesecloudflare-caution
cloudflare-caution
Cloudflare で請求が膨らまない設計にするための規則である。
- 結果が同じになる処理を、リクエストのたびに動かさない
- 暴走したときに止まる仕組みを、コードと設定に入れる
- 課金される単位で費用を見積もり、本番の使用量で確かめる
Rules for designing on Cloudflare so that bills do not balloon.
- Do not run processes that produce the same result on every request
- Add safeguards against runaway execution in both code and configuration
- Estimate costs based on billable units and verify them against production usage
この skill が必要な理由と達成したい状態
Why this skill is needed and the desired outcome
この skill が必要な理由は、Cloudflare の課金がリクエスト、行、操作、ログのイベントといった細かい単位の従量で、しかも支出に上限が無いことにある。どの単位も 1 回あたりは安いので、書いている時点では気にならない。けれど閲覧のたびに SSR や API や DB を動かす設計では、費用がアクセス数に比例して伸びる。ループや再試行のバグがあれば、その回数がそのまま請求になる。予算アラートは知らせるだけで、止めてはくれない。
この skill で達成したい状態は、1 回のアクセスにかかる費用が設計の段階で決まっていることである。バグやボットで想定を外れても、請求になる前にコードと設定が止める。
This skill is needed because Cloudflare bills for fine-grained usage units such as requests, rows, operations, and log events, with no spending cap. Each unit is inexpensive on its own, so the cost is easy to overlook while building. However, a design that runs SSR, APIs, or a database for every view makes costs grow proportionally with traffic. If there is a bug in a loop or retry logic, every iteration becomes billable. Budget alerts notify you, but they do not stop spending.
The desired outcome of this skill is for the cost per visit to be determined at the design stage. Even if bugs or bots exceed expectations, the code and configuration should stop the activity before it becomes billable.
単価と課金の仕組み
Unit prices and how billing works
pricing-trapsAlso read . It summarizes unit prices, the lack of spending caps, and the conditions under which Static Assets do not invoke a Worker.
pricing-traps同じ結果の作り置き
Materializing reusable results
閲覧のたびに同じものを作り直すと、Worker の起動、CPU 時間、DB の行がアクセス数に比例して課金される。作り置けるものは作り置いて配る。
- 誰が見ても同じ公開ページは、ビルド時にプリレンダーして静的アセットで配る。静的アセットへのリクエストは Worker を起動しないので課金されない
- 公開の静的サイトは、Worker のコードを持たないアセットだけの Worker で配る。R2 や Worker を通る配信を、公開ページの主な経路にしない
- 「無料枠に収まる」は、公開ページを課金される経路で配る理由にしない。アクセスが急に増えれば無料枠は超える
- CSP の nonce を使うと、HTML をリクエストごとに作ることになる。公開の静的ページでは nonce に頼らず、inline の script を外部ファイルに出して、全ページ共通の CSP を で付ける。ページごとのハッシュを
_headersに並べる形は、ルール数の上限(100)でいずれ破綻する_headers - は、認証や API のパスだけに絞る。全体に掛けると、静的アセットへのリクエストもすべて Worker の課金に変わる
assets.run_worker_first - 閲覧者ごとに変わる部分だけを動的にする。ページ全体を動的にしない
- 動的なデータは、変わる頻度に合わせて CDN のキャッシュ、Cache API、KV に置く。リクエストのたびに D1 や外部 API を呼ばない
- クライアントでは、データが変わらない間は再取得しない。TanStack Query なら を設定する
staleTime
Recreating the same result for every view causes Worker invocations, CPU time, and database rows to scale with traffic and become billable. Precompute and distribute anything that can be precomputed.
- For public pages that are identical for everyone, prerender them at build time and serve them as Static Assets. Requests for Static Assets do not invoke a Worker and are therefore not charged
- Serve public static sites from an asset-only Worker with no Worker code. Do not make delivery through R2 or a Worker the primary path for public pages
- “Fits within the free tier” is not a reason to serve public pages through a billable path. A sudden increase in traffic will exceed the free allowance
- Using a CSP nonce requires generating HTML for every request. For public static pages, do not rely on nonces. Move inline scripts to external files and apply a shared CSP to all pages through . Listing per-page hashes in
_headerswill eventually break because of the rule limit of 100_headers - Limit to authentication and API paths. Applying it globally makes requests for Static Assets subject to Worker billing as well
assets.run_worker_first - Render only the parts that change per viewer dynamically. Do not render the entire page dynamically
- Store dynamic data in the CDN cache, Cache API, or KV according to how frequently it changes. Do not call D1 or an external API on every request
- Do not refetch data on the client while it remains unchanged. If using TanStack Query, configure
staleTime
暴走の歯止め
Safeguards against runaway execution
支出の上限が無いので、止める仕組みは自分で入れるしかない。
- Worker には を付ける。値は本番の CPU 時間の p99 を測って、その少し上にする。上限まで上げると、無限ループがそのまま請求になる
limits.cpu_ms - 公開する API、認証、書き込みの口の前段には、レート制限を置く。ボットの大量アクセスは、レート制限が無ければすべて課金される
- レート制限は、ゾーンを持つリポでは WAF のレート制限ルールで、持たないリポでは Workers の Rate Limiting バインディングで掛ける
- Queue の consumer、Durable Object の alarm、再試行の処理は冪等にする。自分自身を再投入しない
- 再投入と再試行には回数の上限を付ける
- アカウントに予算アラートを設定する。止めるためではなく、早く気づくためである
Because there is no spending cap, you must add your own mechanisms to stop runaway activity.
- Add to Workers. Measure the p99 CPU time in production and set the limit slightly above it. Raising the limit too high allows an infinite loop to become billable
limits.cpu_ms - Put rate limiting in front of public APIs, authentication, and write endpoints. Without rate limiting, all high-volume bot traffic becomes billable
- For repositories that have a zone, use WAF rate-limiting rules. For repositories without a zone, use a Workers Rate Limiting binding
- Make Queue consumers, Durable Object alarms, and retry processing idempotent. Do not allow them to re-enqueue themselves
- Set attempt limits for re-enqueueing and retries
- Configure budget alerts on the account. Use them to detect unexpected spending quickly, not to stop it automatically
書き込みと操作の削減
Reducing writes and operations
書き込みと一覧の操作は、読み取りより 1 桁から 3 桁高い。
- KV の書き込み、D1 と Durable Objects の行の書き込みは、まとめて書く
- 値が変わっていなければ書かない
- KV の をリクエストのたびに呼ばない。キーで直接引けるように設計する
list() - Durable Object は、WebSocket Hibernation と alarm を使って眠らせる。起きている間は、使っていなくても 128 MB 分の時間が課金される
- Durable Object を や外向きの接続で起こしたままにしない
setTimeout - R2 の Infrequent Access は、書き込みや読み取りの多い小さいファイルに使わない。操作の単価が Standard より高い
Writes and list operations can cost one to three orders of magnitude more than reads.
- Batch KV writes and D1 and Durable Objects row writes
- Do not write a value if it has not changed
- Do not call KV on every request. Design the system to retrieve values directly by key
list() - Put Durable Objects to sleep using WebSocket Hibernation and alarms. While awake, the full 128 MB allocation is billed even if it is not being used
- Do not keep Durable Objects awake with or outbound connections
setTimeout - Do not use R2 Infrequent Access for small files that are written and read frequently. Its per-operation cost is higher than Standard
ログとトレースの間引き
Filtering logs and traces
ログもトレースも、量に応じて課金される。
- 全リクエストのログを Cloudflare に保存し続けない。必要な量だけを でサンプリングする
head_sampling_rate - 外部へ送るだけなら にする
persist: false
Logs and traces are both billed based on volume.
- Do not continuously store logs for every request in Cloudflare. Sample only the required volume with
head_sampling_rate - If logs are only being sent externally, use
persist: false
見積もりと本番での確認
Estimation and production verification
measure-dont-guess に従う。
- 設計を決める前に、想定のアクセス数に 1 回あたりの Worker の起動・行・操作・ログの数を掛けて、月額を見積もる
- デプロイの後は、ダッシュボードの Billable Usage か GraphQL Analytics API で本番の使用量を見る。見積もりとずれていれば、設計を見直す
Follow measure-dont-guess.
- Before finalizing the design, multiply the expected traffic by the number of Worker invocations, rows, operations, and log events per visit to estimate the monthly cost
- After deployment, review production usage through the dashboard's Billable Usage view or the GraphQL Analytics API. If actual usage differs from the estimate, revisit the design