Your pricing page says "$49 a month, 10,000 AI credits included, then $2 per 1,000." It took a minute to write. Then the first invoices go out. One customer's report is counted twice after a deploy. Another's usage from the last night of the month lands on the wrong invoice. A third emails to ask why the meter in your app says 9,800 credits while Stripe billed for 10,400.
Stripe usage-based billing has three moving parts: a meter that adds up usage, a metered price attached to that meter, and the meter events your backend sends. A hybrid plan is two prices on one subscription: a flat price billed in advance and a metered price billed in arrears. The API calls are the easy part. The hard part is counting every billable action exactly once, on the right invoice, and showing customers the same number they'll pay. And one thing changed in 2026: Stripe now points new integrations to Metronome, its usage-billing platform, so this post covers when that's the better choice too.
TL;DR#
- Hybrid pricing is two prices on one subscription: a licensed price for the plan and a tiered metered price whose first tier is free up to the included allowance.
- Record usage in your own database first, in the same transaction as the work, under a unique key built from the business action. That ledger is your source of truth.
- Report to Stripe from a background job, with the ledger row's ID as the meter event
identifier. A resend after a crash comes back asduplicate_meter_event, and nothing is billed twice. - Show customers usage from your ledger, not Stripe's. Stripe processes meter events asynchronously, so its totals lag.
- Stripe now recommends Metronome for new usage-based integrations. Billing Meters are still fully supported and fine for a plan plus a simple overage; credits that stop at zero, contracts and high volume point to Metronome.
What this means for your product#
Usage pricing lets small customers start cheap and lets heavy users pay for what they cost you. That matters most for AI features, where one customer's usage can cost a hundred times another's.
It also moves risk onto the invoice. A flat plan is the same every month; a usage bill is a number the customer has to trust. So before choosing Stripe objects, decide three things: the unit (something customers understand and you can count reliably: reports, API calls, credits), the allowance included in the plan, and what happens at the limit (keep going and bill overage, or stop). An invoice nobody can explain becomes a support ticket, and sometimes a chargeback.
Choose a pricing model before writing code#
| Model | The customer pays | How it's built in Stripe | Good for | Watch out for |
|---|---|---|---|---|
| Per seat | A fixed price per user per month | A licensed price with a quantity | Team tools | Seat changes create prorations |
| Pay as you go | Only what they used, at the end of the month | A metered price on a meter | APIs, infrastructure | No revenue floor; bills are hard to predict |
| Hybrid (plan plus overage) | A base fee that includes an allowance, then a rate per unit | A licensed price plus a tiered metered price whose first tier is free | Most SaaS products adding AI features | The free tier must match the allowance you advertise |
| Prepaid credits | Credits bought up front, spent as they go | Credit grants (applied when the invoice finalizes), your own balance, or Metronome | Products with expensive actions | Stripe's credit grants don't stop usage at zero |
For a SaaS product adding an AI feature, I'd start with hybrid. The plan fee covers your fixed costs and gives revenue a floor, the allowance keeps normal months predictable, and the overage keeps heavy users from costing you money. The rest of this post builds that model: $49 a month with 10,000 credits included, then $2 per 1,000.
Billing Meters or Metronome?#
This is the part most tutorials are now missing. As of October 2026, Stripe's own pay-as-you-go guide is labelled "Not recommended" for new integrations and points to Metronome, which Stripe calls its primary usage-based billing platform. Billing Meters keep working, and Stripe says existing integrations don't need to migrate. Stripe's comparison page has the details; the rows that usually decide it:
| Billing Meters | Metronome | |
|---|---|---|
| Pay as you go; plan plus overage | Yes | Yes |
| Credits | Applied when the invoice finalizes; customers can go past their balance mid-cycle | Real-time burn-down |
| Prepaid credits that stop at zero, commits, contracts | No | Yes |
| Different rates by model or region on one meter | No | Yes |
| Real-time usage visibility | No | Yes |
| Stripe Checkout and Dashboard | Yes | Checkout needs custom work; no Dashboard support |
| Fees (21 Oct 2026) | 0.7% of billing volume | 0.8% of billing volume plus $0.04 per 1,000 events |
Stripe's docs go further and suggest Metronome even when you're adding usage pricing to existing flat-rate subscriptions. My position is narrower. If your pricing is one plan plus one overage, and customers sign up through Checkout, Billing Meters are still the shorter path: one system, one Dashboard, the customer portal you already have. Know that you're on the track Stripe is no longer expanding. Choose Metronome if you need prepaid credits that cut off at zero, enterprise contracts with commits, prices that vary by model or region, or very high event volume.
Either way, the next sections apply. Both need a usage ledger and idempotent reporting; only the call at the end changes.
How Stripe usage-based billing fits together#
Five pieces: the app records usage in a ledger, a job reports it, Stripe meters and invoices it, webhooks report back, and the billing page reads the ledger.
Step 1: a meter, two prices and a hybrid subscription#
Create the meter and prices once per Stripe account, in a sandbox first. This runs on stripe-node 23 (API version 2026-09-30.endive):
// scripts/setup-billing.ts: run once per Stripe account (sandbox first, then live).
import Stripe from 'stripe';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
// 1. The meter: sums the credits each customer uses in a billing period.
const meter = await stripe.billing.meters.create({
display_name: 'AI credits',
event_name: 'ai_credits',
default_aggregation: { formula: 'sum' },
customer_mapping: { type: 'by_id', event_payload_key: 'stripe_customer_id' },
value_settings: { event_payload_key: 'value' },
});
// 2. The flat part: $49 a month, billed in advance.
await stripe.prices.create({
currency: 'usd',
unit_amount: 4900,
recurring: { interval: 'month', usage_type: 'licensed' },
product_data: { name: 'Pro plan' },
lookup_key: 'pro_monthly',
});
// 3. The usage part: 10,000 credits included, then $2 per 1,000 (0.2 cents each), billed in arrears.
await stripe.prices.create({
currency: 'usd',
billing_scheme: 'tiered',
tiers_mode: 'graduated',
tiers: [
{ up_to: 10_000, unit_amount: 0 },
{ up_to: 'inf', unit_amount_decimal: Stripe.Decimal.from('0.2') },
],
recurring: { interval: 'month', usage_type: 'metered', meter: meter.id },
product_data: { name: 'AI credits' },
lookup_key: 'pro_credits_monthly',
});
Three details:
- Graduated tiers make the allowance. The first 10,000 credits cost nothing; only the ones above are charged. A customer who uses 14,500 credits pays 4,500 × $0.002 = $9.00 on top of the plan.
Stripe.Decimal, not a string. Since stripe-node v21 (March 2026), decimal fields such asunit_amount_decimaltake aStripe.Decimal. Older tutorials pass'0.2', which no longer type-checks.- Every metered price needs a meter. The legacy usage-records API was removed in API version
2025-03-31.basil, along withaggregate_usage. If a tutorial callscreateUsageRecord, it's out of date.
Customers then subscribe to both prices in one Checkout session:
const { data: prices } = await stripe.prices.list({ lookup_keys: ['pro_monthly', 'pro_credits_monthly'] });
const price = (key: string) => prices.find((p) => p.lookup_key === key)!.id;
const session = await stripe.checkout.sessions.create({
mode: 'subscription',
customer: account.stripeCustomerId,
line_items: [
{ price: price('pro_monthly'), quantity: 1 },
{ price: price('pro_credits_monthly') }, // metered: no quantity
],
subscription_data: { billing_mode: { type: 'flexible' } },
success_url: 'https://app.example.com/billing?checkout=done',
cancel_url: 'https://app.example.com/billing',
});
Stripe recommends flexible billing mode for new subscriptions; it changes how usage is billed when prices change mid-cycle (more on that below), and you can't switch a subscription back to classic. Grant access from the verified invoice.paid webhook, never from the success page, exactly as in Stripe webhooks that never double-charge.
Step 2: record usage in your own database first#
The tempting version calls Stripe inline: the report finishes, the handler sends a meter event. Then Stripe is slow, the request times out, the client retries, and you've sent two events for one report. Or the report fails after the event went out, and the customer pays for nothing.
Instead, record each billable action in a ledger table, in the same transaction as the work:
CREATE TABLE usage_events (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
account_id uuid NOT NULL REFERENCES accounts (id),
idempotency_key text NOT NULL, -- from the business action, e.g. 'report:8f14e45f'
quantity bigint NOT NULL CHECK (quantity > 0),
occurred_at timestamptz NOT NULL,
reported_at timestamptz, -- Stripe accepted it
failed_at timestamptz, -- Stripe will never accept it
error text,
UNIQUE (account_id, idempotency_key)
);
CREATE INDEX usage_events_unreported ON usage_events (occurred_at)
WHERE reported_at IS NULL AND failed_at IS NULL;
import type { PoolClient } from 'pg';
// Call this inside the same transaction as the work being billed.
export async function recordUsage(db: PoolClient, accountId: string, key: string, quantity: number) {
await db.query(
`INSERT INTO usage_events (account_id, idempotency_key, quantity, occurred_at)
VALUES ($1, $2, $3, now())
ON CONFLICT (account_id, idempotency_key) DO NOTHING`,
[accountId, key, quantity],
);
}
// Example: a report costs 40 credits, and the report ID makes the charge happen once.
export async function generateReport(db: PoolClient, accountId: string, reportId: string) {
await db.query('BEGIN');
try {
// ... create the report row ...
await recordUsage(db, accountId, `report:${reportId}`, 40);
await db.query('COMMIT');
} catch (err) {
await db.query('ROLLBACK');
throw err;
}
}
This buys you four things:
- Work and charge commit together. If the report fails, its usage row rolls back with it.
- Retries are free. The key comes from the business action (
report:{id}), not the attempt, so a retried job or a double click inserts nothing. It's the same rule I use for AI agent tool calls: build idempotency keys from what happened, not from who tried. - A number you can show and audit. Every invoice line can be traced back to rows, and rows to reports.
- Freedom to change vendors. Moving to Metronome later changes the reporter, not your product code.
In a multi-tenant app, keep the ledger inside the same tenant rules as everything else; multi-tenant PostgreSQL covers the options.
Step 3: report usage to Stripe exactly once#
A job runs every minute, reads unreported rows, and sends each one to Stripe. It uses the v2 meter events endpoint, which validates each event when it arrives and returns clear errors, instead of the v1 endpoint, which reports problems later:
// src/billing/report-usage.ts: run every minute, one instance at a time.
import Stripe from 'stripe';
import type { Pool } from 'pg';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
type Row = { id: string; quantity: string; occurred_at: Date; stripe_customer_id: string };
export async function reportUsage(pool: Pool) {
const { rows } = await pool.query<Row>(
`SELECT u.id, u.quantity, u.occurred_at, a.stripe_customer_id
FROM usage_events u JOIN accounts a ON a.id = u.account_id
WHERE u.reported_at IS NULL AND u.failed_at IS NULL
ORDER BY u.occurred_at
LIMIT 500`,
);
for (const row of rows) {
try {
await stripe.v2.billing.meterEvents.create({
event_name: 'ai_credits',
identifier: row.id, // the same row always sends the same identifier
timestamp: row.occurred_at.toISOString(),
payload: { stripe_customer_id: row.stripe_customer_id, value: row.quantity },
});
} catch (err) {
const code = err instanceof Stripe.errors.StripeError ? err.code : undefined;
if (code === 'duplicate_meter_event') {
// Stripe already has it: we crashed after sending, before marking. Fall through and mark it.
} else if (err instanceof Stripe.errors.StripeError && (err.statusCode === 429 || err.statusCode === 409)) {
return; // rate limit or a concurrent call for this customer: the next run picks up from here
} else if (err instanceof Stripe.errors.StripeInvalidRequestError) {
// Stripe will never accept this one (too old, no customer, bad value). Park it and alert.
await pool.query('UPDATE usage_events SET failed_at = now(), error = $2 WHERE id = $1', [row.id, code ?? err.message]);
continue;
} else {
throw err; // network or 5xx: retry on the next run with the same identifier
}
}
await pool.query('UPDATE usage_events SET reported_at = now() WHERE id = $1', [row.id]);
}
}
Why it's built this way:
- The row ID is the identifier. If the job crashes after Stripe accepts an event but before
reported_atis saved, the next run sends the same identifier. Stripe enforces uniqueness over a rolling 24 hours and answers400 duplicate_meter_event, which the job treats as "already sent". - One instance at a time. Stripe allows one concurrent meter event call per customer per meter, and returns
409 too_many_concurrent_requestsotherwise. A single worker, such as a BullMQ repeatable job with concurrency 1 or a cron on one machine, avoids it and keeps the job simple. - Limits. In live mode the endpoint takes 1,000 calls per second per account, separate from your global rate limit; in a sandbox, calls count against the normal limit. Past that, pre-aggregate (one event per customer per minute, with an identifier built from customer and minute), or use meter event streams for up to 10,000 events per second.
- Values are strings of whole numbers. Payload values are strings, the v2 endpoint rejects anything but a positive integer, and since April 2026 Stripe rejects values with more than 15 significant digits. Count credits in whole units.
On Metronome, only the call changes. Add u.account_id to the query and send each row to the ingest API, with the row ID as transaction_id:
const res = await fetch('https://api.metronome.com/v1/ingest', {
method: 'POST',
headers: { Authorization: `Bearer ${process.env.METRONOME_API_TOKEN}`, 'Content-Type': 'application/json' },
body: JSON.stringify([
{
transaction_id: row.id, // Metronome's de-duplication key: the same row, the same ID
customer_id: row.account_id, // set as the customer's ingest alias in Metronome
event_type: 'ai_credits',
timestamp: row.occurred_at.toISOString(),
properties: { credits: row.quantity },
},
]),
});
if (!res.ok) throw new Error(`Metronome ingest failed: ${res.status}`);
Metronome's quickstart takes up to 100 events per request and timestamps from the last 34 days. It says a repeated transaction_id won't double-bill, but doesn't state for how long, so the ledger's unique key still does the real work.
Late, duplicate and wrong usage#
Usage data is messy at the edges. These are the cases to design for, with what Stripe does in each (recording usage, grace periods):
| What happens | What Stripe does | What you do |
|---|---|---|
| The same action is recorded twice | Nothing; it never reaches Stripe | The ledger's unique key drops the second insert |
| The same row is sent twice | 400 duplicate_meter_event within a rolling 24 hours |
Mark the row as sent |
| A row is still unsent after an hour | Nothing yet | Alert: your reporter is stuck |
| Usage arrives after the period ends | Included if it lands before the invoice finalizes: 1 hour by default, up to 72 hours | Set a grace period longer than your reporter's worst delay |
| Usage arrives after the invoice finalized | Accepted into meter totals, but not added to that invoice or the next | Alert, and bill or forgive it by hand |
| The timestamp is over 35 days old or 5+ minutes in the future | Rejected | Park the row and investigate |
| The wrong amount was sent | Nothing, until you cancel the event by identifier | Cancel, then send a corrected row with a new identifier |
| Stripe rejects an event later | Sends a v1.billing.meter.error_report_triggered thin event |
Alert and fix the source row |
Cancelling is one call. Do it before the period's invoice finalizes, because a finalized invoice won't change:
await stripe.billing.meterEventAdjustments.create({
event_name: 'ai_credits',
type: 'cancel',
cancel: { identifier: wrongRow.id },
});
Error reports arrive as thin events on their own event destination, with its own signing secret:
const notification = stripe.parseEventNotification(rawBody, signature, process.env.STRIPE_THIN_WEBHOOK_SECRET!);
if (notification.type === 'v1.billing.meter.error_report_triggered') {
const event = await notification.fetchEvent();
console.error('Stripe rejected meter events', event.data.developer_message_summary, event.data.reason.error_types);
}
Showing usage to customers#
Stripe processes meter events asynchronously, so its meter summaries and preview invoices may not include the last few events. That's how you get "the app says 9,800, Stripe says 10,400": two systems, read at different moments. The fix is to show one number: yours.
const INCLUDED = 10_000;
const CENTS_PER_CREDIT = 0.2;
export async function usageThisPeriod(pool: Pool, accountId: string, periodStart: Date) {
const { rows } = await pool.query<{ used: string }>(
`SELECT coalesce(sum(quantity), 0) AS used
FROM usage_events
WHERE account_id = $1 AND occurred_at >= $2`,
[accountId, periodStart],
);
const used = Number(rows[0].used);
const overage = Math.max(0, used - INCLUDED);
return { used, included: INCLUDED, estimatedOverageCents: Math.round(overage * CENTS_PER_CREDIT) };
}
Take periodStart from the subscription item's current_period_start, saved when customer.subscription.updated arrives; since API version 2025-03-31.basil the period dates live on subscription items, not on the subscription. For an "estimated next invoice" panel, stripe.invoices.createPreview({ subscription }) returns Stripe's view; label it as an estimate.
Limits are yours to enforce. Stripe meters usage; it doesn't stop it. If a plan has a hard cap, check the ledger before doing the work. Stripe's usage alerts (up to 25 per customer per meter) are good for "you've used 80%" emails and upsell nudges, not for blocking requests.
Credits and prepaid usage#
Stripe's credit grants give a customer a money balance that pays for metered usage, either paid or promotional:
await stripe.billing.creditGrants.create(
{
customer: customerId,
name: 'Launch credit',
category: 'promotional',
amount: { type: 'monetary', monetary: { currency: 'usd', value: 1000 } }, // $10.00
applicability_config: { scope: { price_type: 'metered' } },
expires_at: Math.floor(Date.UTC(2027, 0, 1) / 1000),
},
{ idempotencyKey: `launch-credit-${accountId}` },
);
Know the rules before you sell credits this way:
- Credits apply only when an invoice finalizes, and only to metered prices reported through meters. A customer can use more than their balance during the month; the difference is simply billed.
- A customer can hold up to 100 unused grants.
- They're not stored value. Stripe prohibits using them as gift cards, digital-wallet balances or for third-party purchases.
If you need credits that run out, where a customer buys 50,000 credits and usage stops at zero, you have two options. Use Metronome's prepaid commits, or keep the balance yourself: sell credit packs as one-time Checkout payments, add credits from the verified webhook, and deduct from your ledger as work happens. That second shape is the one I worked on for Flaps10's block hours: pilots buy packages of flight hours up front, and the balance lives in the app's database, not in Stripe. The screens are on the Flaps10 project page.
Invoices and proration#
The hybrid invoice is easy to read once you know the rhythm: the plan bills in advance, usage bills in arrears. At signup the customer pays $49 for the first month. At each renewal, one invoice carries the next month's $49 and last month's overage.
The edges:
- Plan changes. The licensed part prorates as usual. The metered part has nothing to prorate; it bills what was used.
- Price changes mid-cycle. In flexible billing mode, usage is billed at the price in effect when it was reported; in classic mode, only usage since the change is billed, at the new price. Stripe's example: 1,000 calls before a change and 500 after bill $1.75 in flexible mode but $0.75 in classic. Also, after a mid-cycle price change, usage reported during the grace period is dropped in both modes. My rule: change metered prices at renewal, with a subscription schedule.
- Removing the metered item mid-period. Flexible mode bills the unbilled usage; classic mode doesn't.
- The grace period. Set it in the Dashboard under invoice settings, with a rule for invoices that have a metered price. Long enough to cover your reporter's delays, and no longer than your billing period.
Testing with the Stripe CLI#
Forward normal webhooks and thin events to your machine, in two terminals:
stripe listen --forward-to localhost:3000/webhooks/stripe
stripe listen --forward-thin-to localhost:3000/webhooks/stripe-thin \
--thin-events "v1.billing.meter.error_report_triggered,v1.billing.meter.no_meter_found"
stripe trigger v1.billing.meter.error_report_triggered
Then test the failure cases, not just the happy path:
- Report the same row twice. The second call should return
duplicate_meter_event, and the row ends up marked as sent. - Kill the reporter between sending and marking. Restart it; nothing should be billed twice.
- Insert a row dated 40 days ago. It should be parked with an error, not retried forever.
- Compare your billing page with
invoices.createPreviewa few minutes after a burst of usage. - Walk a subscription through a renewal with a test clock, to see the invoice and your
invoice.paidhandling:
const now = Math.floor(Date.now() / 1000);
const clock = await stripe.testHelpers.testClocks.create({ frozen_time: now, name: 'pro renewal' });
const customer = await stripe.customers.create({
email: 'renewal-test@example.com',
test_clock: clock.id,
payment_method: 'pm_card_visa',
invoice_settings: { default_payment_method: 'pm_card_visa' },
});
await stripe.subscriptions.create({
customer: customer.id,
items: [{ price: proMonthlyId }, { price: proCreditsId }],
billing_mode: { type: 'flexible' },
});
await stripe.testHelpers.testClocks.advance(clock.id, { frozen_time: now + 32 * 24 * 60 * 60 });
What it costs#
As of 21 October 2026, Stripe Billing charges 0.7% of billing volume on pay-as-you-go, on top of card processing fees. Metronome's Startup plan lists 0.8% of billing volume plus $0.04 per 1,000 ingested events; a million events a month adds $40. Pre-aggregating events cuts that line, and the ledger makes pre-aggregating safe. For what billing adds to a first build, see the cost to build a SaaS MVP.
Checklist#
- The pricing model is written down: unit, allowance, overage rate, and what happens at the limit
- Usage is recorded in your database, in the same transaction as the work, under a unique business key
- A single reporter sends each row with its row ID as the identifier, and treats
duplicate_meter_eventas success - Rejected rows are parked and alerted on; rows unsent after an hour raise an alert
- The grace period covers your reporter's worst delay
- Customers see usage from your ledger; the invoice preview is labelled as an estimate
- Metered price changes happen at renewal
- Duplicates, crashes, late events and renewals are tested in a sandbox
Need billing done right the first time?#
Usage billing goes wrong quietly: a double count here, a late event there, until a customer finds it on their invoice before you do. I build Stripe integrations for SaaS, from choosing the pricing model to the ledger, webhooks and tests behind it. Send me your pricing page and I'll tell you how I'd model it in Stripe, and whether you need Metronome. Email mhuzaifaa.dev@gmail.com or see the projects I've shipped.
FAQ#
How does usage-based billing work in Stripe?#
You create a meter that adds up usage, attach a metered price to it, and subscribe the customer to that price. Your backend sends meter events with the customer and a value as usage happens. At the end of each billing period, Stripe totals the events and charges them on the subscription invoice, in arrears.
Can you combine a subscription fee and usage-based pricing in Stripe?#
Yes. Put two prices on one subscription: a licensed price for the monthly plan, billed in advance, and a metered price for usage, billed in arrears. To include an allowance, make the metered price graduated and tiered, with the first tier free up to the included amount.
How do you stop Stripe from billing usage twice?#
Record each billable action once in your own database, under a unique key built from the action, such as the report ID. Then report each row with its ID as the meter event identifier. Stripe rejects a repeated identifier within a rolling 24 hours, so a resend after a crash isn't counted again.
Does Stripe still support usage records?#
No. The legacy usage-records API and aggregate_usage were removed in API version 2025-03-31.basil. Metered prices now need a meter, and usage is sent as meter events. Older integrations can still call usage records with a pinned pre-Basil API version, but new code should use meters or Metronome.
Should I use Stripe Billing Meters or Metronome?#
Stripe recommends Metronome for new usage-based integrations, and it's the better fit for prepaid credits that stop at zero, enterprise contracts, prices that vary by model or region, and high event volume. For one plan plus a simple overage sold through Checkout, Billing Meters remain fully supported and keep everything in Stripe.
Why doesn't Stripe's usage total match my app?#
Stripe processes meter events asynchronously, so meter summaries and preview invoices can miss the most recent events. Your app may also count usage that hasn't been reported yet. Show customers usage from your own ledger, and treat Stripe's numbers as the billing record once the invoice finalizes.

