DEV Community

Cover image for One Unprotected AI Endpoint Can Drain Your Startup's API Budget Overnight

One Unprotected AI Endpoint Can Drain Your Startup's API Budget Overnight

๐—๐—ผ๐—ต๐—ป on December 01, 2026

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 verif...
Collapse
 
nyaomaru profile image
nyaomaru The Startup Cafรฉ •

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! ๐Ÿˆ

Collapse
 
johnnylemonny profile image
๐—๐—ผ๐—ต๐—ป The Startup Cafรฉ •

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.

Collapse
 
kami_butt_69b922ade8de012 profile image
Agentic Affairs •

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?

Collapse
 
johnnylemonny profile image
๐—๐—ผ๐—ต๐—ป The Startup Cafรฉ •

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.

Collapse
 
kami_butt_69b922ade8de012 profile image
Agentic Affairs •

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?

Collapse
 
andrii_0308f2a18c503d78ec profile image
Andrii •

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?

Collapse
 
johnnylemonny profile image
๐—๐—ผ๐—ต๐—ป The Startup Cafรฉ •

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.

Collapse
 
andrii_0308f2a18c503d78ec profile image
Andrii •

You are right.
Thanks.
Please teach me a lot in the future.

Collapse
 
aheadkit profile image
AheadKit •

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?

Collapse
 
johnnylemonny profile image
๐—๐—ผ๐—ต๐—ป The Startup Cafรฉ •

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.

Collapse
 
aheadkit profile image
AheadKit •

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?

Collapse
 
hasnan_khan_dev_0 profile image
Hasnan Khan •

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?

Collapse
 
johnnylemonny profile image
๐—๐—ผ๐—ต๐—ป The Startup Cafรฉ •

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.

Collapse
 
paullovelace profile image
Paul Lovelace •

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?

Collapse
 
johnnylemonny profile image
๐—๐—ผ๐—ต๐—ป The Startup Cafรฉ •

Dropping straight down to raw fetch with an AbortController signal 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.

Collapse
 
dafili profile image
Renhua Wei •

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?

Collapse
 
johnnylemonny profile image
๐—๐—ผ๐—ต๐—ป The Startup Cafรฉ •

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.

Collapse
 
gautamtalksdev profile image
Gautam K •

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.

Collapse
 
johnnylemonny profile image
๐—๐—ผ๐—ต๐—ป The Startup Cafรฉ •

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.

Collapse
 
murali_gour_13cd7a6a6db2c profile image
Murali Gour •

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.

Collapse
 
johnnylemonny profile image
๐—๐—ผ๐—ต๐—ป The Startup Cafรฉ •

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.

Collapse
 
_komachi-jp profile image
Komachi | AI on a Budget •

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?

Collapse
 
johnnylemonny profile image
๐—๐—ผ๐—ต๐—ป The Startup Cafรฉ •

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.

Collapse
 
sergeevdms profile image
Dmitry Sergeev •

The body sends no stream flag, so this is a non-streamed call, and aborting a non-streamed request is not guaranteed to stop generation on the provider side, the tokens can still be produced and billed. And on a public demo with no login a per-user or per-session budget is keyed on whatever the caller sends, so clearing cookies or rotating IPs resets it. For anonymous routes the cap that holds is a global one on the route itself, sized to what you are willing to lose in one night.

Collapse
 
johnnylemonny profile image
๐—๐—ผ๐—ต๐—ป The Startup Cafรฉ •

Fair point on both counts. Non-streamed calls do not guarantee server-side cancellation even if the client disconnects, and anonymous identifiers are easy to bypass. A global route-level cap sized to what I can afford to lose overnight is a solid backstop when there is no real account identity.

Collapse
 
milochen0418 profile image
Milo Chen •

10 requests, every one 200 OK, and 160,000 tokens. That small test explains the problem better than any rule. The upstream call that keeps going after the user closes the tab is the one I would have missed.

In the app store I self-host, apps never hold an API key. They ask one AI hub for a "use" like fast or local, and I pick the model, so every AI call goes through one door. So I wonder where a cap fits best. When one backend serves several AI features, do you give each route its own token budget, or one shared budget per user?

Collapse
 
johnnylemonny profile image
๐—๐—ผ๐—ต๐—ป The Startup Cafรฉ •

Routing everything through a single hub makes enforcement much cleaner, and pairing a shared per-user budget with tighter per-route caps for expensive tasks usually covers both sides well. That keeps one feature from eating the whole allowance while still letting normal usage flow smoothly across the hub.

Collapse
 
robertpaschal profile image
Odinaka Robert Nnamani •

the user closes the tab and the server keeps generating tokens nobody reads. ten requests, 160,000 tokens, and the bill runs overnight.

Collapse
 
sara_builds profile image
Sara •

One small gap in the sample handler: checking prompt.length against a character cap is a useful first filter, but character count is a shaky stand-in for tokens. A pasted stack trace, minified bundle, or a blob of JSON can stay well under 8,000 characters and still be several thousand tokens. If the route later accepts images or files, a char cap barely applies. I started running a tokenizer (or the provider's token-count endpoint) on the actual payload and rejecting against a hard token budget before the generate call. Have you seen the char cap drift much once people start pasting logs or code into the prompt?

Collapse
 
johnnylemonny profile image
๐—๐—ผ๐—ต๐—ป The Startup Cafรฉ •

Stack traces, minified code, and JSON payloads eat tokens way faster than prose, so character length is definitely just a rough first pass rather than a real token ceiling. Counting tokens up front before calling the model is a much cleaner safeguard once people start pasting code or logs.

Collapse
 
ric0c0derlab profile image
Ric0 C0der Lab •

Per-user quotas and a hard spending ceiling seem like a good combination here. Rate limits alone don't necessarily prevent a costly runaway workflow.

Collapse
 
the_daily_flare profile image
The daily flare •

How did I miss that ten requests in 30 seconds could burn 160,000 tokens while every response still returned 200 OK?

Collapse
 
kling4ai-production profile image
Kling4 AI •

Twenty requests per minute sounds conservative for CRUD until a client loop packs 12k input tokens into each call and quietly burns 160k tokens in half a minute. Metering by estimated token budget rather than request count is really the only safe default.

Collapse
 
mudassirworks profile image
Mudassir Khan •

the 10 requests burning 160,000 tokens test is a good way to show why request counts are the wrong unit. we moved the limiter to a token budget per user per day, estimated on input before the call and reconciled with real usage after, and it caught a retry loop that the rpm limiter never saw.

one gap worth testing is streaming responses that get aborted, since the upstream usually bills the full output unless you forward the abort.

are you counting the reserved output cap against the budget up front, or only actual tokens after the response?

Collapse
 
ai_dev_planner profile image
AI Dev Planner •

The cost story here is exactly right, and the part that gets missed is the product trade-off: add auth and quotas too early and free-trial conversion dies; add them too late and one endpoint drains the budget. The middle path is spend alerts from day one, soft per-user quotas that degrade gracefully instead of hard-blocking, and auth only at the point where the cost per user actually matters. Rate limiting protects the server โ€” quotas protect the business.

Collapse
 
ascendra_ventures_92c21f2 profile image
Ascendra Ventures •

Request count having almost no correlation with cost is the core point, and your 10-request test makes it concrete: every call returned 200, none tripped the limiter, and the run still used 160,000 tokens. A limit counted in requests protects a CRUD endpoint. An LLM endpoint needs a limit counted in the thing that costs money, per user or per key, with a hard daily ceiling, as several comments say.

Ascendra Ventures applied the same principle on a candidate pipeline for a seed-stage talent platform, where each profile went through enrichment, OpenAI batch parsing and embeddings before the database writes. Urgent profiles are processed immediately and the rest are batched, with the batch path waiting durably for the OpenAI parse and embedding jobs. The case study states the result as a unit cost, $0.004 per candidate imported, alongside 99.99% system reliability. Expressing cost per unit of work is what turns the budget into a number someone can own, instead of a surprise on the invoice.

Murali's point about agent retry loops resending the whole context looks like the next gap. Would you cap tokens per run in the same middleware, or keep that as a separate guard inside the agent loop?

Collapse
 
hafizwaleedahmed5 profile image
Hafiz Waleed Ahmed •

Good reminder that request count is a poor proxy for cost on LLM routes. Besides capping max input and output tokens, have you tried passing the client's abort signal to the upstream call so generation stops when the user disconnects? I'm curious how much that saved in your tests.

Collapse
 
argumentmoney8117 profile image
ArgumentMoney8117 •

Building on Andrii's point about req.json() โ€” checking the Content-Length header before parsing is the cheap fix, since the header is available before the body is read. Pairing that with a payload cap at the platform level means the handler never has to trust its own code path to catch an oversized request.

Collapse
 
visionwei profile image
Wei Bin •

10 ไธช่ฏทๆฑ‚ๅœจ 30 ็ง’ๅ†…็ƒงๆމ 160,000 ไธช token ็š„ๆต‹่ฏ•ๅพˆๆœ‰่ฏดๆœๅŠ›๏ผŒๆŒ‰่ฏทๆฑ‚ๆ•ฐ้™ๆต็กฎๅฎžๅๆ˜ ไธไบ†็œŸๅฎžๆˆๆœฌใ€‚ๆˆ‘ไนŸ่ง‰ๅพ—็”จๆˆทๅ…ณๆމๆ ‡็ญพ้กตๅŽๆœๅŠก็ซฏ่ฟ˜ๅœจ็ปง็ปญ็”Ÿๆˆๆ˜ฏๆœ€้š่”ฝ็š„ๆณ„ๆผ๏ผŒๅ› ไธบ็”จๆˆทๆ นๆœฌ็œ‹ไธๅˆฐใ€‚ไฝ ๅœจๅšไผš่ฏ้ข„็ฎ—ๆ—ถ๏ผŒๆ˜ฏๆๅ‰ๆŠŠ้ข„็•™็š„ max_output_tokens ็ฎ—่ฟ›ๅŽป๏ผŒ่ฟ˜ๆ˜ฏๅชๆŒ‰ๅฎž้™…ๆถˆ่€—ๆฅ็ป“็ฎ—๏ผŸ

Collapse
 
vexaloom-labs profile image
vexaloom-labs •

An IP limit puts an entire office behind one throttle, letting one busy user ration everyone else's access. btw I just need a github like you....Crazy work :)