VibeCPR

← All fixes

Security · Billing

Fix a surprise AI API bill: rate limits and spend caps

Updated · Applies to: OpenAI, Anthropic, Supabase, Vercel, Cloudflare, Lovable, Bolt, v0, Cursor, Replit

TL;DR fix: Most surprise bills come from three gaps: the AI key is shipped to the browser, the server route that calls the model has no login check, and nothing limits calls per user or IP. Fix: rotate the key and keep it server-side, require a signed-in user on the AI endpoint, add a per-user and per-IP rate limit, cap output tokens, and set a budget and alert with your AI provider and host (Vercel Spend Management can pause production deployments at a spend amount).

Steps

  1. Stop the bleeding. Rotate the AI provider key now. If the old key was in client code, assume it was copied. Check your provider's usage page to see which key and model the spend came from.
  2. Move the key server-side. Delete any VITE_, NEXT_PUBLIC_ or similar public env var holding an AI key. Call the model only from a server route or a Supabase Edge Function that reads the key from a secret.
  3. Require login on the AI endpoint. Verify the user's session (for example the Supabase JWT) at the top of the function and return 401 if it is missing.
  4. Add rate limits. Limit calls per user and per IP, for example with Upstash Redis in an Edge Function (Supabase has an official example) or a Cloudflare rate limiting rule in front of the route.
  5. Cap the cost of each call. Set max_tokens or max_output_tokens, cap input length, and pin a cheaper model for free users.
  6. Set budgets and alerts. Set usage limits or budget alerts in your AI provider's billing settings and turn on your host's spend management so a runaway bill pages you instead of surprising you.

Why vibe-coded AI apps get expensive fast

AI builders wire up the “chat with your data” feature in minutes, and they take shortcuts that cost money once strangers find the app:

  • The key ships to the browser. An OPENAI_API_KEY in a VITE_ or NEXT_PUBLIC_ variable is readable by anyone who opens dev tools.
  • The AI route has no login check. Even with the key server-side, /api/chat happily answers anyone who sends a POST.
  • Nothing counts calls. No per-user or per-IP limit, no cap on output tokens, no budget alert.

Provider rate limits apply to your whole account, so they decide how fast you can be drained, not whether.

The fix

1. Rotate the key and check the provider’s usage page for which key and model spent the money.

2. Keep the key server-side. Call the model from a server route or a Supabase Edge Function that reads it from a secret.

3. Require a user and limit them (Supabase Edge Function sketch):

const { data: { user } } = await supabase.auth.getUser(
  req.headers.get('Authorization')?.replace('Bearer ', '') ?? ''
);
if (!user) return new Response('Unauthorized', { status: 401 });

const { success } = await ratelimit.limit(user.id); // e.g. Upstash Ratelimit, 20 per minute
if (!success) return new Response('Too many requests', { status: 429 });

If you take the IP for a per-IP limit, read it from the header your host sets, not the left-most X-Forwarded-For value the client controls. The same rules apply to your login form: see login lockout keyed only on email for an atomic per-IP and per-account limit we tested.

4. Cap each call. Set max_tokens (or max_output_tokens), trim long inputs, and use a cheaper model for free users.

5. Set budgets and alerts with your AI provider and host. Vercel Spend Management can pause production deployments at a spend amount; a Cloudflare rate limiting rule can block floods before they reach your code.

If the key was public, other things probably are too: check for tables anyone can read with USING (true) and security definer functions anon can call. The same hunt often turns up Stripe sk_live_ keys pasted into MCP or Agent Toolkit config—rotate those separately; they do not cause your OpenAI bill, but they can empty your Stripe account. If you build with Claude Code, check whether keys were saved into a committed .claude/settings.local.json by “Yes, and don’t ask again” approvals: Fix secrets leaked via Claude Code settings.local.json.

Prompt for Cursor, Lovable, Bolt or Claude Code

Audit this app for AI API cost abuse. Find every place an AI provider key is read,
and move any key in a public env var (VITE_, NEXT_PUBLIC_, EXPO_PUBLIC_) to a
server-side secret. Make every route or Edge Function that calls a model require a
signed-in user, add a per-user and per-IP rate limit that returns 429, and set
max_tokens on every model call. Then list what I must set by hand: key rotation,
provider budget alerts, and host spend limits.

When to get help

Get help if you can't tell where the spend came from, your key was public and you need to know what else leaked, or you want auth, rate limits and budgets reviewed before launch.

FAQ

Why did my AI app run up a big bill overnight?

Usually because the model is reachable without limits: the API key is in browser code where anyone can copy it, or the server route that calls the model accepts requests from anyone with no login and no rate limit. A single script looping on that route can spend money as fast as the provider allows.

Is it safe to put my OpenAI key in a VITE_ or NEXT_PUBLIC_ variable?

No. Those prefixes exist to ship values to the browser, so the key is visible to every visitor. Keep AI keys in server-side secrets and call the model from a server route or Edge Function.

Do rate limits on the provider protect me?

Provider rate limits cap requests per minute for your whole account; they do not stop one stranger from using all of it. You still need your own per-user and per-IP limits, plus a budget alert.

How do I rate-limit a Supabase Edge Function?

Supabase publishes an example using Upstash Redis: count requests per user or IP in a short window and return 429 when the count is over your limit. Put the auth check before it so anonymous callers are rejected first.

Can my host stop the bill automatically?

Vercel Spend Management can notify you, call a webhook, or pause the production deployment of your projects when you hit a set spend amount. On other hosts, set billing alerts and put a rate limiting rule (such as Cloudflare's) in front of expensive routes.

Sources

Related fixes