Deutsch
Fix libraryMediumAI · Costs

No AI spend cap: one bug or one abuser can empty your budget

Without a hard spend limit at your AI provider and a per-user quota in your app, one leaked key or bot can run up a large bill. Set both before launch.

By Tim GeithnerPublished 4 min read

ShipRely's AI & API Integrations audit is in development and will check for this.

Short answer

AI features cost money per request, so an app without limits turns any abuse into a bill. Set a hard monthly spend limit in your OpenAI or Anthropic account, ideally on a separate project or workspace for production, and add a per-user daily quota on the server that the browser cannot reset. Fix the model and the token limit in the server function so callers can’t choose expensive options.

Ask an AI about this page:ChatGPTClaude

On this page

Without a spend cap, the cost of your AI feature has no upper end. A leaked key, a bot that signs up a hundred accounts or a loop in your own code can send thousands of paid requests before anyone looks at the dashboard. The fix has two parts: a hard monthly limit at the AI provider, and a per-user quota inside your app. It is rated medium because it doesn’t expose data by itself, but it turns every other mistake, such as an AI key in client code, into a bill.

Why it matters

AI requests are priced per token, so cost grows with use, including abuse. OWASP lists this as unrestricted resource consumption in its API Security Top 10, and its advice is short: “Configure spending limits for all service providers/API integrations.” The same category counts missing limits on request size and on operations per request.

Three things in AI-built apps make the risk real:

  • Open sign-up. Most apps let anyone create an account, and a function that only checks “is signed in” serves every one of them.
  • Caller-controlled options. If the browser sends model or max_tokens, a caller can pick the most expensive model and the longest answer.
  • No ceiling at the provider. New accounts often start with only notification thresholds. A notification doesn’t stop traffic.

How to find it in your app

Check both sides, the provider account and your code.

At the provider. In OpenAI’s platform, open the limits page and look for a hard spend limit; OpenAI’s production guide notes that hard limits stop API traffic while spend alerts only notify, and that you can set spend limits per project. In the Claude Console, open Spending → Spend limits: Anthropic’s docs say you can set your own monthly limit below your tier’s cap, and separate limits per workspace. If you find only an alert, or no limit at all, that’s the defect.

In your code. Open every function that calls an AI provider and look for three things:

Search your repository
grep -rln "api.openai.com\|api.anthropic.com\|openai\|anthropic" supabase/functions
grep -rn "body.model\|body.max_tokens\|req.json()" supabase/functions

Is there a per-user counter that the function checks before calling the provider? Are the model and the output token limit fixed on the server? Is the prompt length capped? A “no” to any of them means one account can spend without limit.

How to fix it

1. Set a hard limit at the provider. Use a separate OpenAI project or Claude workspace for production, give it its own key, and set a monthly spend limit that you can afford to lose in a bad month. Add an alert at around half of it, so you hear about unusual traffic before requests stop.

2. Add a daily quota per user. Count each AI call in your database, on the server, before you pay for it. This table and function do it in one atomic statement:

SafeA daily quota per user
create table public.ai_usage (
  user_id uuid not null references auth.users (id) on delete cascade,
  day date not null default current_date,
  requests integer not null default 0,
  primary key (user_id, day)
);

alter table public.ai_usage enable row level security;
revoke all on table public.ai_usage from anon, authenticated;
grant select on table public.ai_usage to authenticated;

create policy "Users can read their own AI usage"
  on public.ai_usage for select
  to authenticated
  using ((select auth.uid()) = user_id);

create or replace function public.use_ai_quota(p_user_id uuid, p_daily_limit integer)
returns boolean
language plpgsql
set search_path = ''
as $$
declare
  v_requests integer;
begin
  insert into public.ai_usage as u (user_id, day, requests)
  values (p_user_id, current_date, 1)
  on conflict (user_id, day)
    do update set requests = u.requests + 1
  returning u.requests into v_requests;

  return v_requests <= p_daily_limit;
end;
$$;

revoke execute on function public.use_ai_quota(uuid, integer)
  from public, anon, authenticated;
grant execute on function public.use_ai_quota(uuid, integer)
  to service_role;

Users may read their own row, so you can show “12 of 50 used today”, but they cannot write to the table or call the function, so they can’t reset their counter. on conflict … do update makes the count atomic: Postgres guarantees an insert or an update even under concurrency, so two parallel requests can’t both slip through as “the first”. Refused calls are counted too, so hammering the endpoint doesn’t help.

3. Check the quota in the function, and fix the expensive options there.

Safesupabase/functions/ai-suggest/index.ts
import { withSupabase } from "npm:@supabase/server@1";

const DAILY_AI_REQUESTS = 50;

export default {
  fetch: withSupabase({ auth: "user" }, async (_req, ctx) => {
    // Count the call before paying for it; the function is callable by the service role only.
    const { data: allowed, error } = await ctx.supabaseAdmin.rpc("use_ai_quota", {
      p_user_id: ctx.userClaims!.id,
      p_daily_limit: DAILY_AI_REQUESTS,
    });
    if (error) return Response.json({ error: "Try again later" }, { status: 503 });
    if (!allowed) return Response.json({ error: "Daily AI limit reached" }, { status: 429 });

    // ... read the prompt, call the AI provider with a fixed model and max_completion_tokens
    return Response.json({ ok: true });
  }),
};

The function fails closed: if the quota check errors, no AI call happens. For short bursts, add a per-minute limit as described in no rate limit on login or AI endpoints. The guide to calling AI APIs safely covers the proxy pattern in full.

Add a per-user AI quota

Add a new Supabase migration with a table public.ai_usage (user_id, day, requests, primary key user_id and day) with row level security enabled, all privileges revoked from anon and authenticated, select granted to authenticated and a select policy limited to (select auth.uid()) = user_id. Add a function public.use_ai_quota(p_user_id uuid, p_daily_limit integer) returning boolean that increments today’s counter with insert on conflict do update and returns whether the new count is within the limit; revoke execute from public, anon and authenticated and grant it to service_role only.

In every edge function that calls an AI provider, call use_ai_quota with the verified user id before the provider call and return 429 when it returns false or 503 when it errors. Fix the model and the output token limit in the function and cap the prompt length; ignore any model or token values sent by the browser.

Check that the fix works

  1. In the provider dashboard, confirm a hard limit (not only an alert) on the project or workspace whose key your app uses.
  2. Temporarily set DAILY_AI_REQUESTS to 2, call the AI feature three times as one user: the third call must get 429, and a second user must still get an answer.
  3. Try to reset a counter as a signed-in user in the SQL Editor, with a real user ID from Authentication → Users. It must fail with permission denied for table ai_usage:
A user cannot reset their own quota
begin;
set local role authenticated;
set local request.jwt.claims = '{"sub": "11111111-1111-1111-1111-111111111111", "role": "authenticated"}';
update public.ai_usage set requests = 0;
rollback;
  1. Send a request with "model": "<an expensive model>" in the body: the provider dashboard must still show only your fixed model.

We ran the SQL on this page against Postgres with Supabase’s roles: the fourth call over a limit of three is refused, users only see their own row and get permission denied when they try to reset it, and neither visitors nor users can call the function.

Frequently asked questions

Is a spend alert enough?

No. OpenAI’s docs distinguish alerts, which only send a notification, from hard spend limits, which stop API traffic when the limit is reached. An alert at 2 a.m. doesn’t stop a bot; set a hard limit and use alerts as an early warning.

What happens to my app when the limit is reached?

The provider rejects requests until the period resets or you raise the limit. Anthropic, for example, returns an error with a message that the specified usage limit was reached. Catch that error in your function and show users a friendly message instead of a crash.

How high should the per-user quota be?

Base it on real usage: look at what your most active honest users need per day and add some room. Paying plans can get a higher number. The point is that no single account can cost more than you earn from it.

Do I still need a quota if I have a rate limit?

They do different jobs. A rate limit (for example 10 requests a minute) stops bursts; a daily quota stops a patient abuser who stays just under the burst limit all day. Most apps with paid AI calls want both.

Sources

  1. 1.Production best practices — OpenAI API Docs
  2. 2.Rate limits (spend limits) — Claude Docs
  3. 3.API4:2023 Unrestricted Resource Consumption — OWASP API Security Top 10
  4. 4.CWE-770: Allocation of Resources Without Limits or Throttling — MITRE
  5. 5.INSERT … ON CONFLICT — PostgreSQL Documentation

Find this in your own app

ShipRely reads your repository (read-only), proves each finding with file and line, and gives you a fix prompt to paste into your AI builder.

Run a demo audit
  • Read-only access to your repository
  • Every finding with file and line
  • Fix prompts for Lovable, Cursor, Claude Code and Bolt