Add AI Chat to Your Supabase App Without a Surprise Bill
Per-user LLM token limits for a streaming Claude chat on Supabase: reserve before each call, settle on every exit, never trust the browser.
Every AI feature you add to a SaaS spends your money on someone else's request. A user with a script or five open tabs becomes a line on your invoice. The usual fix is a per-user token limit. The usual implementation of that limit has a hole in it.
This post walks through how the AI chat package in LaunchSaaS, packages/ai-patterns, closes that hole: a streaming Claude chat for a Supabase app, with saved conversations and a per-user daily token budget enforced in Postgres. To be upfront about where it comes from: unlike most of the boilerplate, this package was not extracted from one of my production apps. I wrote it for the boilerplate in December 2026, tested it against a real local Supabase stack, and checked it once against the live Anthropic API.
Why "check usage, then call" overspends
The obvious version reads today's usage for the user, compares it with the limit, and calls the model if there is room. It fails as soon as requests overlap.
Say the limit is 200,000 tokens and the user has used 195,000. Five requests arrive in the same second. All five read 195,000, all five see room, all five call the model. Each reply can be up to 8,000 output tokens plus its input, so the user can end the day near 240,000, and nothing in your code ever said no. Streaming makes it worse: a chat call lasts seconds, and so does the window for the next request to slip past the check.
The check and the spend have to be one step. The repo's DECISIONS.md lists the naive version as the rejected option for exactly this reason: "Check usage, then call: concurrent requests all pass the check."
Reserve before the call, settle after it
Instead of reading usage, the Edge Function reserves the worst case before it calls the model: a rough input estimate plus the full output allowance (AI_MAX_OUTPUT_TOKENS, 8,000 by default). The estimate is deliberately on the high side, about 3 characters per token, from shared/chat.ts:
export function reservationFor(texts: string[], maxOutputTokens: number): number {
const chars = texts.reduce((sum, t) => sum + t.length, 0);
return Math.ceil(chars / 3) + maxOutputTokens;
}
The reservation itself is a single SQL statement inside ai_reserve_tokens, in sql/ai-schema.sql. One ai_usage row per user per UTC day holds what was spent and what is reserved by calls still running:
INSERT INTO ai_usage AS u (user_id, day, reserved_tokens)
VALUES (p_user_id, v_day, p_tokens)
ON CONFLICT (user_id, day) DO UPDATE
SET reserved_tokens = u.reserved_tokens + EXCLUDED.reserved_tokens
WHERE u.input_tokens + u.output_tokens + u.reserved_tokens + EXCLUDED.reserved_tokens <= p_limit
RETURNING v_day INTO v_ok;
The WHERE on the DO UPDATE is the whole trick. ON CONFLICT takes a row lock, so concurrent reservations for the same user queue behind each other, and each one sees the totals the previous one left. If spent plus reserved plus this request would pass the limit, the update matches nothing, the function returns NULL, and the Edge Function answers 429 before a single token is spent. A guard above it also rejects any one reservation larger than the whole daily limit.
After the call, ai_settle_tokens releases the reservation and records what the API says was actually used, again in one UPDATE.
One honest limit: the input half of the reservation is an estimate. What this guarantees is that concurrent calls cannot reserve past the daily limit, not that real usage can never land slightly above it when a prompt tokenizes worse than 3 characters per token.
Settle on every exit path, including the closed tab
A reservation that is never settled leaks budget the other way: the user is locked out for the rest of the day by tokens nobody spent. So the function settles on every path, through one settle() that runs at most once:
- Normal reply: settle, save both turns, send
done. - Refusal: settle, send an error with code
refusal, save nothing. A refused call still used input tokens, and the budget says so. - Mid-stream API error: settle, send an
upstreamerror, save nothing. - Browser disconnect: handled by the response stream's
cancel().
The disconnect is the one most implementations miss. When a user closes the tab or hits stop, the server keeps streaming from the model unless something tells it not to, and you pay for a reply nobody will read. In edge-functions/ai-chat.ts:
async cancel() {
// Browser went away: stop paying for tokens nobody reads, then settle
modelStream.abort();
await settle();
},
The abort stops generation, and the settle releases the reservation and records the usage reported up to that point. If a call fails before the API has reported any input size, there is nothing real to record, so the function charges the whole reservation instead of guessing low:
// Unknown input (failed before message_start): charge the whole reservation
const charged = inputTokens === null ? { p_input: reserved, p_output: 0 } : { p_input: inputTokens, p_output: outputTokens };
Count tokens from the API, not from the text
It is tempting to count usage from the reply you streamed. Don't. The text you see is not what you are billed for: input includes the system prompt, the history and any cached prompt tokens, and output includes thinking tokens you never display. The function reads the usage fields the Messages API sends while it streams:
if (event.type === 'message_start') {
const u = event.message.usage;
inputTokens = u.input_tokens + (u.cache_creation_input_tokens ?? 0) + (u.cache_read_input_tokens ?? 0);
} else if (event.type === 'message_delta') {
outputTokens = event.usage.output_tokens; // cumulative; includes thinking
}
Both cache fields are added to input on purpose. The budget is a token count, not a bill, so a cached token counts like any other. If you want the limit to track money more closely, that is the line to change.
Never let the browser choose the model, prompt or history
The request body has two fields, and parseChatRequest in shared/chat.ts reads only those:
const { message, conversationId } = body as { message?: unknown; conversationId?: unknown };
Everything else comes from the server. The model comes from the AI_MODEL setting, so a client cannot switch itself to a pricier model. The system prompt comes from AI_SYSTEM_PROMPT, so it cannot be rewritten. The new turn always has the user role, and history is loaded from ai_messages by the function, so nobody can send a fake assistant turn or paste an enormous "history" into a request. Message length and history length are capped by settings too. The package's agent skill states the reason plainly: each of those fields "is a way to spend more or to inject instructions."
RLS: owners read, only the service role writes
Three tables hold the state: ai_conversations, ai_messages and ai_usage. All three have row level security on. Signed-in users can read their own rows and delete their own conversations, and that is all. Inserts and updates on messages and usage are revoked from the authenticated role, and the two budget functions can be executed only by service_role. Otherwise users could reset their own budget, or plant an assistant turn that the next request sends to the model as history.
The Edge Function writes with the service role, which bypasses RLS. That makes the function itself the security boundary, so every query it runs filters by the signed-in user's id. Posting into someone else's conversation returns 404, the same as a conversation that does not exist.
A stream format that can tell you it was cut off
The function answers with NDJSON, one event per line, typed in shared/chat.ts:
export type ChatEvent =
| { type: 'start'; conversationId: string }
| { type: 'text'; text: string }
| { type: 'done'; inputTokens: number; outputTokens: number }
| { type: 'error'; code: 'refusal' | 'upstream' | 'limit'; message: string };
A plain text stream cannot tell "the model finished" apart from "the connection dropped halfway through a sentence". With an explicit done line it can: the hook treats a stream that ends without done or error as interrupted and tells the user "The reply was interrupted. Try again." The server saves the exchange only right before it sends done, so a cut-off reply never ends up in the history the next request sends to the model. Errors before streaming starts are plain JSON with a status code, such as 429 when the budget is spent.
Anthropic SDK or Vercel AI SDK
The package ships the same function twice. ai-chat.ts uses the official Anthropic SDK (npm:@anthropic-ai/sdk@1.10.0). ai-chat-vercel.ts is a drop-in alternative on the Vercel AI SDK (npm:ai@7.0.173 with npm:@ai-sdk/anthropic@4.0.105). Same request, auth, ownership checks, budget SQL, stream protocol and hook. You deploy one, not both.
- Pick the Anthropic SDK if you are building on Claude and want the fewest dependencies. That is why it is the default.
- Pick the Vercel AI SDK if you already use it in your app or expect to switch providers. Switching means changing the import, the model line and the allowed models, and recomputing the daily limit.
The Vercel variant has one trap worth knowing even if you never use this code: errors and aborts arrive as error and abort parts in fullStream, not as exceptions. So the function treats a reply as complete only when a finish part arrives with a normal reason, and reports anything else as an error. With a non-Anthropic provider there is also no Anthropic start event carrying the input count, so a stream that fails midway is charged the whole reservation.
Models and refusals
The model is set by AI_MODEL and checked at startup against an allowlist: claude-opus-5-5 (the default), claude-sonnet-5-5 or claude-haiku-5-5. A typo fails at boot, not on a user's first message. Chat calls use low effort, since chat rarely gains from more.
On Opus 5.5 and Sonnet 5.5 the function also sends fallbacks: 'default' with the server-side-fallback-2026-07-01 beta: if the model declines a request, the API retries on a fallback model inside the same call. Haiku 5.5 takes no fallback parameter, so the function leaves it out. If the final answer is still a refusal, the user sees an error, nothing is saved, and the tokens still count against the budget.
The limit itself is a business decision. AI_DAILY_TOKEN_LIMIT defaults to 200,000 input plus output tokens per user per UTC day. Work it out from what the user pays you and the model's current per-token price on Anthropic's pricing page, and redo the sum whenever you change AI_MODEL.
How it was tested
tests/supabase/run.sh starts a local Supabase stack and runs both Edge Functions unmodified, with their real SDKs, against a stubbed Anthropic API. The stub answers any request that does not have the expected model, max_tokens, roles and fallback settings with a 400, which the SDK raises, so a wrong request shape fails the suite instead of passing quietly.
The checks that matter most for your bill:
- Concurrency: five concurrent calls against a budget that fits three return three 200s and two 429s, and nothing is left reserved afterwards.
- Disconnect: the test reads the first text chunk, aborts, and checks that the reservation is released and no half reply is saved.
- Refusal and mid-stream error: both end in an error event, save nothing and are still charged, with their reservations released.
- Browser-chosen fields: a request that also sends a different model, a
systemrole and a fake history gets a normal reply: the stub would reject a wrong model or role, and the reply shows that only the stored history was sent.
The suite also covers ownership and RLS, and runs every check once per function. A separate SQL suite tests the policies and the budget functions on their own.
What a stub cannot prove is that the real API accepts these requests. So on 2026-12-01 each function's exact request settings (claude-opus-5-5, low effort, refusal fallbacks on) went through one live call per SDK. Both returned a normal reply and usage, 51 input tokens each. Sonnet 5.5 and Haiku 5.5 were not checked live, and no deployed round trip has recorded a row in ai_usage yet. Before you go live, send one message through your deployed function and compare ai_usage with the usage the Claude Console shows for that request.
The short version
- Reserve the worst case in one atomic SQL statement before calling the model. Never read usage and then call.
- Settle on every exit: success, refusal, error and disconnect. Abort the model call when the browser goes away.
- Count from the API's usage fields. Output includes thinking.
- Let the browser send a message and a conversation id, nothing else.
- Users read their own rows. Only the server writes.
- End every stream with an explicit done or error line.
If you would rather copy this than write it, ai-patterns is one of the packages in LaunchSaaS. It comes with an agent skill, .agents/skills/ai-patterns/SKILL.md, that tells Claude Code or another coding agent which files go where and which rules not to break.
FAQ
How do I set a per-user token limit for an AI chat on Supabase?
Keep one usage row per user per day and reserve the worst case for each call, an input estimate plus the maximum output, in a single INSERT ... ON CONFLICT DO UPDATE ... WHERE statement before calling the model. Settle with the real usage from the API afterwards. Reading usage first and then calling lets concurrent requests overspend.
Does a closed browser tab still cost tokens?
It can, unless the server notices. In the LaunchSaaS ai-patterns package the response stream has a cancel handler that aborts the model call and settles the budget, so generation stops and the reservation is released when the browser goes away.
Should I use the Anthropic SDK or the Vercel AI SDK for a Claude chat?
Use the Anthropic SDK if you are building on Claude and want the fewest dependencies. Use the Vercel AI SDK if your app already uses it or you expect to switch providers. LaunchSaaS ships the same chat function on both, with the same budget SQL and stream protocol.
Which Claude model should a SaaS chat use?
The ai-patterns package defaults to claude-opus-5-5 and also accepts claude-sonnet-5-5 or claude-haiku-5-5 through the AI_MODEL setting. Set the daily token limit from your plan price and the model you pick. Only Opus 5.5 was checked against the live API.
Related Articles
- Does LaunchSaaS Support Your Tech Stack?
- How Customizable Is the LaunchSaaS Boilerplate?
- Is AI Killing Your SaaS? How to Defend Churn
Ready to ship
Skip the boilerplate. Ship your product.
16 packages with an agent skill each and 200+ tests of their own. Most are extracted from apps used by 13,000+ people (2,335 tests in those apps). One-time payment, lifetime access.
Get Instant Access - $99