No Cap on LLM API Spend: How an Open AI Endpoint Becomes a Five-Figure Bill
Every call to an LLM costs money, and the caller decides how many calls happen and how long each one is. An AI endpoint with no login, no per-user limit and no cap on input or output size is an open tab at your expense. Set five limits before launch: authentication, a per-user rate limit, a daily quota, a token cap on each request, and a hard budget at the provider.
On this page
With most endpoints, abuse costs you some CPU. With an LLM endpoint it costs you dollars per request, and the request size is under the attacker's control. People actively look for such endpoints, because free access to a good model has resale value.
How the bill happens
- An open route.
/api/chatworks without a session because the landing page has a demo widget. A script calls it in a loop. - A key in the browser. The provider key is in the JavaScript bundle, so nobody needs your endpoint at all. See secret keys in the frontend.
- No size limits. The endpoint forwards whatever it receives. Someone sends 100,000 tokens of input and asks for the maximum output, repeatedly.
- A loop. An agent retries a failing tool call forever, or two automations trigger each other. No attacker required.
- A stolen key. In the Railway incident of October 2026, press coverage of the company's report put fraudulent AI usage on keys taken from customer environments at about $740,000. The victims' own code was fine.
Limit 1: require a session
const session = await auth();
if (!session) return Response.json({ error: 'Unauthorized' }, { status: 401 });
If you need a public demo, give it a separate, much stricter path: a small model, a short output cap, a limit per IP address, and a CAPTCHA or similar check when traffic looks automated.
Limit 2: rate limit per user
Per user ID for logged-in users, per IP for anonymous ones. With Upstash Redis it is a few lines:
import { Ratelimit } from '@upstash/ratelimit';
import { Redis } from '@upstash/redis';
const perMinute = new Ratelimit({
redis: Redis.fromEnv(),
limiter: Ratelimit.slidingWindow(10, '1 m'),
});
const { success } = await perMinute.limit(`chat:${session.user.id}`);
if (!success) {
return Response.json({ error: 'Too many requests' }, { status: 429 });
}
An in-memory counter does not work on serverless platforms, where each instance has its own memory. Use a shared store.
Limit 3: a daily or monthly quota
Rate limits stop bursts. A patient script at nine requests a minute still makes about 13,000 calls a day. Track usage per user and stop at a number tied to their plan:
const used = await db.usage.aggregate({
_sum: { totalTokens: true },
where: { userId: session.user.id, createdAt: { gte: startOfDay() } },
});
if ((used._sum.totalTokens ?? 0) > plan.dailyTokenLimit) {
return Response.json({ error: 'Daily limit reached' }, { status: 429 });
}
After each call, store the token counts the provider returns. You get the quota, per-customer cost data for pricing decisions, and something to look at when the bill surprises you.
Limit 4: cap every request
const { message } = Body.parse(await req.json()); // z.string().max(4000)
const result = await client.messages.create({
model: 'claude-haiku-4-5',
max_tokens: 800, // output cap
messages: [...history.slice(-10), { role: 'user', content: message }],
});
Four things are capped here: the length of the user's message, the output, the amount of history sent along, and the model. Never let the client choose the model name or max_tokens. If the request body contains model: "..." and your code passes it through, users will pick the most expensive one.
For agents with tools, also cap steps per run and set a timeout. A loop with a limit of 10 steps is a bug you find in the logs. Without one, you find it on the invoice.
Limit 5: a hard budget at the provider
Everything above lives in your code, and code has bugs. The last limit lives outside it.
- Set a monthly budget and usage alerts in the provider's console. Know whether the limit is a hard stop or only an email. Prefer the hard stop.
- Use prepaid credits without auto-reload while you are small. The worst case is then the balance.
- One key per environment and per app, each with its own limit. A leaked preview key should not be able to spend the production budget.
- Alert on rate of spend as well as the total: a threshold per day, sent to a channel someone reads.
Test it before someone else does
# 1. Without a session: expect 401
curl -s -o /dev/null -w "%{http_code}\n" -X POST https://yourapp.com/api/chat \
-H 'Content-Type: application/json' -d '{"message":"hi"}'
# 2. Thirty quick requests with a session: expect 429 after the first ten
for i in $(seq 1 30); do
curl -s -o /dev/null -w "%{http_code} " -X POST https://yourapp.com/api/chat \
-H "Cookie: $SESSION" -H 'Content-Type: application/json' -d '{"message":"hi"}'
done
# 3. Oversized input: expect 400
python3 -c "import json; print(json.dumps({'message': 'a' * 200000}))" | \
curl -s -o /dev/null -w "\n%{http_code}\n" -X POST https://yourapp.com/api/chat \
-H "Cookie: $SESSION" -H 'Content-Type: application/json' -d @-
Then check the extra fields: send "model" and "max_tokens" in the body and confirm they are ignored.
If the bill already arrived
Revoke the key first. Then look at usage by key and by hour to find where it came from, close that path, and contact the provider's support with the timeline. Some providers will reduce charges for clear abuse. None of them promise to.
Rate limits are check 10 in our security checklist for vibe-coded apps. If you are building an AI feature and want cost controls, usage tracking and abuse protection built in from the first version, that is part of our AI development work.
