This article was drafted with AI help and reviewed by the author.
Adding an AI assistant to a mobile app is easy now. The hard question comes a month later. Why did the model bill triple when daily users only went up a bit?
It's often a few heavy users. Someone pastes a long document every few minutes. Someone keeps one chat open all day, so every message resends a huge history. A test script on a stolen session hammers the endpoint.
The bill is per token, but your users are people. So meter per person.
This post sets up a daily allowance per signed-in user. Postgres in Supabase keeps the count. An Edge Function enforces it and keeps prompts small. The Flutter app shows the limit like a normal product feature, not a crash.
What was checked: the Edge Function passed deno check (Deno 2.9, supabase-js 2.119). The Dart passed flutter analyze (Flutter 3.47, supabase_flutter 2.18). The SQL was parsed with a PostgreSQL parser. None of it was run against a live Supabase project or a model API. All limits and weights are example values.
Why the limit can't live in the app
A daily counter in SharedPreferences is tempting. It's also useless. Reinstall the app and the counter resets. Call the API from a script and there's no app at all.
The model key already has to stay on your server. The allowance belongs right next to it, in the same function that calls the model.
Count weighted tokens, not messages
"20 messages a day" sounds fair until one message is a pasted contract.
Tokens are fairer, with one twist. Output tokens usually cost several times more than input tokens. So count a weighted number:
``text weighted = input tokens + (output price / input price) x output tokens ``
If your model's output price is four times its input price, a reply of 300 tokens counts like 1,200 input tokens. Look up the real ratio for your model on the provider's pricing page. The code below uses 4 only as an example.
This keeps one simple number per user that tracks cost closely, without hard-coding dollar prices in your database.
The usage table
```sql create table public.aiusagedaily ( userid uuid not null references auth.users (id) on delete cascade, day date not null, inputtokens bigint not null default 0, outputtokens bigint not null default 0, weightedtokens bigint not null default 0, requests int not null default 0, primary key (user_id, day) );
alter table public.aiusagedaily enable row level security;
create policy "Users read their own usage" on public.aiusagedaily for select to authenticated using ((select auth.uid()) = user_id); ```
One row per user per UTC day. Row level security lets a signed-in user read their own row, for a usage screen in settings. Nobody writes through the API directly.
A function only the server can call
```sql create or replace function public.recordaiusage( puser uuid, pinput int, poutput int, pweighted int ) returns bigint language sql security definer set searchpath = '' as $$ insert into public.aiusagedaily as u (userid, day, inputtokens, outputtokens, weightedtokens, requests) values (puser, (now() at time zone 'utc')::date, pinput, poutput, pweighted, 1) on conflict (userid, day) do update set inputtokens = u.inputtokens + excluded.inputtokens, outputtokens = u.outputtokens + excluded.outputtokens, weightedtokens = u.weightedtokens + excluded.weightedtokens, requests = u.requests + 1 returning weightedtokens; $$;
revoke execute on function public.recordaiusage(uuid, int, int, int) from public, anon, authenticated; grant execute on function public.recordaiusage(uuid, int, int, int) to service_role; ```
The on conflict ... do update makes each charge one atomic statement. Two replies finishing at the same moment both get added.
The revoke matters in Supabase. Functions in the public schema can be called by anon and authenticated through the API unless you take that away. Without it, any user could call record_ai_usage with a negative number and refill their own allowance.
The Edge Function
```ts import { createClient } from 'npm:@supabase/supabase-js@2'
// Example values. Tune them to your model and your free tier. const DAILYALLOWANCE = 200000 // weighted tokens per user per UTC day const OUTPUTWEIGHT = 4 // your model's output price divided by its input price const MAXOUTPUTTOKENS = 400 const MAXTURNS = 8 const MAXCHARSPERTURN = 2000 const MODEL = Deno.env.get('CHAT_MODEL') ?? 'your-model-id'
type Turn = { role: 'user' | 'assistant', content: string }
const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' }, })
const nextUtcMidnight = () => { const d = new Date() d.setUTCHours(24, 0, 0, 0) return d.toISOString() }
// Never trust the client with prompt size. Keep the last few turns and cap each one. const trimHistory = (raw: unknown): Turn[] => { if (!Array.isArray(raw)) return [] return raw .filter((t) => t && (t.role === 'user' || t.role === 'assistant') && typeof t.content === 'string') .slice(-MAXTURNS) .map((t) => ({ role: t.role, content: t.content.slice(0, MAXCHARSPERTURN) })) }
const extractText = (result: { output?: Array<{ type: string, content?: Array<{ type: string, text?: string }> }> }) => (result.output ?? []) .filter((item) => item.type === 'message') .flatMap((item) => item.content ?? []) .filter((part) => part.type === 'output_text') .map((part) => part.text ?? '') .join('')
// Injected by Supabase. Older projects can use SUPABASEANONKEY and SUPABASESERVICEROLEKEY. const url = Deno.env.get('SUPABASEURL')! const publishableKey = JSON.parse(Deno.env.get('SUPABASEPUBLISHABLEKEYS')!)['default'] const secretKey = JSON.parse(Deno.env.get('SUPABASESECRETKEYS')!)['default']
Deno.serve(async (req) => { const userClient = createClient(url, publishableKey, { global: { headers: { Authorization: req.headers.get('Authorization') ?? '' } }, }) const { data: { user } } = await userClient.auth.getUser() if (!user) return json({ error: 'unauthorized' }, 401)
const admin = createClient(url, secretKey) const today = new Date().toISOString().slice(0, 10)
const { data: row, error: readError } = await admin .from('aiusagedaily') .select('weightedtokens') .eq('userid', user.id) .eq('day', today) .maybeSingle() if (readError) return json({ error: 'usage_unavailable' }, 503)
const used = Number(row?.weightedtokens ?? 0) if (used >= DAILYALLOWANCE) { return json({ error: 'daily_limit', remaining: 0, resetsAt: nextUtcMidnight() }, 429) }
const body = await req.json().catch(() => ({})) const input = trimHistory(body.messages) if (input.length === 0) return json({ error: 'empty_message' }, 400)
const modelRes = await fetch('https://api.openai.com/v1/responses', { method: 'POST', headers: { Authorization: Bearer ${Deno.env.get('OPENAI_API_KEY')}, 'Content-Type': 'application/json', }, body: JSON.stringify({ model: MODEL, instructions: 'You are the in-app help assistant. Keep answers short.', input, maxoutputtokens: MAXOUTPUTTOKENS, }), }) if (!modelRes.ok) return json({ error: 'model_error' }, 502)
const result = await modelRes.json() const inputTokens = Number(result.usage?.inputtokens ?? 0) const outputTokens = Number(result.usage?.outputtokens ?? 0) const weighted = inputTokens + OUTPUT_WEIGHT * outputTokens
const { data: total, error: writeError } = await admin.rpc('recordaiusage', { puser: user.id, pinput: inputTokens, poutput: outputTokens, pweighted: weighted, }) if (writeError) console.error('usage write failed', user.id, writeError.message)
const newTotal = writeError ? used + weighted : Number(total) return json({ reply: extractText(result), remaining: Math.max(0, DAILY_ALLOWANCE - newTotal), resetsAt: nextUtcMidnight(), }) }) ```
Some choices in there deserve a sentence each.
Check before, charge after. The function refuses the call if today's total is already at the allowance. Otherwise it calls the model and adds the real usage afterwards. A user can go a little over on their last message. That's fine for an allowance. If you need a hard money cap, reserve a worst-case amount before the call instead.
The server trims the prompt. The client sends the history, but the function keeps only the last eight turns and caps each one. Never let the client decide how big the prompt is. That's where most runaway input tokens come from in chat features.
Cap the output too. max_output_tokens puts a ceiling on the expensive side of every call.
Fail open on the write, closed on the read. If reading usage fails, the function refuses with 503. If writing usage fails after a successful reply, the user still gets the answer and the error is logged. Pick the opposite if a missed charge worries you more than an unhappy user.
Keys come from the platform. Supabase injects SUPABASE_URL, SUPABASE_PUBLISHABLE_KEYS and SUPABASE_SECRET_KEYS into Edge Functions. The secret key bypasses row level security, so it never leaves the function. Projects still on legacy keys can read SUPABASE_ANON_KEY and SUPABASE_SERVICE_ROLE_KEY instead. Set OPENAI_API_KEY and CHAT_MODEL yourself with supabase secrets set.
The Flutter side
The app's job is to make the limit feel normal. Send once, show how much is left, and explain the reset time when it runs out.
First a small service. It returns a sealed result so the UI has to handle all three cases.
```dart import 'package:supabaseflutter/supabaseflutter.dart';
sealed class ChatResult { const ChatResult(); }
class ChatReply extends ChatResult { const ChatReply(this.text, this.remaining, this.resetsAt); final String text; final int remaining; final DateTime? resetsAt; }
class ChatLimitReached extends ChatResult { const ChatLimitReached(this.resetsAt); final DateTime? resetsAt; }
class ChatFailed extends ChatResult { const ChatFailed(this.reason); final String reason; }
class AiChatService { AiChatService(this._client);
final SupabaseClient client; bool inFlight = false;
bool get isBusy => _inFlight;
Future<ChatResult> send(List<Map<String, String>> turns) async { // One request at a time. A double tap should not cost twice. if (inFlight) return const ChatFailed('busy'); inFlight = true; try { final res = await client.functions.invoke( 'chat', body: {'messages': turns}, ); final data = Map<String, dynamic>.from(res.data as Map); return ChatReply( data['reply'] as String? ?? '', (data['remaining'] as num?)?.toInt() ?? 0, DateTime.tryParse(data['resetsAt'] as String? ?? ''), ); } on FunctionException catch (e) { if (e.status == 429) { final details = e.details is Map ? e.details as Map : const {}; return ChatLimitReached( DateTime.tryParse(details['resetsAt']?.toString() ?? ''), ); } return ChatFailed('http${e.status}'); } catch () { return const ChatFailed('network'); } finally { inFlight = false; } } } ```
functions.invoke throws a FunctionException for a non-2xx response. The function's JSON body comes back in details, which is where resetsAt lives.
The in-flight flag is a cost control, not just a UI nicety. Without it, a double tap on a slow network sends two full prompts.
Then the composer:
```dart import 'package:flutter/material.dart';
import 'aichatservice.dart';
class ChatComposer extends StatefulWidget { const ChatComposer({super.key, required this.service, required this.history});
final AiChatService service; final List<Map<String, String>> history;
@override State<ChatComposer> createState() => _ChatComposerState(); }
class ChatComposerState extends State<ChatComposer> { final controller = TextEditingController(); bool sending = false; int? remaining; DateTime? _limitResetsAt;
Future<void> send() async { final text = controller.text.trim(); if (text.isEmpty || _sending) return;
setState(() => _sending = true); final turns = [ ...widget.history, {'role': 'user', 'content': text}, ]; final result = await widget.service.send(turns); if (!mounted) return;
setState(() { sending = false; switch (result) { case ChatReply(text: final reply, :final remaining): widget.history ..add({'role': 'user', 'content': text}) ..add({'role': 'assistant', 'content': reply}); controller.clear(); remaining = remaining; case ChatLimitReached(:final resetsAt): limitResetsAt = resetsAt ?? DateTime.now().toUtc(); case ChatFailed(): break; } }); }
@override void dispose() { _controller.dispose(); super.dispose(); }
@override Widget build(BuildContext context) { final limited = limitResetsAt != null; return Column( mainAxisSize: MainAxisSize.min, children: [ if (limited) Padding( padding: const EdgeInsets.all(8), child: Text( 'You have used today\'s assistant allowance. ' 'It resets at ${TimeOfDay.fromDateTime(limitResetsAt!.toLocal()).format(context)}.', ), ), if (remaining != null && !limited && remaining! < 20000) const Padding( padding: EdgeInsets.all(8), child: Text('You are close to today\'s assistant limit.'), ), Row( children: [ Expanded( child: TextField( controller: controller, enabled: !limited, maxLength: 2000, decoration: const InputDecoration(hintText: 'Ask a question'), ), ), IconButton( icon: sending ? const SizedBox.square( dimension: 20, child: CircularProgressIndicator(strokeWidth: 2), ) : const Icon(Icons.send), onPressed: sending || limited ? null : send, ), ], ), ], ); } } ```
The send button is disabled while a request is running and after the limit is hit. The text field has a maxLength that matches the server's per-turn cap, so users see the limit before the server cuts their text. When the allowance is close, a quiet hint appears. When it's gone, the app says when it comes back, in local time.
The history is added only after a successful reply. A failed send leaves the text in the box so the user can retry.
Testing it without a big bill
- Set
DAILY_ALLOWANCEto something tiny, like 2,000, in a staging project. You'll hit the limit in two or three messages. - Paste a very long message and confirm the function trims it. Log
input.lengthand the character counts while testing. - Call the function from
curlwith a user's JWT and confirm the 429 body. - Try calling
record_ai_usagewith the anon key. It should be refused.
Limitations
- Check-then-charge can overshoot. Several requests in flight at once can each pass the check. The client lock stops double taps, not scripts. Per-call caps keep the overshoot bounded.
- The day is UTC. Users in other zones see a reset in the middle of their day. The app shows the local time, which helps, but you could store a per-user zone instead.
- Weighted tokens track cost only if the weight matches your model. Re-check it when you change models.
- This meters the chat function only. Embeddings, file processing and other model calls need their own counting, or they need to go through the same function.
- Nothing here replaces a spend limit at the provider. Set that too.
Takeaways
- Meter AI usage per user on the server, never in the app.
- Count weighted tokens so long replies cost what they really cost.
- Let the server decide prompt size. Trim history and cap output on every call.
- Lock down the function that writes usage, or users can reset their own counts.
- In Flutter, prevent double sends and show the limit as a normal state.
Per-user limits are one piece of keeping an assistant affordable. For the other monthly lines, from hosting to the time someone spends maintaining the agent, this rundown of AI agent costs per month is worth reading alongside this.
Top comments (3)
Good write-up, and thank you for listing the limitations and saying it hasn't run against a live project. Most posts leave that out.
On the check-then-charge overshoot: did you consider reserving the worst case up front (the max output tokens, weighted) and refunding the difference after the call? It costs one more write, but parallel requests can no longer all pass the check on the same balance.
A different angle from my own app: I limit the AI feature by a unit the user can see (documents) rather than by tokens. It tracks cost less precisely, but nobody has to learn what a weighted token is. Do your users see the allowance anywhere in the UI, and in what unit?
That's a great point! We keep the allowance user-friendly by presenting it in terms of documents rather than exposing token counts. The goal is to make usage easy to understand without adding technical complexity. Do you find users respond better to a fixed document limit or a flexible monthly allowance?
Showing it as documents makes sense, nobody thinks in tokens. It's too early for me to say which one users prefer. My guess is a monthly allowance feels less punishing, because one busy day doesn't lock you out. Either way, the reserve-and-refund idea can still run underneath. The user only ever sees documents.