AI Gateway · Exercise 03
Cap requests and spend
See how Unified Billing and stored keys pay for inference, cap request volume with a rate limit, and enforce a dollar spend limit per team.
Paste this into your agent
Copied! Now paste it into your agent. No agent yet? Here's how to get one.
Cap requests and spend
People aren’t the only ones calling your AI endpoints anymore — background jobs and autonomous agents call models in loops, and agents have no concept of money. Putting rate limits and dollar budgets in AI Gateway stops a runaway caller or an over-budget team with 429 Too Many Requests before it runs up your bill, while leaving every other team working.
What you’ll build
A gateway-wide request rate limit and a metadata-scoped spend limit (team = "interns") that blocks one team once its budget is spent while allowing "escalations" requests through.
Prerequisites
- You’ve completed Cache responses and still have that Worker and gateway.
Two ways to pay: stored keys vs. Unified Billing
When your gateway calls third-party providers (like OpenAI, Anthropic, or Google), you can pay in two ways:
- Bring Your Own Keys (BYOK): store your provider API keys centrally in the gateway instead of inside each app. Each provider bills your account with them directly.
- Unified Billing: load prepaid credits into your Cloudflare account and call models across providers on a single Cloudflare bill, without opening a separate account at every vendor. Provider token rates are passed through with no markup (credit purchases carry a 5% fee).
The gateway checks credentials in a fixed order — a key on the request, then a stored key, then Unified Billing credits — so each request is paid through one path and never double-billed.
Two kinds of ceilings: rate limits and spend limits
You can cap traffic on your gateway by request count or by dollar spend. Adding rate and spend limits to the pipeline from Exercise 2 stops over-budget or runaway callers on a cache miss before they reach the model provider:
- Rate limiting caps the number of requests the gateway accepts in a time window (for example, 60 requests per 60 seconds). A
fixedwindow resets on the clock; aslidingwindow counts the trailing window whenever a request arrives. - Spend limits cap dollars spent over a time window, and can be filtered or split by
metadatakeys (team,user, oragent_id):
Spend limit rule (team = interns){
"id": "interns-monthly-budget",
"enabled": true,
"limitType": "cost",
"limit": 10,
"window": 2592000,
"technique": "fixed",
"metadata": {
"team": { "mode": "filter", "values": ["interns"] }
}
}
Because a request’s token cost is only known after it finishes, spend limits are enforced right after completion — a simultaneous burst can briefly overshoot the limit before subsequent requests get 429.