BetterIAM

Billing and spend

Usage meters, rate cards, and spend by person, team, department, project and organization, with budgets, plans and subscriptions, and Stripe-style invoicing.

new@better-iam/server@better-iam/client@better-iam/react@better-iam/clibilling.mdbilling.tsbilling-service.tsbilling-plans.tsbilling.tsoptions.tslifecycle.tsindex.tsx

At the end of every month someone asks what the organization spent, and the next question is always who spent it. The answer depends on things an IAM system already knows: which organization and project a request ran in, who made it, which teams that person belongs to, which department they report into, and which agent acted for them. Billing puts usage and money next to that directory, so finance sees the account's total, a team lead sees their team, a department head sees their department, and everyone sees their own spend, and the numbers add up.

Everything lives in the billing API group (client.billing.* over HTTP) and the in-process runtime iam.billing (recording usage and the scheduled jobs).

Setup

Billing is always on. The billing server option only tunes it: currency, time zone, retention, team attribution, and invoicing.

Configure the instance

Set the billing option, and authentication.sendEmail so budget alerts (spend-alert), spike alerts (spend-anomaly), and payment reminders reach people.

iam.ts
import { betterIam } from 'better-iam';
import { sqliteAdapter } from 'better-iam/adapter-sqlite';
import { renderDeliveryMessage } from 'better-iam/auth/templates';
import { mailer } from './mailer';

export const iam = betterIam({
  database: sqliteAdapter({ filename: './iam.db' }),
  secret: process.env.BETTER_IAM_SECRET!,
  baseURL: process.env.BETTER_IAM_BASE_URL!,
  authentication: {
    sendEmail: async (message) => {
      const rendered = renderDeliveryMessage(message, { appName: 'Acme Cloud' });
      if (rendered) await mailer.send({ to: message.to, ...rendered });
    },
  },
  billing: {
    currency: 'EUR',
    timeZone: 'Europe/Berlin',
    teamAttribution: 'split',
    paymentTermsDays: 30,
    issuer: { name: 'Acme Cloud GmbH', taxId: 'DE123456789', email: 'billing@acme.test' },
  },
});

If you run the billing jobs with the CLI, put the same billing settings in better-iam.config.mjs, which the CLI loads.

Migrate

Meters, prices, usage, budgets, statements, plans, and subscriptions are stored in the shared iam_records table, which the ordinary migration creates.

npx better-iam migrate --config better-iam.config.mjs

Create the client

People read their own spend from the browser, and React apps use useMySpend and useSpendCheck inside IamProvider.

lib/iam-client.ts
import { createIamClient } from 'better-iam/client';
import type { iam } from './iam';

export const client = createIamClient<typeof iam>({ baseURL: 'https://app.acme.test' });

Schedule the jobs

Budget alerts, seat recording, invoicing, reminders, and spike detection run as jobs. See Scheduled jobs.

npx better-iam billing-alerts --config better-iam.config.mjs   # hourly
npx better-iam billing-close --config better-iam.config.mjs    # daily

The model

  • Meters name what is billed: API calls, seat-days, GB-days, CI builds, AI inference. The root tenant defines platform meters billed to every organization; an organization or project can define chargeback meters for its own subtree, which show in its spend but never on a platform statement.
  • A rate card prices each meter: per unit, graduated or volume tiers, packages, a free allowance, and negotiated prices for individual organizations.
  • A billing account is an organization, or a tenant below it with a billing profile of its own. Each meter's month total is priced once per account and then shared out to the usage that produced it by quantity (for active-user meters, equally per person), so every breakdown adds up to the account's charges.

Usage

Meters and prices

billing.createMeter and billing.setPrice (iam:billing:manage) define what is billed and its price. Price models are per-unit, graduated, volume, and package.

await iam.api.billing.createMeter(root, {
  tenantId: rootTenantId,
  key: 'api-calls',
  name: 'API calls',
  unit: 'request',
});
await iam.api.billing.setPrice(root, {
  tenantId: rootTenantId,
  meter: 'api-calls',
  price: {
    model: 'graduated',
    includedQuantity: 10_000,
    tiers: [
      { upTo: 1_000_000, unitAmount: 0.0004 },
      { upTo: null, unitAmount: 0.0002 },
    ],
  },
});
// A negotiated price for one organization and its projects:
await iam.api.billing.setPrice(root, {
  tenantId: rootTenantId,
  meter: 'api-calls',
  targetTenantId: acmeId,
  price: { model: 'per-unit', unitAmount: 0.0003 },
});

Route: POST /api/iam/billing/createMeter (also /billing/updateMeter, /billing/deleteMeter, /billing/listMeters, /billing/setPrice, /billing/listPrices)

SettingMeaning
aggregation: 'sum'Quantities add up (default).
aggregation: 'unique'Distinct people and agents with usage in the month: active users or active seats.
pricing: 'rate-card'Priced from the rate card (default).
pricing: 'reported'Every event carries its own cost, as AI inference and chargeback entries do.

Keys belong to the tenant nearest the root, so an organization can never redefine a platform meter, and inference is a built-in platform meter. A price applies from effectiveFrom (a month) until a later entry, and the entry nearest the billing account wins. Past months can be priced until they are invoiced (BILLING_PERIOD_CLOSED after). A meter that has recorded usage cannot be deleted (RESOURCE_IN_USE); archive it instead, after which it accepts no usage (METER_ARCHIVED).

Recording usage

Server code records usage without a credential and without an audit event per call:

import { iam } from './iam';

await iam.billing.record({
  tenantId: projectId,
  meter: 'api-calls',
  quantity: 1,
  identityId: session.identity.id,
  tags: { endpoint: 'search' },
  idempotencyKey: requestId,
});

Route: POST /api/iam/billing/record (also /billing/recordMany)

Backends that only reach the HTTP API use billing.record or billing.recordMany with a service account holding iam:billing:record. Each event is attributed when it is recorded: to the person, service account or agent, to the teams they belong to directly (teamId overrides that), and to their department. An agent's usage counts toward its sponsor's teams and department. Metered AI inference arrives by itself on the built-in inference meter, and iam.billing.recordSeats() records one seat per active person each day for seat pricing. An idempotency key reused for another meter is a CONFLICT, and usage for a month already invoiced is refused with BILLING_PERIOD_CLOSED.

Reading spend

billing.spend and billing.trend (iam:billing:read) report spend for a tenant. Group by meter, identity, agent, team, department, tenant (projects), day, or a tag. Filters narrow to a meter, a person, a team or department (with those below it), or a project; the current month includes a linear forecast. People in several teams count toward each in equal parts, unless the billing option teamAttribution says primary or full.

const byTeam = await iam.api.billing.spend(admin, { tenantId, groupBy: 'team' });
const platformTeam = await iam.api.billing.spend(admin, { tenantId, teamId, groupBy: 'identity' });
const sixMonths = await iam.api.billing.trend(admin, { tenantId, months: 6 });

Route: POST /api/iam/billing/spend (also /billing/trend, /billing/mySpend, /billing/teamSpend, /billing/departmentSpend, /billing/check)

WhoReadsNeeds
Billing managersspend, trend, budgets, credits, statementsiam:billing:read
Team maintainersteamSpend for their team and the teams below itmaintaining the team
Department headsdepartmentSpend for their department and those belowheading the department
EveryonemySpend: their own usage and their agents'a session of the tenant

The CLI prints the same report: better-iam spend --tenant TENANT_ID --group-by team.

Budgets

await iam.api.billing.createBudget(admin, {
  tenantId,
  name: 'Platform team monthly',
  subjectType: 'team',
  subjectId: platformTeamId,
  amount: 600,
  thresholds: [50, 80, 100],
  notify: { emails: ['finance@acme.test'] },
  enforce: false,
});

Route: POST /api/iam/billing/createBudget (also /billing/updateBudget, /billing/deleteBudget, /billing/listBudgets)

A budget covers a tenant subtree, a team with its sub-teams, a department with those below it, or one person, per month, quarter or year. iam.billing.checkBudgets() alerts once per threshold and window, and when the projection passes the budget: an audit event billing:budget-alert that webhooks can forward, and a spend-alert email to the owners, the subject (the person, the team's maintainers, the department head) and any extra addresses. An enforced budget refuses covered usage once it is spent (SPEND_LIMIT_REACHED, 402, for record with enforceBudgets), and billing.check tells callers in advance.

Inference budgets stay the hard, per-call caps on model tokens and cost; billing budgets watch money across every meter.

Spikes, showback and exports

Budgets catch spend that adds up; billing.anomalies catches spend that jumps: people, teams and meters whose spend yesterday was at least three times their daily average over the 14 days before (and at least 10 in the deployment currency; factor, baselineDays, and minimum change these), such as a looping pipeline, a leaked key, or an agent retrying forever. iam.billing.detectAnomalies() runs daily and alerts once per spike (billing:anomaly, spend-anomaly email). For showback, shareUnattributed: true spreads spend nobody in the dimension caused over the teams, departments or people that did, by their share. billing.exportSpend and billing.exportStatement return CSV for spreadsheets.

Route: POST /api/iam/billing/anomalies (also /billing/exportSpend, /billing/exportStatement)

Profiles, credit and statements

A billing profile names who pays: company, billing emails, tax ID, address, purchase order, cost center and payment terms. A profile on a project makes the project a billing account of its own, which is its parent's decision, so it is created from the organization with targetTenantId. Root administrators grant credit to billing accounts (billing.grantCredit) and set contract terms (billing.setTerms: discount, minimum commitment, tax rate).

await iam.api.billing.setProfile(orgAdmin, {
  tenantId: orgId,
  targetTenantId: projectId,
  companyName: 'Apollo Ltd',
  billingEmails: ['ap@apollo.test'],
});

Route: POST /api/iam/billing/setProfile (also /billing/getProfile, /billing/deleteProfile, /billing/grantCredit, /billing/setTerms, /billing/getTerms)

iam.billing.closePeriod() issues last month's invoice for every billing account with something to bill: one line per platform meter (with the tiers its quantity used), subscription fees and seats, pending invoice items, coupons, credit applied earliest expiry first, tax, the total and due date, and a breakdown of usage by project, team, department (with cost centers) and person. Invoices carry a content hash and bill whole cents, so their lines add up. billing.previewStatement shows a billing account its invoice so far, and listStatements and getStatement read issued ones.

Invoicing

Invoices follow the lifecycle Stripe uses:

  • Drafts. With billing.autoFinalize: false (or closePeriod({ draft: true })) monthly invoices stay drafts, recomputed on every run, until a root administrator finalizes them. Their month still takes late usage.
  • Invoice items are one-off charges, or credits with a negative amount, for an account's next invoice (createInvoiceItem). When credits exceed the charges the rest becomes account credit.
  • Payments (recordPayment) may be partial; an overpayment becomes credit. Payment processors report payments with iam.billing.recordPayment({ number, amount, idempotencyKey }) from their webhooks.
  • Credit notes (createCreditNote) reduce the amount due first; a part already paid becomes credit or is recorded as refunded. Invoices with payments or credit notes are corrected with credit notes, never voided.
  • Reminders. iam.billing.sendPaymentReminders() emails billing contacts before and after the due date (billing.paymentReminderDays, default 3 days before, on the day, 7 and 14 days after).
  • Printable invoices. renderInvoice returns a self-contained HTML page with the issuer from billing.issuer, to print or save as PDF.

Route: POST /api/iam/billing/finalizeInvoice (also /billing/closePeriod, /billing/createInvoiceItem, /billing/recordPayment, /billing/createCreditNote, /billing/markPaid, /billing/markUncollectible, /billing/voidStatement, /billing/renderInvoice)

Plans, subscriptions and coupons

await iam.api.billing.createPlan(root, {
  tenantId: rootTenantId,
  key: 'team',
  name: 'Team',
  selfServe: true,
  trialDays: 14,
  items: [
    { id: 'platform', kind: 'fee', name: 'Platform fee', amount: 99 },
    { id: 'seats', kind: 'seat', name: 'Seats', unitAmount: 12, includedSeats: 3 },
    { id: 'calls', kind: 'usage', meter: 'api-calls', price: { model: 'per-unit', unitAmount: 0.0003 } },
  ],
});
await iam.api.billing.subscribe(orgAdmin, { tenantId: acmeId, plan: 'team', seats: 8 });
await iam.api.billing.redeemCoupon(orgAdmin, { tenantId: acmeId, code: 'LAUNCH20' });

Route: POST /api/iam/billing/subscribe (also /billing/createPlan, /billing/updatePlan, /billing/listPlans, /billing/changePlan, /billing/updateSubscription, /billing/cancelSubscription, /billing/resumeSubscription, /billing/listSubscriptions, /billing/quote, /billing/createCoupon, /billing/deactivateCoupon, /billing/listCoupons, /billing/redeemCoupon, /billing/listDiscounts, /billing/removeDiscount)

Fees and seats are billed a month ahead (or in arrears per item), prorated when a subscription starts, changes seats, changes plan or ends mid-month; a plan's usage items replace the rate card for its subscribers. Outside a trial the first month is invoiced at once. Plans are created and changed on the root tenant by root administrators. Organizations subscribe to self-serve plans and manage those subscriptions themselves (iam:billing:manage), and cancel them at the end of the month; root administrators manage subscriptions to every plan, end subscriptions at once, and create coupons (percentOff or amountOff, once, for some months, or forever).

A license pool can name the subscription that paid for its seats (subscriptionId); that is a reference only, and nothing is metered or prorated on the license side.

Spend in policies

Budgets reach authorization too. Two context keys describe the budgets that cover the principal in the decision's tenant (tenant budgets up the tree and, for a person of the tenant, their own, their teams', and their department's):

KeyTypeMeaning
principal.spendExceededbooleanAn enforced budget covering the principal is spent
principal.budgetsExceededlistNames of every spent budget covering the principal
No exports once an enforced budget is spent
{
  "effect": "deny",
  "actions": ["reports:export"],
  "resources": ["*"],
  "conditions": { "Bool": { "principal.spendExceeded": true } }
}

Decisions read budgets only when a policy names one of the keys, and standings are cached for up to 30 seconds. An assumed role sees only the tenant's budgets.

Scheduled jobs

JobCLISchedule
iam.billing.checkBudgets()billing-alertshourly
iam.billing.recordSeats()billing-seatsdaily
iam.billing.closePeriod()billing-closedaily
iam.billing.sendPaymentReminders()billing-remindersdaily
iam.billing.detectAnomalies()billing-anomaliesdaily

billing-close --draft keeps the month's invoices as drafts. See Scheduled jobs for the other jobs a deployment runs.

Options

The billing option of betterIam(). A bad value fails construction with INVALID_CONFIG.

OptionTypeDefaultDescription
currencystring'USD'ISO 4217 code every amount is stated in.
timeZonestring'UTC'IANA time zone that billing months and days follow.
usageRetentionDaysnumber400Days raw usage events are kept after their period ends; daily roll-ups and statements stay.
teamAttribution'split' | 'primary' | 'full''split'How a person's cost counts toward their teams: evenly across direct teams, all to the oldest team, or in full to each.
paymentTermsDaysnumber30Days after issue a statement is due when the billing profile sets no terms.
statementPrefixstring'INV'Statement numbers read {prefix}-{YYYYMM}-{sequence}.
issuer{ name, address?, taxId?, email?, url?, paymentInstructions? }product name onlyWho issues the invoices, printed on every invoice.
paymentReminderDaysnumber[][-3, 0, 7, 14]When payment reminders go out, in days relative to the due date; [] sends none.
autoFinalizebooleantrueWhether closePeriod finalizes monthly invoices at once; false keeps drafts for review.

Permissions

ActionMethods
iam:billing:readReports and listings: spend, trend, quote, anomalies, accounts, listUsage, listMeters, listPrices, listBudgets, listCredits, listStatements, getStatement, previewStatement, renderInvoice, exportSpend, exportStatement, getProfile, getTerms, listPlans, listSubscriptions, listDiscounts, listInvoiceItems, listCreditNotes; and listCoupons (root administrators only)
iam:billing:manageChanges: meters and prices, budgets, profiles, subscriptions to self-serve plans, and coupon redemption. These also require a root administrator: closePeriod, finalizeInvoice, recordPayment, markPaid, markUncollectible, voidStatement, createInvoiceItem, deleteInvoiceItem, createCreditNote, grantCredit, revokeCredit, setTerms, createPlan, updatePlan, createCoupon, deactivateCoupon, removeDiscount, subscription changes to plans that are not self-serve, and cancelling a subscription immediately
iam:billing:recordrecord, recordMany over HTTP
Team maintainer or department headteamSpend, departmentSpend
NonemySpend and check (a session of the tenant)

Billing changes are audited as billing:* events, including billing:budget-alert and billing:anomaly.

Schema

Records live in the shared iam_records table under these tenant-scoped collections. Money is stored in micros of the deployment currency (amountMicros, costMicros).

CollectionHoldsKey fields
billingMetersMeters the tenant defineskey, name, unit, aggregation, pricing, archived
billingPricesRate-card entriesmeterId, meter, definerId, effectiveFrom (a month), spec, note
billingUsageRaw usage eventsmeterId, meter, quantity, costMicros, identityId, agentId, teamIds, departmentId, tags, occurredAt, period, day
billingRollupsDaily roll-upsperiod, day, meterId, identityId, agentId, teamIds, departmentId, tags, quantity, costMicros, events
billingBudgets, billingBudgetAlertsBudgets and the alerts already sentname, subjectType, subjectId, amountMicros, period, meters, thresholds, forecastAlerts, notify, enforce
billingCreditsCredit granted to an accountamountMicros, remainingMicros, reason, expiresAt, grantedBy, revokedAt
billingProfiles, billingTermsWho pays, and contract termscompany, billing emails, tax ID, address, payment terms; discount, commitment, tax rate
billingStatementsInvoicesnumber, status, issuedAt, dueAt, hash, payments, amountPaidMicros, creditNotesMicros, paidAt
billingInvoiceItems, billingCreditNotesOne-off charges and credit notesamount, description, the invoice they belong to
billingPlans, billingSubscriptionsPlans (on the root) and subscriptionskey, items, trialDays, selfServe; planId, seats, startedAt, trialEndsAt, cancelAtPeriodEnd
billingCoupons, billingDiscountsCoupons (on the root) and redeemed discountscode, percentOff, amountOffMicros, duration, maxRedemptions, redemptions, active

A tenant defines at most 100 meters, 200 budgets, and 100 plans.

Errors

CodeStatusWhen
BILLING_PERIOD_CLOSED409Usage, a price, or an invoice item for a month already invoiced for the account
METER_ARCHIVED409Usage on an archived meter
SPEND_LIMIT_REACHED402record({ enforceBudgets: true }) under a spent, enforced budget
CONFLICT409A meter, plan, budget, or coupon with that key or name exists; a built-in meter key; an idempotency key reused for another meter; the account already subscribes to the plan or redeemed the code
RESOURCE_IN_USE409Deleting a meter that has recorded usage
LIMIT_EXCEEDED409More than 100 meters, 200 budgets, or 100 plans in a tenant
INVALID_TRANSITION409An invoice or subscription operation that its current state does not allow, such as voiding an invoice that has payments or credit notes, or a draft
ACCESS_DENIED403Missing permission, or reading spend with a credential of another tenant
NOT_FOUND404An unknown meter, budget, statement, plan, subscription, or coupon
INVALID_INPUT400A malformed key, amount, period, or price
INVALID_CONFIGstartupA bad value in the billing option

In the console

  • Organization → Billing: spend this month by person, team, department, project, meter or day, the six-month trend, budgets, invoices with the amount due, the subscription (seats, cancel, keep), self-serve plans, promotion codes, charges waiting for the next invoice, the meters and prices that apply, the billing profile, and chargeback meters. People without billing permissions see their own spend there.
  • Invoice pages: lines with tier sub-lines, service periods and prorations, coupons, payments, credit notes, breakdowns, the integrity check, and "Print or save as PDF".
  • Administration → Billing (root): accounts and what they owe, invoices (finalize, mark paid, write off, void), payments, credit notes, invoice items, plans, subscriptions, coupons, closing a month (optionally as drafts), contract terms, credit, and platform meters and prices.

Next steps

Was this page helpful?

Better IAM is created by Sean Filimon

Last updated

On this page