Plenty of SaaS products now have at least one AI feature: a summary, a draft reply, a search that answers in sentences. Each call costs money, and the cost depends on how much text goes in and out. Sooner or later someone asks how to stop one customer from running up the bill for everyone else.
The usual answer is a monthly allowance per customer. The part that goes wrong is enforcing it when requests arrive at the same time. We built a small metering layer in PostgreSQL and hit it with 10 parallel workers, first the naive way and then with reservations. The model call is a stub in this test (it waits 200 ms and reports 900 input and 1,500 output tokens), so the numbers are exact and repeatable. Everything else ran on a real Supabase Postgres 17 database.
The naive version, and what it did
This is the version most apps start with: look up what’s left, call the model if there’s enough, then add the usage.
async function naive() {
const { rows } = await pool.query(`select limit_tokens - used_tokens as left from ai_meter.token_budgets where tenant_id = 'acme'`);
if (rows[0].left < MAX) return false;
const u = await fakeModel();
await pool.query(`update ai_meter.token_budgets set used_tokens = used_tokens + $1 where tenant_id = 'acme'`, [u.input + u.output]);
return true;
}We gave tenant Acme 60,000 tokens for the month and sent 50 requests through 10 workers. Each call uses 2,400 tokens, so 25 calls fit. The naive version let 32 through and recorded 76,800 tokens, 28% over the allowance. Ten requests read the same balance, all decided there was room, and all called the model.

Reserve, then settle

The fix moves the check into the same statement as the charge. Before calling the model, the app reserves the most this call could use. PostgreSQL only applies the update if the reservation still fits, and it handles one update to a row at a time, so ten parallel requests can’t all fit into the same space.
After the model answers, the app settles: it records what was actually used and frees the rest of the reservation. If the call fails, it releases the whole reservation.
Step 1: Two tables
-- One row per tenant per billing month: the allowance and what's been used or reserved.
create table ai_meter.token_budgets (
tenant_id text not null,
period date not null, -- first day of the month
limit_tokens bigint not null,
used_tokens bigint not null default 0,
reserved_tokens bigint not null default 0,
primary key (tenant_id, period),
check (used_tokens + reserved_tokens <= limit_tokens)
);
-- One row per AI request. request_id makes retries harmless.
create table ai_meter.ai_requests (
request_id text primary key,
tenant_id text not null,
period date not null,
feature text not null,
model text not null,
reserved_tokens bigint not null,
input_tokens bigint,
output_tokens bigint,
status text not null default 'reserved' check (status in ('reserved', 'settled', 'released')),
created_at timestamptz not null default now(),
settled_at timestamptz
);Feature and model are on every request because the first question after “who used it?” is always “on what?”. When a customer asks why they hit their limit, you can show them that most of it went on document summaries, not chat.
Step 2: Reserve, settle, release
create function ai_meter.reserve(p_tenant text, p_request text, p_feature text, p_model text, p_max_tokens bigint)
returns boolean language plpgsql as $$
declare
v_period date := date_trunc('month', now())::date;
begin
-- A retry of a request we already know about is not charged twice.
if exists (select 1 from ai_meter.ai_requests where request_id = p_request) then
return true;
end if;
update ai_meter.token_budgets
set reserved_tokens = reserved_tokens + p_max_tokens
where tenant_id = p_tenant and period = v_period
and used_tokens + reserved_tokens + p_max_tokens <= limit_tokens;
if not found then
return false; -- over budget: don't call the model
end if;
insert into ai_meter.ai_requests (request_id, tenant_id, period, feature, model, reserved_tokens)
values (p_request, p_tenant, v_period, p_feature, p_model, p_max_tokens);
return true;
end $$;
create function ai_meter.settle(p_request text, p_input bigint, p_output bigint)
returns void language plpgsql as $$
declare r ai_meter.ai_requests;
begin
update ai_meter.ai_requests
set status = 'settled', input_tokens = p_input, output_tokens = p_output, settled_at = now()
where request_id = p_request and status = 'reserved'
returning * into r;
if not found then return; end if; -- already settled or released: nothing to do
update ai_meter.token_budgets
set reserved_tokens = reserved_tokens - r.reserved_tokens,
used_tokens = used_tokens + least(p_input + p_output, r.reserved_tokens)
where tenant_id = r.tenant_id and period = r.period;
end $$;The where clause on the update is the whole trick. used + reserved + max ≤ limit is checked against the row as it is when the update runs, not as it was when the app last read it. If another request got there first, this one sees the new numbers or gets no row back.
settle() charges the smaller of the actual usage and the reservation. The model shouldn’t exceed the max_tokens you sent it, but if your estimate of the input was off, the overage is capped at what was reserved rather than pushing the tenant past its limit.
Step 3: Call it from the app
async function reserved() {
const id = randomUUID();
const { rows } = await pool.query(`select ai_meter.reserve('acme', $1, 'summarize', 'model-x', $2) as ok`, [id, MAX]);
if (!rows[0].ok) return false;
try {
const u = await fakeModel();
await pool.query(`select ai_meter.settle($1, $2, $3)`, [id, u.input, u.output]);
} catch (e) {
await pool.query(`select ai_meter.release($1)`, [id]);
throw e;
}
return true;
}Same test, same 10 workers: 24 calls allowed, 26 refused, 57,600 tokens used of 60,000, nothing left reserved. The tenant stopped 2,400 tokens short of its limit because the next call might have needed 3,000, and it’s better to refuse that than to go over.
Then the retry test: the same request id reserved twice and settled twice. It was charged 2,400 tokens once. That matters more than it sounds. Job queues retry, users double-click, and HTTP clients resend after a timeout.
What customers should see
A hard stop with no warning is how a limit turns into a support ticket. We usually add three things around the meter:
- A usage bar in the account settings, read from token_budgets, with a breakdown by feature from ai_requests.
- An email to the account owner at 80% of the allowance, sent once per period.
- A clear message when a request is refused, with the date the allowance resets and a link to upgrade.
The allowance itself comes from the customer’s plan. In our multi-tenant SaaS guide the database enforces plan limits on projects; AI allowances work the same way, with the monthly token limit stored on the plan and copied into token_budgets at the start of each period.
Tokens, not dollars
We meter in tokens and keep money out of the usage tables. Providers change prices, and you may switch models for one feature next month. Store tokens per request with the model name, keep a price table with dates for reporting, and work out cost in a view. Your history stays correct when prices change.
If customers buy credits rather than a monthly allowance, the same reserve and settle functions work against a credit balance that doesn’t reset. Only the period column goes away.
What shapes the cost
| Factor | Why it matters |
|---|---|
| Number of AI features | Each one needs its own token estimate and a clear name in the usage records. |
| Billing model | A monthly allowance is simplest. Credit packs, rollovers and overage billing need more rules and a link to Stripe. |
| Streaming responses | Usage arrives at the end of the stream, so settling has to happen after it, including when the user closes the tab. |
| Customer-facing usage screens | The meter is the small part. Usage bars, alerts and upgrade flows usually take longer. |
Mistakes we’d avoid
Sources
Questions we often hear
Does this work with streaming responses?
Yes. Reserve before the stream starts and settle when it ends, using the usage figures the provider sends at the end. Release if the stream errors or the user cancels.
Won’t one budget row per tenant become a bottleneck?
Each reservation is a short update on one row, so it handles a lot of traffic per tenant. If one customer sends hundreds of AI requests a second, give them several budget rows and spread requests across them.
Does it work with any model provider?
Yes. The meter only needs token counts, which OpenAI, Anthropic and Google all return with each response.
Can you add usage limits to our existing product?
Yes. On a free 30-minute call an engineer will look at where your AI calls happen today and how we’d meter them without changing your billing.





