Cloudflare AI Gateway: put a proxy in front of your LLM calls
By Flavio
Updated
Tagged: Cloudflare
Learn how Cloudflare AI Gateway sits between your application and AI models, then route and inspect a real request through a Worker.
Sending a prompt to an AI model is the easy part. You call an API and get a response back.
The headaches start when real users hit your app. Suddenly you need to know which requests failed, how much they’re costing you, and whether one user is hammering an endpoint.
Cloudflare AI Gateway sits in front of those calls and gives you that control.
In this tutorial, we’ll look at what an AI gateway does, then route a real Workers AI request through one and inspect the result in the dashboard.
What is an AI gateway?
An AI gateway sits between your app and the AI model you’re calling.
Without a gateway, your request goes straight to the model provider:
your application -> model provider
With a gateway in place, the request makes one extra hop:
your application -> AI Gateway -> model provider
The response comes back along the same path.
Your app still sends prompts and gets model output back, while the gateway watches and controls the traffic in between. It’s the same idea as putting a reverse proxy in front of a web server: you get one place to handle logging, caching, limits, and routing without changing the app itself.
What AI Gateway is not
AI Gateway isn’t an AI model. It won’t make a weak model smarter or rescue a bad prompt, and it doesn’t store application data the way D1 or KV do.
Running models on Cloudflare’s infrastructure is a separate product, Workers AI. You can put AI Gateway in front of Workers AI, OpenAI, Anthropic, Google, and other providers, and it manages the traffic while the provider runs the model.
Why put a gateway in the middle?
When you’re experimenting locally, calling a model directly is fine. You can read the response in your terminal and retry it by hand.
Once your app is in production, things get messier. A user emails you about a request that failed yesterday, a provider slows to a crawl, or a bug sends the same expensive prompt hundreds of times in a loop.
AI Gateway gives you one place to see what happened and put guardrails around those calls.
Logs and analytics
The gateway can log the provider, model, status, duration, token usage, and cost for every request.
That lets you answer practical questions quickly:
- Which model is failing?
- How long are requests taking?
- How many tokens are we spending?
- Did a request reach the provider at all?
Logs pay off even more when your app talks to multiple providers, because you don’t have to stitch together a different logging setup for each one.
Caching
AI Gateway can cache a response and serve it again when the exact same request shows up.
That works well for prompts whose answers are safe to share, like classifying the same piece of public text.
Be careful with anything personalized, though. Never let two users share a cached response that includes private or user-specific data.
Rate limiting and spend control
Model calls cost money, and a public endpoint can rack up a bill fast if someone abuses it or a client gets stuck in a retry loop.
The gateway can throttle requests before they reach the provider, enforce spend limits, and route traffic based on metadata.
I still put limits in my application code for individual users and features, since the gateway doesn’t know who’s logged into my app on its own.
Retries and fallbacks
Providers throw errors even when your code is fine.
AI Gateway can retry a failed call or send it to another model, which helps when availability matters more than sticking to one exact model.
Keep in mind that a fallback model can behave differently even when the HTTP request succeeds, so test the output of every model in your route.
The ways to call AI Gateway
There are three main ways to call AI Gateway.
From a Cloudflare Worker
Inside a Worker, the shortest path is the AI binding.
You call env.AI.run() and pass a gateway ID in the options. Because Cloudflare authenticates the binding inside your account, you don’t need to attach a gateway token to the request.
We’ll use this path in the example below.
Through the unified REST API
The AI Gateway REST API gives you one Cloudflare endpoint for both Workers AI and third-party models.
It supports several request formats, including OpenAI-compatible chat completions. For third-party models, you prefix the model name with the provider:
openai/gpt-4.1
anthropic/claude-sonnet-4.5
google/gemini-3-flash
Cloudflare handles authentication and unified billing here, so you send a Cloudflare API token instead of a provider key.
If you’re integrating from outside Cloudflare Workers, start with this option.
Through a provider-native endpoint
Provider-native endpoints preserve the original provider’s API shape.
With OpenAI, for instance, you swap this base URL:
https://api.openai.com/v1
for this one:
https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/openai
This is handy when you already have provider-specific code or want to bring your own provider key. I’ll cover its authentication headers later.
Create an AI Gateway
Let’s set up a gateway for our example.
Open the Cloudflare dashboard, pick your account, and follow these steps:
- Go to AI → AI Gateway
- Click Create Gateway
- Name it
tutorial-gateway - Leave logging enabled
- Create the gateway
That gateway ID becomes part of your app’s config. Create separate gateways for development and production if you want their logs and limits kept apart.
Cloudflare can also auto-create a gateway called default on your first authenticated request, though I prefer naming it explicitly so it’s easy to spot in code and in the dashboard.
Build a small gateway example
Now we’ll route a Workers AI request through tutorial-gateway.
You’ll need a Cloudflare Worker project. If you haven’t built one yet, start with my Cloudflare Workers tutorial.
We’ll run the Worker with Wrangler. These commands use Wrangler 4, and npx wrangler runs the copy installed in your project. If your local copy is older, upgrade it with npm install -D wrangler@4.
First, add the AI binding to wrangler.jsonc:
{
"ai": {
"binding": "AI"
}
}
That exposes the binding on env.AI.
If you’re using TypeScript, regenerate the binding types after editing wrangler.jsonc:
npx wrangler types
Now replace your Worker code with this:
export default {
async fetch(request, env) {
const result = await env.AI.run(
'@cf/meta/llama-3.2-3b-instruct',
{
messages: [
{
role: 'user',
content: 'Explain what an API is in one short sentence',
},
],
max_tokens: 80,
},
{
gateway: {
id: 'tutorial-gateway',
metadata: {
feature: 'api-explanation',
},
},
},
)
return Response.json({
answer: result.response,
logId: env.AI.aiGatewayLogId,
})
},
}
Here env.AI.run() takes three arguments: the model name, the model input (one user message with a cap on the response length), and the gateway options. Passing tutorial-gateway routes the call through the gateway we created, and the small piece of metadata makes the request easier to find later. The logId in the response points straight to the matching gateway log.
Run the Worker
Start the local dev server:
npx wrangler dev
Wrangler prints a local URL, usually http://localhost:8787.
Open it in your browser or hit it with curl:
curl http://localhost:8787
You’ll get a response shaped like this:
{
"answer": "An API is a defined way for software programs to communicate with each other.",
"logId": "01K..."
}
The text will vary since the model generates it on the fly. Even though the Worker runs through the local dev server, model inference happens on Cloudflare and counts toward your Workers AI usage.
Inspect the request
Go back to AI → AI Gateway → tutorial-gateway in the Cloudflare dashboard.
Open the logs and find the ID your Worker returned. You’ll see the model, duration, status, token counts, and the feature metadata you attached.
Your Worker made a normal model call, and you now have a record of it outside the app itself. Send a few more requests and you’ll see a separate log entry for each one.
Add caching to one request
You can also control gateway options on individual requests.
For example, we can cache the previous response for five minutes:
gateway: {
id: 'tutorial-gateway',
cacheTtl: 300,
metadata: {
feature: 'api-explanation',
},
}
Now repeated identical requests can come back straight from the gateway cache instead of running the model again.
You can also bypass the cache for a single request:
gateway: {
id: 'tutorial-gateway',
skipCache: true,
}
My advice is to leave caching off at first, and turn it on only after you know which outputs are safe to reuse.
Calling a third-party model from the binding
The same AI binding can also call third-party models through Unified Billing.
Switch the model name to the provider/model format:
const result = await env.AI.run(
'openai/gpt-4.1-mini',
{
messages: [
{ role: 'user', content: 'Write a two-line poem about Rome' },
],
},
{
gateway: {
id: 'tutorial-gateway',
},
},
)
Cloudflare supplies the provider credentials and deducts the cost from your AI Gateway credits.
The binding doesn’t support bringing your own provider key for third-party models. If you need BYOK, use a provider-native endpoint instead.
Understanding the two authentication headers
Provider-native endpoints have two separate authentication layers.
When you call OpenAI through an authenticated gateway using your own OpenAI key, you send two headers:
Authorization: Bearer <OPENAI_API_KEY>for OpenAIcf-aig-authorization: Bearer <CF_AIG_TOKEN>for AI Gateway
Here’s how both headers look in a request:
const response = await fetch(
'https://gateway.ai.cloudflare.com/v1/ACCOUNT_ID/GATEWAY_ID/openai/chat/completions',
{
method: 'POST',
headers: {
Authorization: `Bearer ${env.OPENAI_API_KEY}`,
'cf-aig-authorization': `Bearer ${env.CF_AIG_TOKEN}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: 'gpt-4o-mini',
messages: [
{ role: 'user', content: 'Explain DNS in one sentence' },
],
}),
},
)
Store both values as Worker secrets instead of putting them in wrangler.jsonc or source code:
npx wrangler secret put OPENAI_API_KEY
npx wrangler secret put CF_AIG_TOKEN
If you leave out cf-aig-authorization, the authenticated gateway rejects the request before it ever reaches OpenAI.
The unified REST API works differently: it takes a Cloudflare token in the standard Authorization header, and Cloudflare handles provider billing for you.
Caching is not always correct
Caching a weather answer for a few minutes makes sense. Caching a private support conversation under a shared key is a serious bug.
Before you turn caching on, run through these questions:
- Does the answer depend on a specific user or organization?
- Does the prompt include private data?
- Does the answer change with time?
- Do temperature or other model options vary between calls?
- Would returning an old answer cause a problem?
If any of those make you hesitate, skip the cache.
Streaming responses are another catch. Gateway caching doesn’t apply to streaming responses, because the output is already being sent while the model generates it.
Rate limits need application context
A gateway-wide limit can shield a provider from a sudden traffic spike, but it doesn’t know that one specific user has already used up their daily allowance. Your app still needs an identity layer and its own per-user rules.
I usually combine three layers:
- application limits for each user or feature
- a gateway limit for the entire service
- a spend limit as the final boundary
Logging and private data
Gateway logs are useful because they can capture prompts and responses, which also means they can end up holding private user data.
Decide what you’re allowed to record before sending production traffic through the gateway. AI Gateway lets you disable logging for individual requests, apply data-loss prevention rules, or run with zero data retention.
Don’t record prompts just because a dashboard makes it one click away. Store only what you need to run and debug the app.
How I use AI Gateway
I use AI Gateway in production when my LLM calls need a visible trail.
I keep all model calls behind a small adapter, so the rest of the codebase doesn’t know or care whether a request goes straight to a provider or through a gateway.
Here’s the pattern I stick to:
feature code -> model adapter -> AI Gateway -> provider
The adapter handles the URL, headers, request shape, and error handling, while AI Gateway takes care of cross-provider controls and logs. That also keeps local experiments painless, since I can tweak the adapter config without touching every route that calls an AI model.
I explain that separation in more detail in my LLM adapter pattern tutorial.
When to use AI Gateway
AI Gateway makes sense when:
- real people are using your AI feature
- you want one place to check cost, latency, and failures
- several apps or providers need the same controls
- caching can save you from repeated model calls
- you need retries, fallbacks, limits, or routing
Skip it for a throwaway script or an early local experiment. Calling the provider directly has fewer moving parts.
Once a model call is part of a real product, that extra layer pays for itself. Having every request logged and controllable in one place saves a lot of guesswork when something fails.
If you’re on Vercel instead, check out the Vercel AI Gateway tutorial.
Want me to talk about your product? You can sponsor this site.
Related posts about cloudflare: