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

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 (2)

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