Metering
Meter every model call on the tenant's usage meters through registerTelemetry, and reconcile each tenant's AI Gateway spend nightly.
meterTelemetry from better-supabase/ai-sdk is an AI SDK telemetry
integration that records the tokens of every model call on the
usage block. Register it once, and calls made
anywhere in the app (the assistant, agents, a job, a batch) are metered on
the tenant without passing usage around.
import { registerTelemetry } from "ai";
import { meterTelemetry } from "better-supabase/ai-sdk";
import { serviceUsage } from "@/lib/usage";
export function register() {
registerTelemetry(meterTelemetry({ usage: serviceUsage }));
}| Call | Meter | Quantity |
|---|---|---|
| each language model call | ai.input_tokens | input tokens |
| each language model call | ai.output_tokens | output tokens |
embed, embedMany | ai.embedding_tokens | embedding tokens |
rerank | ai.rerank_calls | 1 |
An agent with several steps records each step. The tenant comes from the
org: tag that gatewayOptions puts in
providerOptions.gateway.tags, then from runtimeContext.organizationId;
a call without either isn't metered. Pass tenant(event) to read it from
somewhere else, and meters to rename the meters.
registerTelemetry takes several integrations, and each gets every event.
Register meterTelemetry next to an OpenTelemetry integration, such as
@ai-sdk/otel, to meter usage and export traces from the same calls. Set
telemetry: { functionId } on a call to tell its spans apart; metering
doesn't need it:
import { OpenTelemetry } from "@ai-sdk/otel";
import { registerTelemetry } from "ai";
import { meterTelemetry } from "better-supabase/ai-sdk";
export function register() {
registerTelemetry(
meterTelemetry({ usage: serviceUsage }),
new OpenTelemetry(),
);
}The spans from @ai-sdk/otel carry the OpenTelemetry GenAI attributes, such
as gen_ai.usage.input_tokens, so any backend that reads those conventions
shows them without extra code. They use the same tracer provider as
better-supabase/otel, so a model call and the
repository queries it triggers land in one trace. better-supabase doesn't add
its own gen_ai.* attributes; the metering above stays the source for
per-tenant usage.
A call that passes telemetry: { integrations } uses those instead of the
registered ones, so list meterTelemetry there too or the call isn't
metered.
Without an idempotencyKey option, each row carries the key
ai-call:<callId>:<responseId>, so a retried event is counted once. The integration keeps at most 1,000 calls in
flight and releases a call on onEnd, onAbort and onError, so an aborted
stream leaves nothing behind. Don't also record the same tokens with usageEntries, or
they count twice. A failed write goes to onError; it never fails the
model call.
Source, idempotency key, actor and metadata
Each row's source is ai:<functionId> (for example
ai:inbox.suggest-actions) when the call sets telemetry: { functionId },
and ai:telemetry otherwise. The usage history and usage.breakdown group
by it, so a background run shows up under its own name. Pass source as a
string or a function of the start event to choose another.
A background run that can be retried needs a key per unit of work, not per
call. idempotencyKey(event) returns the base of the key, such as one key per
source message, and each row adds its own suffix, so the steps of one agent
run don't collide. actor(event) names the user a row is recorded for (it
defaults to runtimeContext.userId), and metadata(event) keeps more detail
with the history row:
meterTelemetry({
usage: serviceUsage,
idempotencyKey: (event) =>
isRecord(event.runtimeContext)
? `message:${String(event.runtimeContext["messageId"])}`
: undefined,
metadata: (event) => ({ functionId: event.functionId }),
});Refusing calls before they run
rateLimitMiddleware from better-supabase/ai-sdk counts each model call
against a rate limit and throws
before the model runs when the limit is used up. Wrap the model with it:
import { wrapLanguageModel } from "ai";
import { rateLimitMiddleware } from "better-supabase/ai-sdk";
export const model = (organizationId: string, userId: string) =>
wrapLanguageModel({
model: "openai/gpt-5.4",
middleware: rateLimitMiddleware({
rateLimit: serviceRateLimit,
scope: "ai:calls",
key: userId,
organizationId,
}),
});A refused call throws a DbException whose error is rate_limited with the
code AI_RATE_LIMITED and retryAfter in seconds. aiErrorToDbError returns
it unchanged, so a route answers it with the same 429 as any other limit.
key is a string or a function of the call that returns undefined to skip
the limit. When the limit itself can't be checked, the call fails with that
database error; set failOpen: true to let it through instead.
Nightly spend reconciliation
The per-call cost in the usage block comes from each response. The AI
Gateway's spend report is the figure you are billed, and the two drift when
a response arrives without a cost or a call fails after it was charged.
spendReconciliation is a job handler that reads yesterday's report grouped
by tag and records each tenant's cost, in micro-dollars, on its own meter:
import { gateway } from "ai";
import { spendReconciliation } from "better-supabase/ai-sdk";
export const handlers = {
"ai.spend_reconcile": spendReconciliation({
gateway,
usage: serviceUsage,
credentialType: "system",
}),
};Schedule it once a day after midnight UTC. The payload can name a day
(YYYY-MM-DD) to reconcile another one. Each tenant's day is recorded once
on ai.gateway_cost (set meter to change it), so running the job twice
changes nothing. credentialType: "system" counts only the spend the app
pays, leaving out calls made with a tenant's own key. Compare
ai.gateway_cost with the per-call cost meter to find the drift.
Last updated on
Tenant keys and sandboxes
Send each tenant's own provider keys to the AI Gateway as BYOK, keep the sandbox registry current while a sandbox runs, and run model-written code in it.
Gateway per organization
Give each organization its own AI Gateway policy and budget, record the full cost of every call, and attribute virtual model spend to organizations.