# Metered Usage

> Charge per unit of usage: declare meters, make the Stripe meter and price by hand, record usage from server code, cap it, show it on the billing page, and check it with billing:doctor.

*Canonical: https://makerkit.dev/docs/void-cloudflare/billing/usage*

---

A plan can charge per unit of something your app does (AI tokens, emails sent, API calls). The kit counts each use per account, can refuse uses past a cap, shows the count on the billing page, and sends every use to Stripe as a [meter event](https://docs.stripe.com/billing/subscriptions/usage-based). Stripe is the billing truth; the local count is what your app enforces and shows.

## 1. Make the Meter and the Price in Stripe

Do this first: with billing on, the app refuses to load until every price id in the config is set. `pnpm billing:setup` makes no meter or metered price, so you make them in the Stripe Dashboard (test mode first), once per meter.

1. **Billing → Meters → Create meter**: event name `ai_tokens` (any name; the config repeats it), aggregation **Sum**, customer mapping key **`stripe_customer_id`**, value key **`value`**. Stripe can't change a meter's event name or aggregation later.
2. **Product catalog**: a recurring price on that meter (per unit or graduated tiers) and put its id in `apps/web/.env` as `STRIPE_PRICE_PRO_TOKENS`, declared in `apps/web/env.ts` and `env.example` like every price (a key missing from `env.ts` reads as "not set").
3. Run `pnpm billing:doctor`: the `meters` check says what differs, per meter and per price.

The same key works for meter events (`STRIPE_SECRET_KEY`); the kit sends events only from its outbox job, never from a request.

## 2. Declare Them

In `billing.config.ts`, a top-level `meters` entry per meter, and a `metered` line item on each plan that charges for it. The plan's first (primary) line item must stay a flat price.

```ts
export const billingConfig = defineBillingConfig({
  currency: 'usd',
  // what an account without a subscription gets: its whole allowance
  defaultLimits: { tokens: 100 },
  meters: {
    tokens: { eventName: 'ai_tokens', label: 'billing.meters.tokens' },
  },
  products: [
    {
      id: 'pro',
      name: 'billing.products.pro.name',
      description: 'billing.products.pro.description',
      plans: [
        {
          name: 'pro-monthly',
          interval: 'month',
          lineItems: [
            { kind: 'flat', priceEnv: 'STRIPE_PRICE_PRO_MONTHLY', cost: 19 },
            {
              kind: 'metered',
              priceEnv: 'STRIPE_PRICE_PRO_TOKENS',
              meter: 'tokens',
              allowance: 1000, // included in the flat price; shown on the page
            },
          ],
          limits: { tokens: null }, // the cap; null: no cap (billed per unit)
        },
      ],
    },
  ],
});
```

`label` is a message key for the unit's name, in `apps/web/messages/<locale>/billing.json` (`meters.tokens`; agents: the `app_translations_*` tools). `allowance` only drives the display; what is free is set in the Stripe price (graduated tiers, first tier at 0).

## 3. Record Usage

In an action, after you authorized the caller:

```ts
import { billingRefusalOf } from '@kit/billing';

export const actions = {
  generate: defineHandler(async (c) => {
    requireSession({ c });
    // …your validation and authorization (the role that may do this)…
    const usage = await getUsage({ c });
    const result = await generateText(prompt); // yours

    const { duplicate } = await usage.record({
      meter: 'tokens',
      quantity: result.tokens, // a whole number, 1 to 1,000,000
      key: generationId, // your id for this unit of work
    });

    return { result, duplicate };
  }),
};
```

A refused call is a 409 `LIMIT_REACHED`; the form decodes it with `billingRefusalOf(form.error)` like any plan limit ([Gating](./gating)).

- **The key** is an id your server made for the unit of work (a generation or message id), not one the browser can choose: a repeat of it counts once, so a browser retry can't double-bill, and a caller who picks the key can't dodge the count. `record` answers `{ total, duplicate }`: on `duplicate: true` the use was already counted, so don't charge it or redo the work. A repeat with a different `quantity` is ignored too. A key is remembered while its outbox job exists (7 days after it succeeded, 90 after it died): never reuse a long-lived business id. Keep personal data out of it.
- **The account** is the session's (`getBilling`), never from the request. `quantity` comes from your code, never a request body.
- **The cap** protects you from a runaway loop or an abused route. By default a use is refused past `limits[meter]` (the plan's, else `defaultLimits`) **unless the account's live plan bills that meter and is past its trial**: only then is the overage invoiced. So an account without a plan, on a plan that doesn't bill the meter, or in a trial (Stripe doesn't bill usage recorded in a trial) is bounded by its cap: set `defaultLimits[meter]` to the free quota (`0` for none) and the trial's cap, or those accounts use the meter at your cost without limit. Pass `enforceCap: true` to also cap a billed plan, or `false` to never refuse. Plans are laid over `defaultLimits`: a plan that bills a meter with a default cap must set its own `limits[meter]` (`null` for no cap) or the config fails to load. Also rate-limit the route.
- **Cost known only afterwards** (AI tokens): `record` after the work with `enforceCap: false` (a billed overage is invoiced), or refuse earlier from what you know.
- The count and the Stripe job are written in one transaction (not joinable with your own). Usage while billing is off stays local and is never sent later.
- The period is the live subscription's current period, else the UTC month.

## Test It

`fakeUsage({ config, billing, used? })` (`billing` from `fakeBilling({ config, plan })`: its plan and limits decide the caps) from `@kit/billing/testing` is `getUsage`'s answer in memory, with the real rules (bad input, `duplicate`, caps) and `calls` listing what your code recorded. Mock `#/lib/billing.server.ts` to return it, as with `fakeBilling` ([Gating](./gating)).

## Show It

The billing page loader returns `usage` (`usage.read()`) and renders `<UsageCard rows={usage} />`: used against allowance or cap, the reset date, an overage badge and a cap alert. It shows a meter the plan bills or caps.

## Plans With Metered Items

A plan's extra and metered line items reach Stripe Checkout with the plan. Switching **to or from** a plan with extra line items can't use Stripe's confirm page (it can't update a subscription with several items), so the plan picker shows **Review switch** for those plans: a page with what is due now or credited (Stripe's invoice preview) and a **Confirm change** button. Confirming swaps the plan's items in one Stripe update and invoices the proration at once. If the card needs 3D Secure or is declined, nothing changes and the page says the card couldn't be charged and to use another card in Manage billing, then try again (`SWITCH_PAYMENT_FAILED`). Deleting an account ends its subscription with a final invoice, which bills the period's usage.

## When Something Is Wrong

`pnpm billing:doctor` checks each meter, each metered price and the dead billing jobs. A dead usage job stays counted locally and is not billed. Most are usage Stripe refused for good (unknown meter, older than 35 days): fix the cause, then run it again with `outbox.replay` ([failures](../outbox/failures)). One that died on timeouts or network errors may have reached Stripe already: check the meter's events in the Stripe Dashboard before replaying it, since Stripe only dedupes a replay within about 24 hours of the first send. Transient errors, rate limits and a refused key retry on their own.
