Give every app its own credential, put a budget and a model allow-list on each, and let all traffic pass through one endpoint so the real provider keys never leave it. This post describes a small gateway layer I run for my own projects, in front of Cloudflare AI Gateway. It is based on the project's own README, it is not a product pitch, and it is not a service I sell on its own. Checked on 2026-12-05; Cloudflare product behaviour changes, so confirm against the Cloudflare docs before copying the approach.
The problem
Once more than one thing calls language models, ordinary problems appear:
- Keys spread. The provider key ends up in
.envfiles, in a coding assistant's settings, in a CI job and in an app's config. Rotating it means finding every copy. - Nobody knows which app spent what. The provider bill shows one total.
- A loop can burn money. A bug, a runaway agent or a stuck retry can use a month of budget in an afternoon.
- Model choice is scattered. Each tool hard-codes a model name.
None of this is hard to solve in principle. It needs a single point that every request passes through.
The design
Each app or tool gets its own credential and talks to one OpenAI-compatible endpoint. That endpoint is a small service that checks the credential, applies limits and forwards the request to Cloudflare AI Gateway, which sits in front of the model providers.
app --OpenAI-style API--> gateway layer --> Cloudflare AI Gateway --> model provider
The apps never see the Cloudflare token or the provider keys. It runs as a Cloudflare Worker with a D1 database, and it is deliberately small.
What happens to each request
- Authenticate. The caller sends a bearer credential. Only its SHA-256 hash is stored.
- Guard. Check requests per minute, the credential's daily, weekly and monthly budget, and a global budget. Over budget, the request is refused with
429 budget_exceeded, or switched to the credential's fallback model if that option was chosen. - Resolve the model. An alias such as
cheap,fast,premiumorauto/codingexpands to an ordered list of candidate models, filtered by what the credential may use. A specific model works if it exists in the catalogue. - Forward to the gateway with metadata (project, credential, request id). If an upstream model returns a server error, a rate limit or not-found, the next candidate is tried. Streams pass through untouched, and the option that makes the final chunk report usage is injected so streamed calls are still counted.
- Record tokens and an estimated cost.
Response headers say which model actually answered and whether fallbacks happened, which makes debugging easier.
Why per-app credentials matter
Each credential has its own budget, rate limit, allowed models, default and fallback model, and optional expiry. That gives you what one shared key cannot:
- Credentials can be limited to the models and budgets that suit the tool (the portal offers presets such as Cheap, Coding, Premium coding and Reasoning).
- If one credential leaks, you disable or rotate only that one.
- The dashboard shows spend per project and per credential.
When a credential is created, the key is shown once with copy-ready snippets for environment variables, cURL, Python and Node. After that only the hash exists.
Two accounts, one public address
One detail from real cloud work: Cloudflare only allows a Worker custom domain inside the account that owns the DNS zone. In this setup the app and its AI billing live in one Cloudflare account while the domain lives in another. The fix is a tiny edge Worker in the domain's account that relays requests to the app and adds a shared secret header. The app refuses requests without it, so the only public entry point is the custom domain. It is a small example of a structural decision that is easy to get wrong when deploying on Cloudflare.
Default setup and the honest limits
| Area | What it does | Limit |
|---|---|---|
| Models | Default setup uses Workers AI models only; Anthropic, OpenAI and OpenRouter rows exist but are disabled until a provider key is set | Enable them deliberately |
| Cost | Estimated from token counts and a price table; Cloudflare's own cost is synced back for comparison | Prices must be kept current; a model with a zero price counts as free |
| Budgets | Enforced from the Worker's own ledger, because Cloudflare's spend limits had no public API | Add gateway-side limits in the Cloudflare dashboard as a second guard rail |
| Rate limit | A 60-second sliding count of recorded requests | Concurrency is not limited |
| Keys | Hashed with SHA-256 | A lost key cannot be recovered, only rotated |
I would rather be upfront about these than pretend a small tool is a full billing system.
If you want to do this for your own team
You do not need this code to get most of the benefit. In rough order of value:
- One credential per app or person, never a shared provider key.
- A budget on each credential with a clear failure mode: block, or fall back to a cheaper model.
- An allow-list of models per credential.
- Aliases (
cheap,premium) so you can change models in one place. - A log of usage by project. Even a spreadsheet beats nothing.
- Hashed storage and rotation for the keys you issue.
- Data review. Before sending customer or staff data to any model provider, check the provider terms and your obligations under Malaysia's PDPA.
Common questions
Why not share one provider key? Rotation and cost tracking become guesswork.
What happens over budget? A 429 budget_exceeded response, or a cheaper fallback model, depending on the credential.
Are the costs exact? No, they are estimates.
Can a lost key be recovered? No, only rotated.
If you would rather have it built and kept running
If you want AI features or automation inside a system, I build them as part of custom system development (see also AI integration), and the monthly maintenance contract, from about RM3,000 per month (estimate, confirmed after scoping), covers keeping them updated afterwards. You can reach me on the hire page. For budgeting a whole system, see what custom development and maintenance cost in Malaysia.