DEV Community

Cover image for One Unprotected AI Endpoint Can Drain Your Startup's API Budget Overnight
𝗝𝗼𝗵𝗻 for The Startup Café

Posted on AI-assisted

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

Agent retry loops compound token drain quickly

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.

Analytics dashboard displaying usage metrics and charts

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:

  1. A user submits a prompt, gets impatient after 3 seconds, and refreshes the page—or a bot closes the connection early.
  2. Your server handler ignores the aborted client socket.
  3. 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 });
}
Enter fullscreen mode Exit fullscreen mode

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.

Developer writing backend code on a dark-mode editor

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.signal into your upstream fetch or 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!

johnnylemonny GitHub Banner

Top comments (12)

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
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 
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?