Metering Usage and Billing with Stripe
Record usage per customer, enforce plan limits, and bill for it with Stripe — including credits, overages, and reconciling against your provider bill.
You've picked a pricing model: seats with an included credit allowance, and overage billed per credit. Now it has to work in code, every day, for every customer, without double-charging anyone or letting a runaway integration burn through a month of credits in an afternoon. Billing bugs are a special kind of bug. Overcharge a customer once and you lose their trust; undercharge for months and you lose your margin without noticing.
In this lesson you'll build Deskmate's metering and billing: a usage ledger that records every billable AI action, enforcement that checks limits before work happens, idempotent reporting of overage to Stripe's usage-based billing, prepaid credit top-ups through Checkout, and a monthly reconciliation that compares your ledger, Stripe's totals, and your AI provider's bill.
The shape of a metering system
Metering means recording how much of your product each customer used, in units you bill for. It's tempting to make your billing provider the source of truth: send an event per AI call and let it add things up. Don't. You need usage data in your own database for three jobs your billing provider can't do in real time:
- Enforcement. Before running an expensive action, you need to know whether this tenant has credits left. That check has to be fast and consistent, inside your request.
- Display. Customers should see their usage and remaining allowance in your product, updated immediately.
- Reconciliation. When a customer disputes a bill, you need the list of actions behind it, each linked to the model call that produced it.
So the architecture has four parts:
| Part | What it does | Where it lives |
|---|---|---|
| Usage ledger | One row per billable action, in credits | Your Postgres |
| Enforcement | Checks allowance and caps before work runs | Your request path |
| Reporting | Sends billable usage to Stripe on a schedule | A background job |
| Reconciliation | Compares ledger, Stripe, and provider costs | A monthly job and report |
Stripe's part is what it's good at: aggregating reported usage per billing period, turning it into invoice line items, charging cards, and handling taxes, dunning (retrying failed payments), and receipts.