Usage and quotas
Count usage per tenant and meter with idempotent increments, enforce quotas per tenant or plan in RLS and RPCs, and report usage to Stripe meters.
The usage block counts what each tenant uses (API calls, seats, generated
documents) and enforces quotas on it. Counters are kept per tenant, meter and
UTC day, so one meter can have a daily quota for one plan and a monthly one
for another.
better-supabase add usage # adds tenant and access as well| Table | Holds |
|---|---|
usage_counters | value and reported_value per (organization_id, meter, day) |
usage_events | One row per idempotency key, so a retried increment counts once |
usage_quotas | limit and period (day, week, month, year or billing) per tenant or per plan |
Members with usage.read (the default admin role) can read the counters,
the tenant's quotas and the status that current and overview return.
Other members get a forbidden result with the hint USAGE_FORBIDDEN. Recording usage (record, consume and the batch
variants) needs usage.record (also in the default admin role) or the
service role, so a member can't inflate or use up the tenant's quota from
the browser. Only the service role writes quotas.
Quotas
A quota row names either a tenant or a plan. A tenant row overrides the plan
rows. The plan * applies to every tenant; with the
entitlements module installed, any other plan
matches tenants with that entitlement key, and the highest limit wins. When
auth.entitlements.source is a plan catalog, a quota's plan also matches the
tenant's active plan key (better_supabase.tenant_plans(tenant)), so
('pro', 'api_calls', 50000, 'month') applies to every tenant on pro.
insert into better_supabase.usage_quotas (plan, meter, "limit", period) values
('*', 'api_calls', 1000, 'month'),
('pro', 'api_calls', 100000, 'month');
insert into better_supabase.usage_quotas (organization_id, meter, "limit", period)
values ('8d1c...', 'api_calls', 250000, 'month');A null limit is unlimited. It wins over every other plan row, so an
enterprise plan row with a null limit lifts the * limit for those
tenants, and a tenant row with a null limit lifts the plan limits for one
tenant. consume and within_quota always pass for an unlimited meter, and
current returns unlimited: true with no limit or remaining. Unlike a
meter with no quota row at all, the unlimited quota still sets the meter's
period.
insert into better_supabase.usage_quotas (plan, meter, "limit", period)
values ('enterprise', 'api_calls', null, 'month');Setting quotas from code
usage.setQuota and usage.removeQuota write the same rows with a service
transport. Give either organizationId or plan, never both:
await serviceUsage
.setQuota({ meter: "ai.input_tokens", organizationId, limit: 2_000_000 })
.orThrow();
await serviceUsage
.setQuota({
meter: "ai.input_tokens",
plan: "free",
limit: null,
period: "day",
})
.orThrow();
const removed = await serviceUsage
.removeQuota({ meter: "ai.input_tokens", organizationId })
.orThrow();limit: null is unlimited and period defaults to month. removeQuota
resolves to whether a quota existed.
usage.quotas reads the quotas of many organizations and meters in one call,
for an admin list or a billing job. It resolves each organization's plans once
and leaves out the pairs without a quota. It needs a service transport, and
calls usage_quotas_for(tenants, meters), which usage_quota also uses for one
pair:
const quotas = await serviceUsage
.quotas({ organizationIds, meters: ["ai.input_tokens", "seats"] })
.orThrow();
// [{ organizationId, meter: "seats", limit: 10, period: "month" }, ...]Billing periods
Calendar periods reset at the start of the UTC day, week, month or year.
Products billed through Stripe usually reset quotas with the invoice instead,
which starts on the subscription's own day. Give such quotas the period
billing and write a usage_billing_period(tenant) function (in the hooks
schema, public by default) that returns the current window:
create function public.usage_billing_period(tenant uuid)
returns table (starts_at timestamptz, ends_at timestamptz)
language sql stable security definer set search_path = '' as $$
select to_timestamp(s.current_period_start), to_timestamp(s.current_period_end)
from stripe.subscriptions s
join better_supabase.billing_customers c on c.stripe_customer_id = s.customer
where c.organization_id = tenant and s.status in ('active', 'trialing')
order by s.created desc
limit 1
$$;Any source works: a column on your subscriptions table, or a fixed anchor
day. Counters are kept per UTC day, so a window counts the whole days from
starts_at up to the day of ends_at. Without the function, or when it
returns no row, a billing quota falls back to the calendar month.
The function only returns the current window, so a day reported after its
period ended (an overage report that ran late, say) counts in the period that
held it, taking earlier periods to be as long as the current one.
usage_status and current return startsAt and resetsAt for the window,
and retryAfter counts down to its end.
The meter catalog
options.meters lists the meters with a unit, category and label for
display. With it, record_usage and consume_quota refuse other meter names
(USAGE_METER_UNKNOWN), usage_status returns the meter's fields, and
usage.meters() (usage_meters()) reads the catalog for a usage page:
usage: {
options: {
meters: {
"ai.tokens": { unit: "tokens", category: "ai", label: "AI tokens" },
"api.requests": { unit: "requests", category: "api" },
"storage.bytes": { unit: "bytes", category: "storage" },
},
},
},A catalog that changes without a deploy (meters an admin adds, products
from a plan table) can live in a table instead. Point options.meters at it
with table and the column names; unit, category, label and active
are optional, and only rows where active is true are meters:
usage: {
options: {
meters: {
table: "public.meters",
key: "slug", // default key
unit: "unit",
label: "title",
active: "is_active",
},
},
},usage_meters() then reads the table on every call, so a new row is a
meter right away.
Weighted quantities
record and consume take a quantity, so a meter can count something
other than calls. For credits, record the credits a call costs, such as
tokens * creditsPerToken, on a credits meter with a quota in credits;
the counter, the quota and the Stripe report all work on that number. Keep
the raw units on their own meter when you also want to show them.
Quantities, counters and limits are numeric, so a meter can count
fractions, such as GB-hours or credits with decimals, against a fractional
quota:
await usage.record(organizationId, "gb_hours", { quantity: 0.25 });A tenant that the billing
block bills as a Stripe Accounts v2 account is reported under the v1 customer
Stripe links to the account, in the meter's default stripe_customer_id
payload key. Its counters wait (they count as skipped) until the billing
webhook has recorded that customer.
reportUsageToStripe sends the change as it is; when your Stripe meter
expects whole numbers, record in whole units (tokens, cents) instead.
within_quota takes a whole quantity (1 by default), as policies check
rows.
Use within_quota in a policy to stop inserts once the quota is used up:
create policy "projects_insert" on public.projects for insert to authenticated
with check (better_supabase.within_quota(organization_id, 'projects'));Any member of the tenant gets the answer, so the policy works for members
without usage.read. For a caller outside the tenant within_quota returns
false, so nobody can probe another tenant's usage with it.
Recording and consuming
Server code calls the usage instance on db, in the caller's organization. With gen.hooks set, better-supabase gen writes the hooks:
export const { useList: useUsage } = defineDataHooks(
"usage",
(db: AppDb) => db.usage,
);const rows = await db.usage.list({ limit: 50 }).orThrow();"use client";
import { useUsage } from "@/lib/supabase/hooks";
const rows = useUsage({ limit: 50 });consume locks the day's counter, so two concurrent calls can't both take the
last unit. When the quantity doesn't fit, nothing is recorded and the result
is a quota_exceeded DbError with status 429,
the meter, its limit and retryAfter, the seconds until the period
resets. problemResponse turns it into Problem Details with a Retry-After
header. In SQL, consume_quota raises it with SQLSTATE BSQ29, so an RPC
that calls it fails the same way.
canConsume({ organizationId, meter, quantity }) answers whether the quantity fits right now without recording it, for a button that should be disabled when the quota is used up. A meter without a quota always fits. consume stays the call that decides.
Every meter of a tenant
A usage page that shows every meter calls overview instead of current
once per meter. It returns the status of each meter in the catalog, each
meter a quota applies to and each meter the tenant has used, sorted by
meter, in one request (usage_overview(tenant) in SQL). Like current, it
needs usage.read.
const meters = await usage.overview(organizationId).orThrow();
// [{ meter: "api_calls", used: 420, limit: 1000, remaining: 580, unlimited: false, ... }]A usage meter in the browser
useUsageMeter is a registry item: npx shadcn add @better-supabase/use-usage writes hooks/use-usage.ts into the app. The hook
reads the overview through the provider's client and adds fraction (used over the
limit, from 0 to 1, undefined without a limit) and exceeded to each
meter. meters keeps only the meters you name, in that order, and
refresh() reads them again after the app records usage. The same hook
runs in React DOM and React Native.
import { useUsageMeter } from "@/hooks/use-usage";
const { meters } = useUsageMeter({
organizationId,
meters: ["api_calls"],
schema: "api",
});
// meters?.[0]: { meter: "api_calls", used: 420, limit: 1000, fraction: 0.42, exceeded: false, ... }createUsageMeterController from better-supabase/blocks/usage is the
same logic without React. Vue, Svelte and Solid run it with
useBlockController from better-supabase/vue, /svelte and /solid (see
Block controllers),
passing createUsage(...) as client. The usage meter recipe shows it in
the Next.js and Expo examples.
<script setup lang="ts">
import { useBlockController, useSupabase } from "better-supabase/vue";
import {
createUsage,
createUsageMeterController,
rpcTransport,
} from "better-supabase/blocks/usage";
const supabase = useSupabase();
const { state } = useBlockController(createUsageMeterController, {
client: createUsage({ transport: rpcTransport(supabase) }),
organizationId: "org-id",
});
</script>
<template>
<p v-for="meter in state.meters" :key="meter.meter">
{{ meter.meter }}: {{ meter.used }} of {{ meter.limit }}
</p>
</template><script lang="ts">
import { betterSupabase, useBlockController } from "better-supabase/svelte";
import {
createUsage,
createUsageMeterController,
rpcTransport,
} from "better-supabase/blocks/usage";
const { supabase } = betterSupabase();
const usage = useBlockController(createUsageMeterController, {
client: createUsage({ transport: rpcTransport(supabase) }),
organizationId: "org-id",
});
</script>
{#each $usage.meters ?? [] as meter}<p>{meter.meter}: {meter.used}</p>{/each}import { useBlockController, useSupabase } from "better-supabase/solid";
import {
createUsage,
createUsageMeterController,
rpcTransport,
} from "better-supabase/blocks/usage";
export function UsageMeter() {
const supabase = useSupabase();
const { state } = useBlockController(createUsageMeterController, {
client: createUsage({ transport: rpcTransport(supabase) }),
organizationId: "org-id",
});
return <p>{state().meters?.length ?? 0} meters</p>;
}Several meters at once
recordMany and consumeMany record several meters in one transaction, all
or none, such as the input and output tokens of one model call.
consumeMany checks each meter's quota first; when one doesn't fit, nothing
is recorded and the result is quota_exceeded. The idempotency key covers
the batch, and source, metadata and actor apply to every entry:
await usage
.consumeMany(
organizationId,
[
{ meter: "input_tokens", quantity: inputTokens },
{ meter: "output_tokens", quantity: outputTokens },
],
{ idempotencyKey: requestId, source: "feature:chat" },
)
.orThrow();
// { recorded: true, today: { input_tokens: 1200, ... }, used: { input_tokens: 48000, ... } }record, consume and the batches return today, the UTC day's usage, and
used, the usage in the quota's current period (the month without a quota),
the same number current returns.
In SQL, record_usage_batch(tenant, entries, idempotency_key, check) takes
entries as a JSON array of { meter, quantity }.
Distinct and computed meters
A meter is a counter unless options.meters gives it a kind. Inline
catalogs (not { table } catalogs) accept two more:
distinctcounts each subject once per period, for active users or active projects. Callusage.track(tenant, "mau", subject). The first sight in the period adds one unit, repeats change nothing.computedis a gauge a query reports, for storage bytes or seat counts.queryis one select of(tenant, value)rows.usage.refresh()(or the hourly pg_cron job the migration schedules) sets today's counter so the period's total equals the value.
blocks: {
usage: {
options: {
meters: {
mau: { kind: "distinct", period: "month", label: "Active users" },
storage: {
kind: "computed",
unit: "bytes",
query: "select organization_id, sum(size) from app.files group by 1",
},
},
},
},
}Both kinds write the counters table, so quotas, current, overview and
reportUsageToStripe treat them like any counter. The query runs as the
function owner and is never returned by usage.meters(). The tenant is
whatever scope the usage module is installed on, so a meter can be
organization-level or, with a platform-level tenant, environment-level: the
query decides which ids it returns.
Usage history
A usage page shows who and what used a meter. Set
blocks.usage.options.history to true and every recorded quantity also
goes to usage_history, with the user who used it and the source and
metadata you pass:
await usage.consume(organizationId, "tokens", {
quantity: tokens,
source: "feature:summary",
metadata: { documentId },
});
const entries = await usage
.history(organizationId, { meter: "tokens", limit: 50 })
.orThrow();
// [{ id, meter, quantity, actor, source, metadata, recordedAt }], newest first
const byUser = await usage.breakdown(organizationId, "tokens").orThrow();
// [{ actor, source, quantity }] in the quota's current window, largest firstThe actor is the caller's user id. A service transport recording on a user's
behalf passes actor; other callers can't set it. Reading the history and
the breakdown needs usage.read, and history pages with cursor (the
last entry's id). better_supabase.purge_usage_history(older_than, batch)
deletes old entries (400 days by default), and
better_supabase.purge_usage_events(older_than, batch) deletes idempotency
keys (30 days by default). usage.purgeHistory({ olderThan, batch }) and
usage.purgeEvents({ olderThan, batch }) call them from TypeScript, and
usage.purgeJob() runs both as a job handler; schedule them like the other
purges. A retry
that arrives after its key is purged counts again. Without the option, both reads return [].
With options.partitioned as well, a new usage_history table is
partitioned by month on recorded_at (primary key (id, recorded_at)), and
purge_usage_history drops every month past the cutoff before it deletes
rows. Schedule better_supabase.maintain_partitions() once a month. An
existing table stays as it is, and better-supabase doctor reports it as
BS335.
Billing a period
With options.history and the invoices block installed, the usage history can
become an invoice. usage.setPrice stores what one unit of a meter costs in
minor units (an amount is always Money), and how many units each period
includes. usage.billPeriod then rates the history of the UTC days from
periodStart up to, not including, periodEnd into one draft invoice: per
meter, the quantity beyond the included units times the unit amount. A meter
without a price in the currency adds no line.
import { money } from "better-supabase/commerce";
await usage
.setPrice({
meter: "api_calls",
unitAmount: money(5n, "EUR"),
included: 100,
label: "API calls",
})
.orThrow();
const billed = await usage
.billPeriod({
organizationId,
periodStart: Temporal.PlainDate.from("2026-10-01"),
periodEnd: Temporal.PlainDate.from("2026-11-01"),
})
.orThrow();
// { invoiceId, created: true, lines: 1 }A period bills once per tenant: billing it again returns the first invoice with
created: false, and a period with nothing to bill returns invoiceId: undefined. Both functions need a service transport. Issue the draft with
invoices.issue; the example app does this in
apps/examples/nextjs/src/features/billing/usage-billing-actions.ts.
Reporting to Stripe
reportUsageToStripe sends the usage not yet reported as
Stripe meter events,
one per counter and change. Run it from a job or a cron route with a
service-role transport:
import {
reportUsageToStripe,
sqlTransport,
} from "better-supabase/blocks/usage";
import { stripeFromKey } from "better-supabase/stripe";
const stripe = stripeFromKey({ secretKey: env.STRIPE_SECRET_KEY });
export async function GET() {
const { reported, skipped } = await reportUsageToStripe({
transport: sqlTransport(postgres),
stripe,
eventName: (meter) => (meter === "api_calls" ? "api_requests" : undefined),
});
return Response.json({ reported, skipped });
}The event identifier is the tenant, meter, day and new total, so a run that
fails between sending and marking sends the same event again and Stripe drops
the duplicate. The Stripe customer comes from tenant_stripe_customer() in
the entitlements module unless you pass customer, which reads it from
anywhere, such as your own customers table:
customer: async (organizationId) =>
(
await db.billingCustomers
.get({ where: { organizationId } }, { optional: true })
.orThrow()
)?.stripeCustomerId,When a plan includes an allowance and Stripe bills only what goes over it,
pass overage: true: in each quota window, usage up to the tenant's quota
is marked reported without an event, and only the units above it are sent.
A meter without a quota sends everything, and a meter with an unlimited quota
sends nothing. unreported_usage returns each
counter's included quota and window_before (the earlier days' usage in
that window) for the calculation; usage that arrives late on an earlier day
is counted with that day.
Counters without a
customer or an event name are skipped and stay unreported. They don't hold up
the rest: once a run meets a meter without an event name or a tenant without
a customer, it asks unreported_usage again with that meter in skip_meters
or that tenant in skip_tenants, so batch still fills with counters it can
send. The stripe
option takes the same sources as in the billing
block: stripeFromKey() in a bundled app, { secretKey } in plain Node, or a
Stripe client of your own.
Functions
| Function | Granted to | Returns |
|---|---|---|
record_usage(tenant, meter, quantity, key, source, metadata, actor) | authenticated, service_role | { recorded, used } |
consume_quota(tenant, meter, quantity, key, source, metadata, actor) | authenticated, service_role | the same, or raises BSQ29 |
within_quota(tenant, meter, quantity) | authenticated, service_role | whether quantity more fits, false outside the tenant |
record_usage_batch(tenant, entries, key, check, source, metadata, actor) | authenticated, service_role | { recorded, used } with used per meter, or raises BSQ29 |
usage_status(tenant, meter) | authenticated, service_role | { meter, used, limit, remaining, unlimited, period, starts_at, resets_at }, plus the catalog fields, for usage.read |
usage_overview(tenant) | authenticated, service_role | usage_status of every meter of the tenant, by meter, for usage.read |
usage_meters() | everyone | the meter catalog |
usage_history(tenant, meter, max_rows, before_id) | authenticated, service_role | the history entries, for usage.read |
usage_breakdown(tenant, meter) | authenticated, service_role | [{ actor, source, quantity }] in the current window |
set_usage_quota(tenant, plan, meter, quota_limit, period) | service_role | nothing; sets the quota of a tenant or a plan |
delete_usage_quota(tenant, plan, meter) | service_role | whether the quota existed |
set_usage_price(meter, currency, unit_amount, included, label) | service_role | the price, with options.history and invoices |
bill_usage_period(tenant, period_start, period_end, currency, attrs) | service_role | { invoice_id, created, lines }, with options.history and invoices |
usage_window(tenant, period) | service_role | the current window's starts_at and ends_at |
unreported_usage(max_rows, skip_meters, skip_tenants) | service_role | counters with value > reported_value |
mark_usage_reported(tenant, meter, day, value) | service_role | whether the counter exists |
Plan limits and meters declared by blocks
A block manifest can declare a limits entry (a method that must fit a quota
before it runs) and a meters entry (a method that records usage after it
succeeds). With createBlocks({ metering: true }) and the usage block in the
set, createBlocks applies them to the blocks' methods. Without the option, or
without usage, nothing is applied, so installing usage never starts counting
by itself.
const blocks = createBlocks(
{ transport, metering: true },
{ organizations: organizationsBlock, usage: usageBlock },
);
await blocks.organizations.invite({ organizationId, email, role: "member" });organizations.invite declares limits: { invite: { meter: "seats" } }. When
the organization's quota on seats (set per plan with setQuota, so the plan
the billing and entitlements blocks resolve decides the limit) is used up,
the call returns a quota_exceeded error with the meter and limit before
it reaches the database. api-keys.create declares both a limit and a meter on
api_keys_created, so each key counts against the plan's quota.
A declaration reads the organization from organizationId on the method's
first argument (tenant names another property); a call without one isn't
checked or counted. The check uses canConsume, so it answers right now and
two concurrent calls can both pass; use consume where that matters. Set
seats as a computed meter so it counts members rather than invites.
A limit is a gate: it can refuse a call, which an event handler or sink never
can. A meter is not: when recording fails, the logger gets the error and the
caller still gets the call's result. Declared checks run before your own
hooks, so a before hook can't skip a plan limit.
Every block option that limits use is named quota and takes
{ meter, quantity? } (blocks.drive.options.quota). A per-row rateLimit,
as on an API key, is data, not an option. A quota and a rate limit return
different codes: quota_exceeded for a used-up quota or plan limit and
rate_limited for a request rate, both with status 429 and retryAfter.
Hooks
createUsage takes hooks around its methods, such as a rule before
consume that returns a DbError to refuse the call; see
extending blocks.
Without the client
db.usage is this client. Code that does not go through bsb.db() builds it with a transport and an organization id:
import { createUsage, sqlTransport } from "better-supabase/blocks/usage";
const usage = createUsage({ transport: sqlTransport(postgres.asUser(claims)) });
// Counts the call and fails when it would go over the quota.
const consumed = await usage.consume(organizationId, "documents", {
idempotencyKey: requestId,
});
if (!consumed.ok) return problemResponse(consumed.error);
await usage.record(organizationId, "api_calls"); // metering only, no check
const { used, limit, remaining, resetsAt } = await usage
.current({ organizationId, meter: "documents" })
.orThrow();Last updated on