I put a standard 20-requests-per-minute IP rate limiter in front of a prototype /api/summarize route and assumed my API credits were safe. To verify it, I ran a 30-second local test sending just 10 requests from one IP. Every single request returned 200 OK, never tripped the limiter, and still burned through 160,000 tokens.
If a single broken client loop or scraper repeats that pattern at the allowed 20 RPM for one hour, that is 1,200 requests and roughly 19.2 million tokens before you even open your laptop the next morning.
The Illusion of Request-Based Rate Limiting
When building an MVP or micro-SaaS, shipping fast is the priority. The default playbook is straightforward: wrap an LLM provider call behind a backend route, slap an IP-based rate limiter on it (say, 20 requests per minute), and launch.
That pattern works for traditional CRUD endpoints because one GET /api/projects call costs roughly the same compute as the next. With generative AI endpoints, request count has almost no correlation with cost.
A normal user sends a 50-word prompt and receives a 150-word reply. A malicious userβor a buggy frontend retrying on timeoutβcan pack 12,000 input tokens into the exact same endpoint and instruct the model to write an exhaustive response. Because output tokens typically cost several times more than input tokens, one unconstrained call can cost as much as hundreds of legitimate ones.
In the OWASP Top 10 for LLM Applications (LLM10: Unbounded Consumption), this exact failure modeβoften called Denial of Wallet (DoW)βis highlighted as a primary financial and availability risk for AI-backed apps.
Why Your Backend Keeps Paying After the User Leaves
Payload size is only half the leak. The second cost multiplier happens when clients disconnect mid-request.
In a typical streaming or long-running AI route:
- A user submits a prompt, gets impatient after 3 seconds, and refreshes the pageβor a bot closes the connection early.
- Your server handler ignores the aborted client socket.
- The upstream fetch to the LLM provider continues generating tokens until completion, and your account is billed for every token nobody ever read.
Combine unbounded input length, missing output caps, and orphaned upstream requests, and a free-tier demo page becomes an open wallet.
Capping Tokens and Canceling Orphaned Requests
Fixing this does not require an enterprise API gateway. Before the request ever touches an LLM provider, I enforce three hard boundaries directly in the route handler: a strict input size limit, an explicit output token cap, and cancellation forwarding via the Web AbortSignal API.
const MAX_INPUT_CHARS = 8_000; // ~2,000 tokens
const MAX_OUTPUT_TOKENS = 500;
export async function POST(req: Request) {
const { prompt } = await req.json();
if (typeof prompt !== "string" || prompt.length > MAX_INPUT_CHARS) {
return Response.json({ error: "Input exceeds limit" }, { status: 413 });
}
const controller = new AbortController();
req.signal.addEventListener("abort", () => controller.abort());
const upstream = await fetch(process.env.LLM_API_URL!, {
method: "POST",
signal: controller.signal,
headers: { Authorization: `Bearer ${process.env.LLM_API_KEY}`, "Content-Type": "application/json" },
body: JSON.stringify({ model: "your-model-id", input: prompt, max_output_tokens: MAX_OUTPUT_TOKENS }),
});
return new Response(upstream.body, { status: upstream.status });
}
Rejecting oversized strings before tokenization avoids burning CPU on giant payloads, while setting max_output_tokens (or max_tokens, depending on your provider's SDK) puts a hard ceiling on the most expensive part of the call. Forwarding req.signal ensures that when a user closes the tab, the upstream generation stops immediately.
Pre-Launch AI Cost-Control Checklist
Before exposing any AI-powered endpoint to the public, I run through these four checks:
- [ ] Enforce token budgets, not just RPM: Track per-user or per-session token usage alongside request counts, and cap both input length and maximum output tokens in the backendβnever trust client-sent parameters.
- [ ] Propagate abort signals: Wire
req.signalinto your upstreamfetchor provider SDK call so disconnected clients stop token generation immediately. - [ ] Understand provider limits and set spend caps: Remember that provider limits (as outlined in the OpenAI API Rate Limits Guide) are enforced at the organization or project level, not per end userβso configure hard monthly spending caps and email alerts in your billing dashboard.
- [ ] Gate expensive models behind auth: Never expose flagship reasoning models on unauthenticated landing-page demos; use smaller, cheaper models for public try-it-now widgets and require verified accounts for full access.
The Takeaway
Request-count rate limits protect your server's CPU, not your API wallet. Treating every AI endpoint as a metered financial transactionβwith strict input caps, output ceilings, abort propagation, and hard provider spend limitsβtakes less than 30 minutes to wire up and prevents the kind of overnight bill that kills an early-stage project.
What was the most unexpected API bill or abuse pattern you caught in your own project?
Connect with Me
If you found this article helpful, let's connect!
- π» GitHub: johnnylemonny

Top comments (40)
Great article, John! πΈπ
Your article got me thinking about how we could manage token budgets across concurrent requests. Reserving an estimated budget before each LLM call and adjusting it based on actual usage afterward might be another interesting approach!
Thanks for sharing such a practical topic! π
Reserving an estimated token slice upfront and reconciling the delta once the response finishes is a smart way to keep concurrent calls from blowing past a shared budget. Glad the post resonated with you.
160,000 tokens from 10 requests that never tripped the limiter is the number that should kill request-count rate limiting for LLM routes. The orphaned-request leak is the one I'd add to the checklist first β a user closing a tab shouldn't keep billing you for tokens nobody read. Do you also cap per-session token budgets server-side, or is the per-request cap enough in practice?
Aborting orphaned upstream work when a tab closes saves real money right away because nobody is waiting on that output anymore. Per-request caps handle single spikes, while per-session token budgets are what keep one persistent user from steadily draining credits across a long visit.
Exactly β the per-request cap stops the spike, but the per-session budget is what stops the slow bleed from one persistent user. That distinction is the part most checklists miss. Do you enforce the session budget as a hard cutoff mid-session, or a throttle that degrades gracefully?
One important detail: the input validation happens after
req.json()has already consumed and parsed the request body. Unless the hosting layer enforces a payload limit, a massive JSON request can still consume significant server memory before reaching the validation logic. I'd enforce a strict body-size limit at the gateway or framework level, rather than relying solely on prompt-length validation. Are you handling this at the infrastructure level or directly inside the application?Parsing a huge JSON payload before checking its size is a sneaky way to burn memory before the handler even starts. Putting a hard body-size cap right at the reverse proxy, gateway, or framework layer keeps oversized requests from reaching application memory in the first place.
You are right.
Thanks.
Please teach me a lot in the future.
The 10 requests β 160k tokens test is the number that should scare people, because 20 RPM sounds perfectly safe until you do that multiplication. The abort-propagation half is the one I'd bet most people skip β in our own browser-agent runs I watched a single long-page read cost 25,958 tokens one run and 37,848 the next on the same unchanged page, just because the page was still settling. Nothing in a request-count limiter would have caught any of that. Do you cap per-session token totals too, or is the output cap doing all the work?
Jumping from 25,958 to 37,848 tokens on an unchanged page while it finishes settling shows how quickly dynamic context can blow up a run. Output caps help bound a single reply, while per-session token totals keep repeated reads or long browsing sessions from quietly compounding.
yeah the per-session total is the one I'd actually trust β an output cap bounds one reply but a long session just keeps compounding quietly underneath it. the scary part is nothing in the run flags it, the total just creeps up while every single reply looks fine. have you ever had a session total actually trip in practice, or is it mostly a guard you set and never hit?
Really important topic! One thing worth emphasizing is that protecting an AI endpoint requires more than just rate limiting. Per-user token budgets, output limits, and proper cancellation of upstream requests should all work together.
I especially like the point about orphaned requests. A user disconnecting doesn't necessarily mean the model stops generating or billing. This is an easy detail to overlook when building AI-powered features.
How do you think startups should balance strict usage limits with keeping the user experience smooth?
Keeping the UX smooth comes down to setting sensible defaults that fit normal tasks while showing clear feedback when someone hits a cap or needs a higher allowance. Layering token limits, output caps, and cancellation together gives you predictable costs without getting in the way of genuine users.
The orphaned generation bit is the one that got me β the user closes the tab and the server just keeps minting tokens nobody reads. I've wired AbortSignal through before and the annoying part was the SDK swallowing it halfway. Does yours actually propagate the abort, or did you have to drop down to raw fetch to make it stick?
Dropping straight down to raw
fetchwith anAbortControllersignal is the cleanest way to avoid SDK wrappers eating or delaying cancellation mid-stream. Keeping that signal wired all the way to the underlying request makes sure an abandoned tab actually cuts the work short instead of lingering on the server.Every counter in that defense comes from your own logs, and the aborted streams are exactly where your logs stop telling the truth: with stream_options: {"include_usage": true} the usage chunk only lands at the end of the stream, so cancelling one books 0 tokens in your ledger while the provider bills every token generated up to the socket dying. Same on Anthropic, output_tokens only appears in the final message_delta. Do you reconcile the ledger against the provider usage endpoint, or does the spend cap only get checked against the invoice?
That is a great catch. When a stream is cut short before the final usage or delta chunk arrives, local counters miss tokens the provider still charges for. Reconciling against provider usage data and billing caps is the right way to close that blind spot.
Great that you tested it instead of trusting it. The 20 per minute IP limit looking fine until all 10 requests came back 200 is exactly the kind of thing people only find on the invoice. Per user or per key limits plus a hard daily spend cap feel like the real floor here.
Spot on. Seeing those 200s stack up locally saved me from a painful surprise later. Per-key or per-user tracking paired with a hard spend cap really is the baseline before anything goes public.
The one that gets people with agents is the retry loop. A tool errors, the model tries again, and every retry resends the whole context, so the bill grows fast. Cap steps per task and total tokens per run, not just requests per minute.
Agent retry loops are brutal because every attempt replays growing history on top of an already expensive step. Putting a hard ceiling on steps and total run tokens stops an agent from quietly burning through a task budget in circles.
Your 10-requests, 160,000-token test is the part that stuck with me, because it shows exactly why counting requests is the wrong unit. I audit my own AI spending the same way, in small fixed amounts β Claude Pro and ChatGPT Plus at $20 each, $40 a month total β and the habit that saves me is checking what actually got used, not what the limit allowed. The orphaned-generation point hit home too: in my small family project, a verifier re-solves every answer from scratch, so nothing is accepted just because it finished. In your own logs, what do you watch first β the biggest single request, or the session that quietly adds up?
Checking actual usage against fixed caps is such a grounded habit, especially when a verifier re-checks work from scratch and multiplies token costs. Looking at the largest single request first catches runaway prompts immediately, while session totals catch the slow creep that sneaks past per-call limits.