Demo
General
Billing

Metered Usage

Learn how to charge customers based on their usage.

Metered usage billing is a model where customers are charged based on their actual usage which commonly seen in AI apps and APIs, where charges are based on requests made.

Billing configuration

Here’s how you can define a metered usage plan in your billing schema:

packages/billing/src/config.ts
export const config = createBillinConfig({  products: [    {      id: 'starter',      name: 'Starter',      description: 'The perfect plan to get started',      isRecommended: true,      plans: [        {          id: 'plan-starter-month',          prices: [            {              id: 'price_1234',              type: PriceType.Recurring,              interval: PriceInterval.Month,              model: PriceModel.Metered,              cost: 0, // Must be 0. If you want also a subscription, like $5/mo, add another price to the plan.              currency: 'USD',              meter: {                id: 'mtr_test_1234'                unit: 'API requests',                tiers: [                  { upTo: 10000, cost: 0 },                  { upTo: Infinity, cost: 0.01 }                ]              }            }          ]        }      ]    }  ]});

Tiers in the example

  • First 10000 API requests are free
  • Beyond 10001 API requests the rate goes to $0.01 per request
  • The meter resets every billing cycle (here: month)

Reporting usage

Assume you track usage via a function consumeApiTokens. You’d report usage like so:

apps/dashboard/api/something/route.ts
const quantity = await consumeApiTokens(organizationId);await BillingProvider.reportMeteredUsage({  customerId: ctx.organization.billingCustomerId,  eventName: 'api_tokens',  quantity});

Querying usage

We would need to fetch the metered subscription by organizationId from our database. Then we can query the usage of our meter. Note that a meter can have multiple event names.

apps/dashboard/query-example.ts
const currentUsage = await BillingProvider.getMeteredUsage({  meterId: price.meter.id,  customerId: ctx.organization.billingCustomerId,  startsAt: subscription.periodStartsAt,  endsAt: subscription.periodEndsAt});

Subscription handling

After checkout, two records are stored:

  • A Subscription record for the overall subscription.
  • A SubscriptionItem record to track usage-based charges.

This allows the system to report usage accurately to the billing provider.

Deleting an organization

When an organization get's deleted, the starter kit will:

  • Create an invoice for the metered billing.
  • Cancel any active subscription.
  • Delete the Subscription entry.
  • Delete the SubscriptionItem entry.

This is fine since the billing provider will hold the data.