Production readiness
Unexpected Supabase or AI bill: finding what grows with every user
A usage bill grows when something in the app runs once per user, per screen or per minute, so twice the users means twice the cost. Start on the usage pages: Supabase's organization Usage page shows which line item grew, and OpenAI's usage dashboard can be filtered by project, API key and model. Then find the feature behind it with a few read-only SQL queries and the browser's Network tab, and fix it: a spending limit first, then polling, queries that return too much, Realtime without filters, and AI calls without a cap on tokens and requests.
What you are seeing
Usage-based costs usually show up as one of these:
- The Supabase invoice has overage lines you did not expect, usually Egress, Monthly Active Users, Function Invocations, Realtime Messages or Storage Size. Supabase charges these per unit above your plan's quota (Billing on Supabase).
- On the Free plan or with the Spend Cap on, you get an email to the billing address about exceeding a quota and a grace period, instead of a bill (Egress).
- The OpenAI bill or usage graph grew much faster than your user count, or AI requests started failing with
429and the codeproject_spend_limit_exceededororganization_spend_limit_exceededbecause a hard limit was reached (OpenAI spend limits). - On Lovable Cloud, run credits drain faster than before. When they run out, Lovable says AI features in the deployed app stop working and apps that rely on Cloud can pause (Lovable: usage and costs).
- The bill grows even on days with few new users. That points to something that runs on its own (a timer in the app, a scheduled job, an open screen) rather than to new customers.
How to check it yourself
Check your own project only. Everything below only reads. The SQL runs in the Supabase dashboard under SQL Editor. Prices and quotas quoted on this page were checked against Supabase, OpenAI and Lovable docs on 2026-11-21; they change, so compare them with your own invoice and the linked pages.
1. Find the line item that grew
- Open the organization's Usage page in Supabase (
https://supabase.com/dashboard/org/_/usage). It shows all projects by default; pick one in the dropdown and choose the time period. Hovering a day in Total Egress breaks it down by service: Database, Auth, Storage, Edge Functions, Realtime (Egress). - Open the organization's billing page. The Upcoming Invoice section shows what you have spent so far and an estimate for the whole cycle (Cost control).
- If you have more than one project, look at Compute Hours as well. Each project is billed for compute by the hour, paid plans get 10 USD of compute credits per month in total, and compute is not covered by the Spend Cap (Compute). Forgotten test projects and preview branches add up here.
- OpenAI: open the usage dashboard, use Filters to narrow by API key and model, and Group by Project or Model. Data is shown in UTC and the most recent usage can take a while to appear (Reviewing API usage and costs).
- Lovable Cloud: More > Usage, filtered to Run credits, splits Cloud from AI gateway usage. Lovable also offers an Optimize your usage button for owners and admins; it appears once a project has used more than 5 run credits in the last 7 days (Lovable: usage and costs).
What each Supabase line item counts, and what usually drives it (quotas from the linked pages, checked 2026-11-21):
- Egress: data sent from Supabase to clients - rows returned by the API, file downloads, function responses, Realtime events. Pro and Team include 250 GB uncached and 250 GB cached per month, then 0.09 USD per GB uncached and 0.03 USD per GB cached; Free has 5 GB of each (Egress). Driven by how much each request returns times how often it runs.
- Monthly Active Users: distinct users who sign in or refresh their token in the billing cycle, each counted once. Free includes 50,000, Pro and Team 100,000, then 0.00325 USD per MAU (Monthly Active Users). Driven by real users, but also by fake or throwaway accounts.
- Edge Function invocations: every call is billed whatever the status code; CORS preflight (OPTIONS) requests are not. Free includes 500,000, Pro and Team 2 million, then 2 USD per million, rounded up to whole millions (Edge Function invocations).
- Realtime messages: a database change counts once per client listening to it, so one change heard by five clients is five messages. Free includes 2 million, Pro and Team 5 million, then 2.50 USD per million (Realtime messages). Realtime peak connections are billed separately on the highest number of concurrent connections (Realtime peak connections).
- Storage size: the average size of stored files over the cycle. Free includes 1 GB, Pro and Team 100 GB, then 0.0213 USD per GB (Storage size).
- Disk size (paid plans): you pay for the provisioned disk, with 8 GB included on Pro and Team for the default disk type (Disk size). The disk grows automatically when the database gets close to full and does not shrink during normal operation (Database size), so a one-off import can keep costing you after you delete it.
2. Watch what one open screen does
- Open your live app in Chrome, sign in as a test user, press F12 (Cmd+Option+I on a Mac) and go to the Network tab.
- Type
supabase.co(or your custom API domain) in the filter box and open the screen your users spend most time on. Then do nothing for two minutes. - If new requests keep appearing while you do nothing, the app is polling: it asks the server again on a timer. Multiply what you see per minute by your users and the minutes they keep the app open.
- Click the largest requests and look at the Size column and the Response tab. A list screen that downloads hundreds of rows, or columns the screen never shows, is egress you pay for on every visit.
- Requests to
/functions/v1/are Edge Function invocations. A screen that calls a function on every keystroke or every render shows up here as a burst of calls. - Switch the filter to WS (WebSocket) to see Realtime connections. Several connections from one tab, or one more each time you change screens, means channels are opened and never closed.
3. Find the queries that run most often and return the most rows
Supabase's egress guide points to Advisors > Query performance, sorted by most frequent, which shows how often each query runs and how many rows it returns on average (Egress). The same data comes from the pg_stat_statements extension. If the query below fails because the view does not exist, enable the extension under Database > Extensions (pg_stat_statements).
select
calls,
rows,
round(rows::numeric / nullif(calls, 0), 1) as rows_per_call,
round(total_exec_time::numeric) as total_ms,
left(query, 150) as query
from extensions.pg_stat_statements
order by calls desc
limit 20;calls is how many times a statement ran and rows the total rows it returned or changed (PostgreSQL pg_stat_statements). Run it again with order by rows desc to find the queries that move the most data. The numbers add up since statistics were last reset, so run it twice a day apart and compare.A query near the top by calls that your app should run once per visit is a sign of polling or of a component that reloads on every render. A query with a high rows_per_call on a screen that only shows a few items is downloading more than it needs.
4. See which tables and buckets take the space
select
c.relname as table_name,
pg_size_pretty(pg_total_relation_size(c.oid)) as total_size,
c.reltuples::bigint as estimated_rows
from pg_class c
join pg_namespace n on n.oid = c.relnamespace
where n.nspname = 'public'
and c.relkind = 'r'
order by pg_total_relation_size(c.oid) desc
limit 20;pg_total_relation_size includes indexes and TOAST data (PostgreSQL admin functions). estimated_rows is the planner's estimate; -1 means the table has not been analyzed yet (pg_class). A log, event or chat table at the top that grows with every action is a candidate for cleanup.For Storage, Supabase's own query lists buckets by total size (Storage size). This version casts to bigint so files over 2 GB do not break it:
select
bucket_id,
count(*) as files,
(sum((metadata->>'size')::bigint) / 1048576.0)::numeric(12, 2) as total_size_mb
from storage.objects
group by bucket_id
order by total_size_mb desc nulls last;5. Check which tables send Realtime events
Postgres Changes only fires for tables in the supabase_realtime publication (Postgres Changes). List them:
select schemaname, tablename
from pg_publication_tables
where pubname = 'supabase_realtime'
order by schemaname, tablename;6. Compare MAU with the users you know about
select
count(*) as all_accounts,
count(*) filter (where last_sign_in_at > now() - interval '30 days') as signed_in_last_30_days,
count(*) filter (where is_anonymous and created_at > now() - interval '30 days') as anonymous_created_last_30_days,
count(*) filter (where created_at > now() - interval '30 days' and last_sign_in_at is null) as new_never_signed_in
from auth.users;last_sign_in_at, so the dashboard figure can be higher than this. A large anonymous or never-signed-in group is worth a look: see the guide on open sign-up linked at the bottom.7. Search the code for things that run on a timer or per render
If the project is synced to GitHub, clone it and run this from the project folder:
grep -rnE "setInterval|refetchInterval|postgres_changes|\.channel\(|\.select\(\)|\.select\(['\"]\*|responses\.create|chat\.completions\.create|functions\.invoke" \
--include='*.ts' --include='*.tsx' --include='*.js' --include='*.jsx' \
--exclude-dir=node_modules --exclude-dir=.git ..select() with no columns and .select('*') return every column. A refetchInterval or setInterval that calls Supabase or a function is polling. An AI call inside a component that re-renders, or one per keystroke, multiplies your AI bill.Why it happens
Usage pricing charges for work done, and an app built quickly tends to do more work per user than it needs to. The cost of a feature is roughly: how much one action costs, times how often it runs, times how many users have the screen open. The first two are invisible while you test alone, and they only show on the bill once there are users.
- Polling: a screen reloads its data every few seconds to look "live". Each reload is a request, returned rows count as egress, and if it calls an Edge Function, each call is an invocation. With TanStack Query,
refetchIntervalkeeps refetching at that frequency; it pauses in background tabs only becauserefetchIntervalInBackgrounddefaults tofalse(useQuery reference). A plainsetIntervaldoes not pause at all. - Queries that return too much:
select('*')without a limit returns every column of every row the policy allows. Supabase's own advice for egress is to select fewer fields or rows, reduce how often queries run, and not return full rows from inserts and updates when you do not need them (Egress). - Realtime without filters: Supabase counts one message per listening client for each database change (Realtime messages), and Postgres Changes "authorizes every event against each subscriber" (Postgres Changes). A subscription to a whole busy table on every open screen grows with users times changes.
- Channels that are never closed: a component that subscribes when it appears and never removes the channel can leave subscriptions running after the user has left the screen, and each one keeps receiving, and being counted for, every matching change.
- AI calls priced per token: OpenAI prices models per million tokens, with separate prices for input, output and cached input (OpenAI pricing); Lovable's AI gateway deducts credits by model and number of tokens processed (Lovable: usage and costs). A chat that sends the whole conversation with every message pays for that history again on every turn, and an answer without an output limit can be as long as the model chooses.
- No limit per user: if any signed-in user (or a bot account) can call the AI feature as often as they like, one user can produce most of the bill.
- Things that stay after you stop using them: extra projects keep billing compute by the hour (Compute), and a disk that grew during an import does not shrink by itself (Database size).
How to fix it
1. Put a ceiling on spending first
- Supabase (Pro plan): check the Spend Cap under Cost Control on the organization's billing page. With it on, usage of the covered items (egress, MAU, function invocations, Realtime, storage, disk size and a few others) is blocked above the quota until the next cycle instead of billed. It does not cover compute, read replicas, custom domains, IPv4, point-in-time recovery or extra disk IOPS and throughput. Supabase also says the Spend Cap does not send notifications when certain costs are reached, so with the cap off, watch the Usage page yourself (Cost control).
- Know the trade-off: with the cap on, a feature can stop working for your users when a quota runs out, and Supabase may restrict services if you keep exceeding quotas under its Fair Use Policy (Cost control). The cap is a safety net while you fix the cause, not the fix.
- OpenAI: in Project settings > Limits, set a spend limit and turn on Enforce a hard limit. A spend alert alone only notifies you and does not stop traffic. Enforcement is not instantaneous, so spend can slightly exceed the limit (OpenAI spend limits).
- Lovable: owners and admins can set a monthly spend limit on auto top-up; per-member credit limits only apply to build credits, not to Cloud or AI usage (Lovable: usage and costs).
2. Stop polling, or slow it down and pause it when nobody looks
Ask whether the screen really needs fresh data every few seconds. Often refreshing when the user opens the screen or comes back to the tab is enough. TanStack Query does the latter by default with refetchOnWindowFocus (useQuery reference). If you do need a timer, make the interval long and keep it off in background tabs:
const { data, error } = useQuery({
queryKey: ["orders", userId],
queryFn: async () => {
const { data, error } = await supabase
.from("orders")
.select("id, status, total, created_at")
.order("created_at", { ascending: false })
.range(0, 19);
if (error) throw error;
return data;
},
staleTime: 60_000, // treat data as fresh for a minute
refetchInterval: 60_000, // was 3_000 - pick what the screen actually needs
refetchIntervalInBackground: false, // the default, written out so nobody flips it
});A plain setInterval should at least skip work when the tab is hidden and stop when the component goes away:
useEffect(() => {
const tick = () => {
if (document.visibilityState === "visible") {
void loadOrders();
}
};
const id = setInterval(tick, 60_000);
return () => clearInterval(id);
}, [loadOrders]);3. Return only the columns and rows the screen shows
- Replace
select('*')andselect()with the columns the screen uses, as in the example above. Large text, JSON or base64 image columns are the expensive ones to send by accident. - Page long lists with
.range(from, to); both values are 0-based and inclusive, so.range(0, 19)returns the first 20 rows (range). - For inserts, supabase-js does not return the inserted rows unless you chain
.select()(insert). Remove.select()after inserts and updates when the screen does not use the result, or select only theid. - Images: store them in Storage rather than as base64 in a table column, and serve smaller versions to list screens. Supabase's storage-size page also suggests limiting upload size per bucket and deleting files nobody uses (Storage size).
4. Filter Realtime subscriptions and close them
Subscribe to the rows the screen needs, not to the whole table, and remove the channel when the screen closes. Postgres Changes supports filters such as eq on a column (Postgres Changes), and removeChannel unsubscribes and tears the channel down (removeChannel):
useEffect(() => {
const channel = supabase
.channel(`room-${roomId}`)
.on(
"postgres_changes",
{
event: "INSERT",
schema: "public",
table: "messages",
filter: `room_id=eq.${roomId}`,
},
(payload) => addMessage(payload.new),
)
.subscribe();
return () => {
void supabase.removeChannel(channel);
};
}, [roomId]);INSERT only if that is all the screen reacts to, instead of * for every event type.Take tables nobody needs live updates for out of the publication: in the dashboard's Publications settings, under supabase_realtime, switch the table off (Postgres Changes). The SQL equivalent (ALTER PUBLICATION):
alter publication supabase_realtime drop table public.activity_log;public.activity_log with your table. Check first that no screen depends on live updates from it.If a server or Edge Function only sends messages, Supabase recommends the Broadcast REST API instead of subscribing, because every subscribed client, server workers included, is counted (Realtime messages, Realtime peak connections).
5. Record what each AI call costs, per user and per feature
You cannot fix what you cannot attribute. OpenAI's dashboard shows usage per project, key and model, but not per user of your app. A small log table fills that gap. Run this in the SQL Editor or put it in a migration:
create table public.ai_calls (
id uuid primary key default gen_random_uuid(),
user_id uuid not null references auth.users (id) on delete cascade,
feature text not null,
model text not null,
input_tokens integer not null,
output_tokens integer not null,
created_at timestamptz not null default now()
);
create index ai_calls_created_at_idx on public.ai_calls (created_at);
alter table public.ai_calls enable row level security;
-- No policies on purpose: only server code using the secret key writes or reads this table.
revoke all on table public.ai_calls from anon, authenticated;
grant select, insert, delete on table public.ai_calls to service_role;Then, in the Edge Function that calls OpenAI (see the guide on moving API keys to Edge Functions, linked at the bottom, for the full function with sign-in check and a daily request limit), cap the answer length, send only recent history, and log the token counts the response returns. max_output_tokens is an upper bound on generated tokens, reasoning tokens included (Responses API):
const MAX_OUTPUT_TOKENS = 800; // pick what your feature needs
const MAX_HISTORY_MESSAGES = 10;
type ChatMessage = { role: "user" | "assistant"; content: string };
// history comes from the request and was validated before this point
const recent: ChatMessage[] = history.slice(-MAX_HISTORY_MESSAGES);
const response = await openai.responses.create({
model: MODEL,
input: recent,
max_output_tokens: MAX_OUTPUT_TOKENS,
});
if (response.usage) {
const { error: logError } = await ctx.supabaseAdmin.from("ai_calls").insert({
user_id: userId,
feature: "chat",
model: MODEL,
input_tokens: response.usage.input_tokens,
output_tokens: response.usage.output_tokens,
});
if (logError) {
console.error("ai-chat: could not log usage", { userId, message: logError.message });
}
}
return Response.json({ text: response.output_text });After a few days, this shows who and what drives the AI bill:
select
user_id,
feature,
count(*) as calls,
sum(input_tokens) as input_tokens,
sum(output_tokens) as output_tokens
from public.ai_calls
where created_at > now() - interval '7 days'
group by user_id, feature
order by sum(input_tokens) + sum(output_tokens) desc
limit 20;6. Limit AI calls per user
- Add a daily request limit per user in the database, checked inside the Edge Function before the AI call. The guide on moving API keys to Edge Functions has a ready counter (
ai_usagetable andbump_ai_usagefunction). - Set the limit from the user's plan, looked up in the database, never from a value the browser sends.
- Do not call the AI on every keystroke or on page load. Call it when the user presses a button, and disable the button while a request is running.
- If sign-up is open and the AI feature is free to try, every fake account can spend your budget. Close or protect sign-up first.
7. Clean up what keeps billing
- Delete or pause Supabase projects and preview branches you no longer use; Supabase lists deleting unused projects as a way to lower compute cost, and paused projects do not count toward compute usage (Compute).
- Delete old rows from log and event tables you do not need. Deleted rows keep their space until vacuum runs, and the provisioned disk does not shrink in normal operation; Supabase says it right-sizes during a project upgrade (Database size).
- On Lovable Cloud, Lovable suggests pausing the backend when it is not used, right-sizing the database instance, fixing slow queries, removing unused files and reviewing scheduled jobs (Lovable: usage and costs).
Verify
- Repeat check step 2: with the screen open and idle for two minutes, the Network tab should show few or no new requests, and the largest responses should be small.
- Repeat check step 3 a day later. The query that topped the
callslist should have dropped down. - Watch the daily figures on the Supabase Usage page and the OpenAI usage dashboard for a week. Daily cost should now follow active users, not the hours screens stay open.
- Trigger your OpenAI hard limit on a test project with a tiny amount, and check that the app shows a clear message instead of breaking.
When to get help
Finding a polling timer or an unfiltered subscription takes an afternoon. A second pair of eyes is worth it when:
- The Usage page shows which line item grew, but nothing in the checks above explains it, for example egress from a source you cannot find in the Network tab.
- The cost comes from users you cannot identify: bot sign-ups, a leaked key, or an endpoint that can be called without signing in.
- Fixing it means changing how a core feature works, such as replacing polling with Realtime in a chat, or redesigning the data model behind a feed.
- You need to know what the app will cost at ten times today's users before you launch a campaign or sign a customer.
Sources
Primary documentation this guide was checked against. Platforms change - if something here no longer matches, the source wins.
- Manage your usageSupabase docs
- EgressSupabase docs
- Monthly Active UsersSupabase docs
- Edge Function invocationsSupabase docs
- Realtime messagesSupabase docs
- Realtime peak connectionsSupabase docs
- ComputeSupabase docs
- Disk sizeSupabase docs
- Storage sizeSupabase docs
- Database sizeSupabase docs
- Control your costs (Spend Cap)Supabase docs
- Billing on SupabaseSupabase docs
- pg_stat_statementsSupabase docs
- Postgres ChangesSupabase docs
- JavaScript: range()Supabase docs
- JavaScript: insert()Supabase docs
- JavaScript: removeChannel()Supabase docs
- pg_stat_statementsPostgreSQL docs
- System administration functionsPostgreSQL docs
- pg_classPostgreSQL docs
- ALTER PUBLICATIONPostgreSQL docs
- useQuery referenceTanStack Query docs
- Spend limitsOpenAI docs
- Reviewing API usage and costsOpenAI Help Center
- PricingOpenAI docs
- Create a model responseOpenAI API reference
- Usage and costsLovable docs
Frequently asked questions
- Which Supabase usage items can grow without limit on a paid plan?
- On Pro with the Spend Cap off, and on Team, usage above the quota is billed per unit: egress, monthly active users, Edge Function invocations, Realtime messages and peak connections, storage and disk size among others. Compute is billed per project per hour and is never covered by the Spend Cap. The current list is on Supabase's cost control page.
- Will turning on the Spend Cap break my app?
- It can. With the cap on, usage of a covered item is blocked once its quota is used up, until the next billing cycle, so a feature that depends on it can stop working for your users. It prevents a surprise invoice, and it does not fix whatever is using too much.
- Does an OpenAI spend alert stop requests?
- No. OpenAI says spend alerts do not enforce a cap. To stop traffic you need a hard spend limit (Project settings > Limits, Enforce a hard limit), and requests then fail with a 429 error. Enforcement is not instant, so spend can go slightly over the limit.
- Why did egress grow when the number of users did not?
- Egress counts data sent, not users. A screen that polls every few seconds, a list that downloads every row and column, or images served at full size grow egress with the time users keep the app open, even with the same users.
- Is Realtime cheaper than polling?
- Often, because the server only sends something when data changes. But Realtime messages are counted once per listening client for every change, so subscribing every screen to a whole busy table can cost more than a slow poll. Filter subscriptions to the rows a screen needs and close channels you no longer use.
- How do I see which user is behind my AI bill?
- OpenAI's usage dashboard groups by project, API key and model, not by your app's users. Log the token counts each response returns, together with the user id and feature, in a table only your server can write to, and query it by user. The Edge Function must also be the only place that calls the AI.
Related guides
Fixed-price audit
Want someone to check the whole app, not just this?
A review of data security, production readiness and App Store readiness for apps built with AI tools. 900 USD, a ranked list of fixes within 5 business days.