What goes wrong
Moving the API key to the server stops people from stealing it, but your endpoint still spends money on behalf of whoever calls it. Free sign-ups, a buggy client retrying in a loop, or someone using your app as a free general-purpose model can run up a large bill, or exhaust your provider rate limit so real users get errors. OWASP lists this as LLM10:2025 Unbounded Consumption (it also covers “denial of wallet”).
The layers
- Key only on the server, behind your own authenticated endpoint.
- Hard caps per request: maximum input length and maximum output tokens.
- A request rate limit per user (requests per minute).
- A token budget per user per day, enforced before each call.
- A spend limit and usage alerts in the provider's console as the last line.
This guide covers 2 and 4; see the related guides for the others.
A daily token budget in Postgres
Reserve the worst case before calling the model (estimated input plus the output cap), then correct it with the real usage afterwards. The reserve is atomic, so parallel requests can't overspend:
create schema if not exists private;
create table if not exists private.ai_usage (
user_id uuid not null,
day date not null,
tokens bigint not null default 0,
primary key (user_id, day)
);
create or replace function public.reserve_ai_tokens(p_user uuid, p_tokens int, p_daily_limit bigint)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
declare
v_day date := (now() at time zone 'utc')::date;
v_total bigint;
begin
insert into private.ai_usage as u (user_id, day, tokens)
values (p_user, v_day, p_tokens)
on conflict (user_id, day) do update set tokens = u.tokens + excluded.tokens
returning u.tokens into v_total;
if v_total > p_daily_limit then
update private.ai_usage set tokens = tokens - p_tokens where user_id = p_user and day = v_day;
return false;
end if;
return true;
end;
$$;
create or replace function public.adjust_ai_tokens(p_user uuid, p_delta int)
returns void
language sql
security definer
set search_path = ''
as $$
update private.ai_usage set tokens = greatest(0, tokens + p_delta)
where user_id = p_user and day = (now() at time zone 'utc')::date;
$$;
revoke execute on function public.reserve_ai_tokens(uuid, int, bigint) from public, anon, authenticated;
revoke execute on function public.adjust_ai_tokens(uuid, int) from public, anon, authenticated;
grant execute on function public.reserve_ai_tokens(uuid, int, bigint) to service_role;
grant execute on function public.adjust_ai_tokens(uuid, int) to service_role;Use it around the model call
const MAX_INPUT_CHARS = 8000;
const MAX_OUTPUT_TOKENS = 600;
const DAILY_LIMIT = 200_000;
if (message.length > MAX_INPUT_CHARS) return new Response('Message too long', { status: 413 });
const reserved = Math.ceil(message.length / 3) + MAX_OUTPUT_TOKENS; // rough upper estimate
const { data: ok } = await admin.rpc('reserve_ai_tokens', {
p_user: user.id, p_tokens: reserved, p_daily_limit: DAILY_LIMIT,
});
if (!ok) return new Response('Daily AI limit reached', { status: 429 });
const r = await fetch('https://api.anthropic.com/v1/messages', {
method: 'POST',
headers: {
'x-api-key': Deno.env.get('ANTHROPIC_API_KEY')!,
'anthropic-version': '2023-06-01',
'content-type': 'application/json',
},
body: JSON.stringify({
model: Deno.env.get('ANTHROPIC_MODEL'),
max_tokens: MAX_OUTPUT_TOKENS,
messages: [{ role: 'user', content: message }],
}),
});
const out = await r.json();
const used = r.ok ? out.usage.input_tokens + out.usage.output_tokens : 0;
await admin.rpc('adjust_ai_tokens', { p_user: user.id, p_delta: used - reserved });With OpenAI's Chat Completions API the fields are usage.prompt_tokens and usage.completion_tokens, and the output cap is max_completion_tokens. If you stream, set stream_options: {"include_usage": true} and read the usage from the final chunk; without it, streamed responses report no usage at all. Conversation history counts as input on every call, so cap or summarise it too.
Provider-side limits
Set a monthly spend limit and usage alerts on the provider account, and use a separate project or workspace key per app so one app's runaway usage can't starve another. These don't replace per-user quotas: they protect your bill, but when they trip, every user is cut off at once.
How to verify
Set DAILY_LIMIT low in a test environment and send requests until you get 429; select * from private.ai_usage shows a total close to the limit, never far above it. Fire 20 parallel requests at the edge of the limit: the total still stays within one request of the limit. A message longer than the input cap gets 413 without any provider call in your logs.
Related guides
- AI API keys and system prompts in frontend code – find them and move the call server-side
- Rate limiting an API route – return 429 Too Many Requests before abuse costs you
- A .env file or API key in Git history – rotate first, then rewrite history
- Prompt injection through retrieved documents (RAG) – what it is and how to contain it
More in AI agent and LLM app security · all guides