@octabits-io/metering
Usage metered at the source and priced at read time. A model call books the tokens the vendor reported; a paid HTTP API books its calls by host, in the units the vendor bills; both land on the feature, the run and the paying account that caused them, through an ambient context a run carries. Prices are a table an operator corrects after the fact — a missing price still counts, and a price set later reprices every row that came before, because nothing is multiplied until the report reads it. A monthly budget alerts at thresholds, once each, and can stop paid calls while free ones keep running. The controlling report puts cost beside revenue per customer.
npm i @octabits-io/metering zod # + drizzle-orm if you declare the table with ./drizzle
import { createBatchedSink, createMetering, defineMeteredHosts } from '@octabits-io/metering';
import { asyncLocalUsageContext } from '@octabits-io/metering/node';
import { createPostgresCostEventStore } from '@octabits-io/metering/postgres';
// Once, at start-up — the controlling module. Without this, nothing is recorded.
export const metering = createMetering({ context: asyncLocalUsageContext() });
metering.install(createBatchedSink(createPostgresCostEventStore({ db: pool, scope: { column: 'org_id' } })));
export const hosts = defineMeteredHosts([
{ service: 'serp', host: /(^|\.)serpapi\.com$/, billing: 'paid' },
{ service: 'youtube', host: 'www.googleapis.com', path: /^\/youtube\//, billing: 'quota', endpoints: [{ path: /\/search$/, units: 100 }] },
{ service: 'wikipedia', host: /(^|\.)wikipedia\.org$/, billing: 'free' },
]);
// Around a run: every booking inside lands on it, however deep.
await metering.withUsage({ feature: 'research', scopeKey: orgId, runId }, async () => {
await researchStep(); // a model call booked by octaflow, three API calls booked by the fetch
});
// At the source — a call site that knows its usage and nothing else:
metering.record({ kind: 'model', service: 'anthropic', model: 'claude-haiku-5-5', inputTokens: 1200, outputTokens: 80 });
@octabits-io/models/octaflow captures tokens per step and enforces a quota of its own; this
package is what sits beside it: the paid APIs around the model, the
attribution to the paying account, the prices as data, the budget as money,
the report. The two meet in one table: createAiWorkflowHooks({ usage: metering }).
| Subpath | Deps | Contents |
|---|---|---|
. |
zod (peer), @octabits-io/result |
the contract (UsageContext, UsageBooking, CostEvent), createMetering (withUsage, record, install), the payload carrier for a queue hop (attachUsageContext, usageContextOf), defineMeteredHosts, the price book (readPricingTable, createPriceBook, the override store), the budget guard (createBudgetGuard, spentFromStore), the batched sink, the metered fetch (createMeteredFetch, checkBudget, bookResponse), the report (costReport, costReportCsv), every row of a query paged (listAllCostEvents, forEachCostEventPage), BudgetExceededError, the in-memory stores |
./ai-sdk |
ai, @ai-sdk/provider (optional peers) |
meterModel — an AI SDK language model that books every call and asks the budget before a paid one |
./node |
node:async_hooks |
asyncLocalUsageContext() — the ambient context on Node |
./postgres |
none | createPostgresCostEventStore over a structural SqlExecutor — pg Pool/Client, PGlite, a wrapper over postgres.js — plus costEventDdl() and costEventGrantsDdl() |
./drizzle |
drizzle-orm (optional peer) |
costEventColumns, the table for drizzle-kit; no Drizzle store — the SQL store is the store |
A boundary lint keeps the root on zod and result, node:async_hooks in
./node, drizzle-orm in ./drizzle and ai in ./ai-sdk; everything but ./node and
./drizzle type-checks with no Node typings.
The rule: meter at the source, price at read time
A call site books what it knows — tokens, a host, units — and never a price. The price is read when the report is built, from the table and the overrides as they stand then. Three things follow:
- A missing price is not a lost row. The usage is in the table; the
report prices it to
null, contributes0to the totals and lists it underpriceMissingwith its tokens and units. An operator adds the price, and the next report has it — for the past rows too. - A correction is an override, not an update. The rows are append-only
for the application role (
costEventGrantsDdl); a wrong price is fixed by setting the right one, with who set it and when. - The budget is a read, not a counter. What the month has cost is the
sum of all its rows, paged, at today’s prices (
spentFromStorewith the book as a function, asked on every read), cached for a few seconds in the guard. There is no running total to drift — and the hard stop is soft by that cache and the sink’s flush (see “The budget”).
When not to use it
You want per-step token totals on the workflow row and a quota for a key
(@octabits-io/models/octaflow has them); you want to bill customers (this is cost, not
revenue — your billing stays the source of what they paid); you want to
trace a request (that is telemetry); or your spend is one vendor with one
invoice and nobody asks which feature or customer caused it.
Attribution: the context a run carries
interface UsageContext {
feature?: string; // 'research', 'import.mapping'
scopeKey?: string | null; // the paying account — your organisation, workspace, customer id; null = the house
runId?: string; // the workflow run, the request
jobId?: string; // the background job
correlationId?: string; // shared with your traces and the disclosure log
}
withUsage(context, fn) runs fn with the context ambient; a nested
withUsage extends the outer one. On Node the carrier is
AsyncLocalStorage (./node), so a booking after any number of awaits, in
any helper, on a timer, lands on the run — and two concurrent runs never
see each other’s. fn also receives the merged context as its argument, so
a runtime without async context passes it explicitly; createStaticUsageContext()
is a one-slot carrier for a single-request runtime and for tests.
A queue hop carries the context in the payload, the way queue carries
the trace: attachUsageContext(payload, metering.current()) on the producer,
metering.withUsage({ ...usageContextOf(job.data), jobId }, run) on the
worker.
A booking’s own context is merged over the ambient one, field by field —
for the call site that knows better (octaflow names the run and the
workflow type; the ambient context adds the paying account).
Booking at the source
A model call, by whatever wraps the model. @octabits-io/models/octaflow does it for
every step when its hooks get a usage sink — createAiWorkflowHooks({ …, usage: metering }); the provider becomes the service, the workflow type
the feature, the workflow id the runId. Outside octaflow:
metering.record({ kind: 'model', service: model.provider, model: model.modelId, inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens });
Or wrap the model once, where it is built (./ai-sdk): every call is booked as it returns, a streamed one on
its finish, a failed one as failed; and with a budget, a paid model is refused before it is asked once
the month is spent and the hard stop is on (BudgetExceededError). A model you run yourself is paid: false
and always passes. The context goes with the wrapper when a call site knows more than the ambient one — the
step a call served, as a correlationId shared with the disclosure log:
import { meterModel } from '@octabits-io/metering/ai-sdk';
const model = meterModel(vendorModel, { metering, budget, paid: true, context: { scopeKey: orgId, runId, feature, correlationId: stepId } });
Wrap it inside the disclosure gate: a call the gate denies never reaches the model and books nothing.
An HTTP API call, by the fetch. Two shapes:
// 1. A fetch that already reports its responses — the guarded fetch of
// @octabits-io/server/outbound/node takes an `onResponse`:
import { bookResponse } from '@octabits-io/metering';
const outbound = createOutboundFetch({ onResponse: bookResponse({ hosts, metering }) });
// 2. A fetch that meters itself — books every known host, refuses a paid one under a spent budget:
import { createMeteredFetch } from '@octabits-io/metering';
const fetch = createMeteredFetch({ hosts, metering, budget, fetch: outbound.fetch });
The host table (defineMeteredHosts) names a service per host — exact or a
pattern — its billing (paid, quota, free), a path to narrow one host
that serves several services, the units a call costs, and per-endpoint units
for a quota API that prices by endpoint (YouTube’s search at 100). A URL the
table does not know books nothing and is never refused.
A failed call is booked too, with failed: true — the metered fetch and
bookResponse set it for a refused or unanswered request, a model wrapper
for a call that errored. The report counts failures per line (failed); the
price book charges a failed API call nothing unless its price says
billsFailed: true, and a failed model call only for the tokens it reports.
Without a sink nothing is recorded. record is a no-op until install
is called, and an invalid booking comes back as a value
({ key: 'invalid_usage' }) — metering never fails the call it meters.
Prices as data
const table = readPricingTable({
currency: 'USD',
models: {
'claude-haiku-5-5': { inputPerMillion: 0.1, outputPerMillion: 0.5, cacheReadPerMillion: 0.01, source: 'https://…/pricing', asOf: '2026-10-01' },
},
apis: {
serp: { perUnit: 0.01, source: 'https://serpapi.com/pricing', asOf: '2026-10-01' },
youtube: { perUnit: 0, source: 'quota', asOf: '2026-10-01', endpoints: { '/search': { perUnit: 0, source: 'quota', asOf: '2026-10-01' } } },
},
});
const book = createPriceBook(table.value, await overrides.list(), { reportCurrency: 'EUR', rates: { USD: 0.92 } });
book.price(row); // micro-units of EUR, or null
The table is plain data — a JSON or YAML file your host parses, validated
by readPricingTable — with a source and an asOf on every row, so a
price can be traced to where it was read. An override
(priceOverrideSchema: the row, setBy, setAt, a note) takes precedence
over the table, row by row; createInMemoryPriceOverrideStore is the
reference, a host keeps them in its settings. Rows are in the table’s
currency unless they say otherwise; one rate per currency converts into the
report currency, and a row in a currency with no rate prices to null.
Amounts are micro-units (1 EUR = 1 000 000) as integers.
A model key is matched against the booking’s model id and against
service/model: the exact key first, then the longest key ending in
* as a prefix. 'claude-sonnet-5-5*' prices the dated ids of that model,
'ollama/*' every local model, 'openrouter/gpt-6-luna' one model behind one
gateway only.
The budget
const budget = createBudgetGuard({
budgetMicros: 500 * 1_000_000, // €500 a month — a setting
spent: spentFromStore(store, () => book()), // the month's rows, priced by the book in force at each read
alertAt: [0.8, 1], // once each, per month
notify: (alert) => mail.admins(`Budget ${alert.month}: ${alert.threshold * 100} %`),
alerts: alertLog, // claim(month, threshold) → true once; in memory by default
hardStop: true, // refuse paid calls once spent; default false
onError: (error, stage) => log.warn('budget', { stage, error }), // what the guard contained
});
const gate = await budget.check({ paid: hosts.isPaid(url) });
if (!gate.ok) return gate; // { key: 'budget_exceeded', budget: { month, spentMicros, budgetMicros } }
Pass the price book as a function: a PriceBook value is the prices of the
moment the guard was built, and an override or a new rate would not count
until it is rebuilt.
The hard stop is soft by a window. A booking reaches the store when the
sink flushes (the batched sink: every second), and the guard sees it once
its cached read is older than cacheMs (default 5 s) or after
invalidate(). Calls in that window pass on the last read, so a burst can
overshoot the budget by what it spends in it. Narrow it with a smaller
cacheMs and budget.invalidate() after each flush; cacheMs: 0 reads the
month on every check.
Each alert once. alerts is a BudgetAlertLog whose one method,
claim(month, threshold), is atomic: true for the one caller that takes
the alert, false for every other — an INSERT … ON CONFLICT DO NOTHING
row, a SET NX key. Two checks crossing a threshold together send it once.
Metering never fails the call it meters, the budget included: a spend
that cannot be read lets the call through on the last read (or none,
spendUnreadable: true on the status), a log or a notify that throws is
contained (a claimed alert that could not be delivered is not sent again),
and onError(error, stage) hears each.
A free or quota service passes always: the budget is about money. The
metered fetch raises the same error as BudgetExceededError (key
budget_exceeded) for a library that takes a fetch; @octabits-io/server
maps the key to 429, and octaflow’s circuit breaker treats it as fatal, so a
run shows one clear notice instead of a failure per step. The budget, the
alert thresholds and the exchange rate are plain options here: a host reads
them from its settings and rebuilds the guard when they change.
The report
const report = costReport({
month: '2026-10',
events: await listAllCostEvents(store, monthRange('2026-10')), // every row, paged — one list() stops at its limit
book,
budgetMicros,
revenue: invoices.map((i) => ({ at: i.paidAt, scopeKey: i.orgId, netMicros: i.netMicros })),
fixedCostsMicros,
});
report.totalMicros; report.forecastMicros; report.budget?.usedRatio;
report.byService; report.byModel; report.byFeature; report.byDay; report.byRun; report.costPerRunMicros;
report.byScope; // per paying account: cost, revenue, margin
report.contributionMarginMicros; // revenue − variable cost − fixed costs
report.priceMissing; // what is unpriced, with its usage
costReportCsv(report); // one section per breakdown, two-place amounts
Pure functions over the rows you hand them: a page renders it, a CLI prints it, a test holds it against a fixture. Admin only — it names customers.
The table
costEventDdl({ scope: { column: 'org_id' }, appRole: 'app' }) creates
cost_event (bigserial id, at, kind, service, model, endpoint,
units, the four token counts, failed, feature, run_id, job_id,
correlation_id) with your scope column nullable, an index on (at, id),
one on (scope, at) and a partial one on run_id, and leaves the
application role SELECT and INSERT only. On Drizzle, declare the table
from costEventColumns and add costEventGrantsDdl({ appRole }) in a
custom migration; the SQL store is the store, hand it drizzleExecutor.
No vendor is added: the package calls nothing. infra/SUBPROCESSORS.md
stays as it is.
From @octabits-io/metering@0.5.0 in the platform repository.