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
- 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.
- 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.
- 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.
- 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.
- Cap the cost of each call. Set max_tokens or max_output_tokens, cap input length, and pin a cheaper model for free users.
- 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_KEYin aVITE_orNEXT_PUBLIC_variable is readable by anyone who opens dev tools. - The AI route has no login check. Even with the key server-side,
/api/chathappily 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.
Want us to look at your app?
VibeCPR Rescue Reports are launching soon: we scan your repo and live app, and a human verifies every critical finding. Join the waitlist for early access and founder pricing. You'll also get Patch Notes, our weekly fixes newsletter.
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
- OpenAI docs: Rate limits
- Anthropic docs: Rate limits
- Supabase docs: Rate limiting Edge Functions
- Vercel docs: Spend Management
- Cloudflare docs: Rate limiting rules
Related fixes
- AI agent pushed API keys to GitHub? git commit --no-verify skipped your pre-commit hook
- Your app is public to anyone with the link: a share link is not a login
- Triage Bolt's "RLS Policy Always True" warning: when it's fine and how to fix it
- Fix secrets leaked via Claude Code .claude/settings.local.json
- Fix "Your Cloud Firestore database has insecure rules" (Firebase email)
- Login lockout keyed only on email? Rate-limit by IP and account without locking users out
- Fix Lovable "Invalid API key" after rotating Supabase keys (anon, publishable, secret)
- Lovable won't publish because of security findings? What each finding means and how to fix it
- "Sign in with Google" lets anyone in: restrict who can use your app (allowlist, domain check, RLS)
- Fix Stripe sk_live keys left in MCP or agent config
- Fix Stripe webhook "No signatures found matching the expected signature for payload"
- Fix Supabase auth redirecting to localhost after deploy
- Fix Supabase Edge Function "blocked by CORS policy" (preflight)
- Fix Supabase "infinite recursion detected in policy for relation" (42P17) in RLS
- Form says success but no row in Supabase (or Stripe webhook returns 200 but writes nothing)
- Fix "new row violates row-level security policy for table" (Supabase)
- Supabase only returns 1,000 rows? Fix the silent max rows limit in Lovable and Bolt apps
- Fix Supabase "permission denied for table" (42501) on new tables after Oct 30, 2026
- Fix a Supabase public Storage bucket that lets anyone list or download your files
- Supabase Realtime leaking rows or not receiving changes: fix RLS and the publication
- Supabase RLS not working on the server? Your API uses the service_role or secret key
- Fix Supabase RLS policy USING (true) that makes a table publicly readable
- Your app's rules only live in the frontend: move them into Supabase
- Fix a Supabase SECURITY DEFINER function anyone can call through /rest/v1/rpc
- Fix Supabase .single() "JSON object requested, multiple (or no) rows returned" (PGRST116)
- Stop Supabase users from upgrading their own plan or making themselves admin
- Fix a Supabase view that bypasses RLS: security_invoker and revoking anon write grants
- Fix "404: NOT_FOUND" on refresh in a React/Vite app on Vercel (vercel.json rewrite)
- Fix "Module not found: Can't resolve" on Vercel (works locally)
- Is my Vite dev server exposed? Check --host / server.host and patch the RCE (GHSA-p4f5-76q4-ffq7)