How to rate limit AI API route calls and stop bill spikes
Rate limit AI API route code before you ship it, or a stranger can loop it with curl and spend your credits. A login screen in the UI doesn't protect the route behind it. Here is how to test your own route, then add a login check, a rate limit, token caps and spend limits, in that order.
QUICK CHECKLIST
- Call your AI route signed out with curl
- Return 401 when there is no valid user
- Add a per-user and per-IP rate limit
- Cap input size and output tokens
- Fix the model name on the server
- Set a spend limit at the AI provider
Why a public AI route is a cost trap
A server route that calls OpenAI, Anthropic or Gemini is a public URL. Your login screen lives in the browser UI. The route itself answers any HTTP request that reaches it, from a browser, from curl or from a script. If the handler never checks who is calling, you have an unauthenticated AI endpoint.
Your key is safe from view because it only lives on the server. It isn't safe from use. Anyone who finds the route URL, for example in the network tab or your JavaScript bundle, can call it, and your key pays. Two things go wrong. Someone loops the route and you get an OpenAI bill spike. Or someone uses your route as a free proxy for their own prompts, with your model and your credits.
OWASP lists this as LLM10:2025 Unbounded Consumption: users can run inference with no limits, which drains your budget or knocks the service over. On a small app nobody watches, that can go on for days.
Test your own route with a curl loop
Only test your own app, and keep it small. Every request that succeeds is a real, billed call, so send a short message.
# 20 signed-out requests, print only the status codes
for i in $(seq 1 20); do
curl -s -o /dev/null -w "%{http_code}\n" \
-X POST https://your-app.example/api/chat \
-H "Content-Type: application/json" \
-d '{"message":"say hi"}'
doneRead the result:
200every time means anyone can use your key.401means the login check works.200a few times, then429, means a rate limit works.
Then probe the inputs: a very long message, an extra "model" field, a "system" field. If the route passes these on to the provider, the caller controls your spend and your prompt.
Test every route that calls a paid API, including server actions and Supabase edge functions. One open route is enough.
Layer 1: require a signed-in user
Check the user on the server, inside the handler, before you touch the AI provider. Return 401 if there is none. With Supabase, use getUser(), which asks Supabase Auth to validate the session. getSession() only reads the cookie. See getSession vs getUser.
// app/api/chat/route.ts
import { createClient } from "@/lib/supabase/server"; // your server client helper
export async function POST(req: Request) {
const supabase = await createClient();
const { data: { user }, error } = await supabase.auth.getUser();
if (error || !user) {
return Response.json({ error: "Sign in required" }, { status: 401 });
}
// rate limit, input checks and the AI call go below
}With another auth library, use its server-side check in the same place. Clerk, for example, has auth(), and you return 401 if userId is empty. See Clerk and NextAuth mistakes.
Don't rely on middleware alone. A matcher gap can leave the route open, as in Next.js middleware auth bypass. In a Supabase edge function, the default JWT check doesn't prove a user is signed in (the legacy public anon key passes it), so call getUser() inside the function as well.
Layer 2: rate limit per user and per IP
A login check stops strangers but not a signed-up user with a script. Sign-up is free, so add a rate limit. On serverless hosts, a counter in memory resets whenever a new instance starts, so use a shared store. Upstash Ratelimit works with Redis over HTTP and fits Next.js route handlers.
Install @upstash/ratelimit and @upstash/redis, and put UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN in your server env vars.
import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";
const ratelimit = new Ratelimit({
redis: Redis.fromEnv(),
limiter: Ratelimit.slidingWindow(10, "1 m"),
prefix: "ai",
});
// inside POST, after the 401 check
const { success } = await ratelimit.limit(user.id);
if (!success) {
return Response.json({ error: "Too many requests" }, { status: 429 });
}The numbers are examples. Pick them from what a real user does in a minute. You can add a second limiter keyed by IP, but only trust x-forwarded-for if your host sets it, since a client can fake it.
For Express, mount express-rate-limit on the AI route with a windowMs and a limit. Set trust proxy behind a proxy, and use a shared store if you run more than one instance.
A request limit counts calls, not cost. The next layer caps what one call can cost.
Layer 3: cap input, output and daily use
Set a max_tokens limit on every call, and limit what goes in. The option has different names:
- Anthropic Messages API:
max_tokens, and it is required. - OpenAI Chat Completions:
max_completion_tokens. OpenAI's reference marks the oldermax_tokensas deprecated, and it doesn't work with reasoning models. - OpenAI Responses API:
max_output_tokens. - Vercel AI SDK v5:
maxOutputTokens. - Gemini:
maxOutputTokensingenerationConfig.
Output caps don't limit input, and input tokens are billed too. Reject long messages before you call the provider. Never take the model name from the request body. Fix it on the server.
const MODEL = "gpt-4o-mini"; // example. Set on the server, never from req
const MAX_INPUT_CHARS = 4000;
const body = await req.json();
const message = typeof body.message === "string" ? body.message : "";
if (!message || message.length > MAX_INPUT_CHARS) {
return Response.json({ error: "Invalid message" }, { status: 400 });
}
const completion = await openai.chat.completions.create({
model: MODEL,
max_completion_tokens: 500,
messages: [
{ role: "system", content: SYSTEM_PROMPT }, // defined on the server
{ role: "user", content: message },
],
});If the browser sends chat history, cap its length and drop any system role. Validate the body with Zod.
Finally, add a daily quota that survives restarts. A table works, and only your server should touch it:
create table public.ai_usage ( user_id uuid not null references auth.users (id) on delete cascade, day date not null default current_date, requests int not null default 0, tokens bigint not null default 0, primary key (user_id, day) ); alter table public.ai_usage enable row level security; -- no policies: browsers can't read or write it
Before the call, count the request in one atomic step: insert into ai_usage (user_id, requests) values ($1, 1) on conflict (user_id, day) do update set requests = ai_usage.requests + 1 returning requests. Refuse with 429 if the returned number is over your limit. A separate read and then write lets parallel requests slip past. After the call, add the usage token numbers the provider returns. Run it from server code with the service role key, or wrap it in a database function your route calls. The service role key must never reach the browser.
Layer 4: edge rules and provider spend limits
Rules at your host or CDN stop traffic before it reaches your function. Vercel Firewall rate limiting and Cloudflare rate limiting rules both let you set a request count and time window for a path such as /api/chat. Limits differ by plan.
These are an extra layer, not a replacement. On most plans an edge rule counts by IP and path. Even where it can key on a header or token, it doesn't know how many tokens a user used, and it is easy to forget when you move hosts.
The last line is the spend limit at the provider. If every other layer fails, a hard limit caps the damage. Not every provider has one: some budgets only send alerts (Google Cloud budgets, for example), and prepaid credits with auto-recharge off may be your only real cap. Set it up with API key spending caps.
| Layer | What it stops | What it misses |
|---|---|---|
| Login check (401) | Strangers and bots with no account | Signed-up users who script the route |
| Rate limit per user and IP | Fast loops from one user or one address | Slow abuse, and costly single calls |
| Input and token caps | Huge prompts, long outputs, caller-chosen models | Many cheap calls |
| Edge rule (Vercel, Cloudflare) | Floods before they reach your function | Which user is calling, and token use |
| Provider spend limit | Runaway bills when the other layers fail | Abuse below the limit, and the service stopping when it is hit |
No single layer is enough. The spend limit is the last line.
Rate limit AI API route calls, step by step
Do these in order.
Find every route that calls a paid AI API
Search the repo for
openai,anthropic,@google/genai,generative-ai,@ai-sdkand the API hosts, then run the signed-out curl loop on each route.Add the login check
Check the user on the server and return 401 when there is none. Put it at the top of the handler.
Add the rate limit
Add Upstash Ratelimit, or
express-rate-limiton Express, keyed by user ID. Return 429 when over.Cap input, output and model
Reject long messages, set the token cap for your provider's API, and hard-code the model name on the server.
Set provider spend limits and read past usage
Set a monthly limit at the provider, then check its usage page for spikes you don't recognize. If you find any, follow the spending caps guide and rotate the key.
Add an edge rule and test again
Add a Vercel or Cloudflare rule for the path and run the loop again. Signed out you should get 401. For the signed-in run, add your session cookie or bearer token with
-H, and fast requests should get 429. A low edge threshold can answer 429 before your 401 check runs.
Repeat the test after any change to the route. A refactor that moves the handler can drop the checks without anyone noticing.
Fix prompt you can paste
Paste this into Cursor, Claude Code or your Lovable chat. It asks for a report first, so nothing changes until you approve.
Find every route in this repo that calls a paid AI API (OpenAI, Anthropic, Gemini, or the Vercel AI SDK). Include route handlers, Express routes, server actions and edge functions. Do not change any code yet. Only report. For each route, list file and line, and answer: 1. Does it check the signed-in user on the server and return 401 if there is none? 2. Is there a rate limit per user and per IP? What are the numbers? 3. Is there a maximum on input length, and on output tokens (max_tokens, max_completion_tokens, max_output_tokens or maxOutputTokens)? 4. Does the model name or the system prompt come from the request body? 5. Is there a daily per-user quota stored in the database? Then propose, without applying, the smallest change per route: a 401 check, an Upstash Ratelimit (or express-rate-limit) returning 429, an input length check, a fixed model name, and an output token cap. Wait for my approval before editing anything.
If the agent says a route is limited, confirm it with the curl loop.
What Leakcade checks
Leakcade's paid scan reads a public GitHub repo. It flags routes that call a paid AI API with no rate limiter visible in the same file, in middleware or in a global app.use, and custom login, signup, password reset and OTP routes without limits. A limiter wrapped in a helper imported from another file may not be recognized, so check each finding against your code. Each finding comes with a fix prompt.
A limit set at the CDN or WAF, such as a Vercel Firewall or Cloudflare rule, doesn't show in the repo. So "no sign found" is not proof that a route is unprotected, and a clean result is not proof that it is safe. Leakcade doesn't call your live app, so the curl loop above and your provider's usage page still matter. For the login side, see login rate limiting.
Further reading
- Upstash docs: Ratelimit for TypeScript
- Vercel docs: WAF rate limiting
- Cloudflare docs: Rate limiting rules
- OWASP GenAI: LLM10:2025 Unbounded Consumption
- OpenAI API reference: Chat Completions
- OpenAI API reference: Responses
- Anthropic API reference: Messages
- express-rate-limit on npm
FAQ
Does a login screen protect my AI route?
No. The route answers any HTTP request, not just your UI. Check the user on the server inside the handler and return 401 when there is none.
Is a rate limit enough to stop a bill spike?
No. It counts calls, not cost. Add input limits, an output token cap, a fixed model name and a spend limit at the provider.
Can Leakcade tell me if my AI route is safe?
Not fully. The paid scan reads your public GitHub repo and flags AI routes with no visible rate limit. It can't see CDN or WAF rules and doesn't call your live app, so still run the curl loop.
Want a second pair of eyes?
We review your whole repo and write a fix prompt for every finding. $19, report within an hour.
Check my repoLeakcade is an automated check. It can miss vulnerabilities and is not a substitute for a professional security audit or pentest. Provided as is. You stay responsible for your code. Where the law allows, our liability is limited to what you paid ($19). Terms