Subscription billing

Usage-based billing: meter it, dedupe it, close it on time

With a flat plan, a bug in your billing code charges the wrong customer. With usage billing, a bug in your event pipeline charges every customer the wrong amount, and nobody notices until one of them reads the invoice more carefully than you did. Here's how metering, aggregation and invoicing fit together, what Stripe's Meters API expects now that usage records are gone, and how to handle the event that arrives twice or after the invoice, with the metering material from chapters 7 and 24.

Usage-based billing (metered billing) charges a customer for what they consumed in a billing period rather than a fixed price: API calls, tokens, gigabytes, minutes. The price is easy. The pipeline behind it is the product: every unit has to be recorded once, counted once, attributed to the right customer and the right period, and turned into an invoice line the customer can check.

It breaks into four stages, and each one has its own way to lose money:

StageWhat it doesHow it goes wrong
MeteringRecords each usage event at the source, with a unique id and the time it happenedDropped events under-bill; retried events double-bill
AggregationRolls events up per customer, per meter, per period (sum, count, or last value)Events stamped with arrival time land in the wrong period
RatingApplies the price: per unit, tiered, included allowance, creditsVolume tiers make a bigger month cheaper; see pricing models
InvoicingCloses the period and bills itUsage that arrives after the invoice finalizes is billed nowhere

Stripe: meters, not usage records

If your code calls SubscriptionItem.create_usage_record, it was written for an API that no longer exists. API version 2025-03-31.basil removed the UsageRecord and UsageRecordSummary resources and the aggregate_usage parameter, and a metered price now has to name a meter (Stripe changelog). Older versions still work if you pin them, and Stripe has a migration guide. The current shape, checked 14 November 2026:

  • A meter defines what you count and how it aggregates over the period: sum of values, count of events, or the last value reported. You can't change a meter's configuration after creating it, apart from its display name (Stripe).
  • A meter event reports usage against the meter by event_name, with the customer id and a numeric value in its payload and an optional identifier and timestamp (API reference).
  • A metered price attaches to the meter and goes on the subscription like any other price.

Stripe processes meter events asynchronously, so the upcoming invoice can lag what you just sent. Errors don't come back on the request: a bad customer id or an out-of-range timestamp turns up later as a v1.billing.meter.error_report_triggered event, so subscribe to it and alert on it (Stripe).

The rules that decide what gets billed

From Stripe's usage and grace-period docs, checked 14 November 2026:

RuleValueWhat it means for you
Event timestamp windowPast 35 calendar days to 5 minutes in the futureOlder usage is rejected outright
Identifier uniquenessEnforced over "a rolling period of at least 24 hours"Protects quick retries, not a replay from last week
Invoice finalization grace period1 hour by default, configurable up to 72 hoursThe time you have after the period ends to send its usage
Usage after finalizationAccepted into meter summaries, not added to that invoice or the next oneLate usage is unbilled unless you bill it yourself
Cancelling an eventOnly for events sent in the last 24 hours, by identifierAfter that, correct with a negative value
Live-mode rate limit1,000 calls a second per account, one concurrent call per customer per meterPre-aggregate, or use v2 meter event streams (10,000 events a second)

Two of those catch people out. First, the 35-day window is about acceptance, not billing: Stripe says it "doesn't guarantee that Stripe can include the usage on an invoice" (Stripe). Second, the grace period only applies to subscription cycle invoices and schedule phase transitions, and if the subscription item's price changed mid-cycle, usage sent during the grace period doesn't appear on any invoice at all (Stripe).

Sending a meter event safely

The pattern that survives retries: write each usage event to your own table first, in the same transaction as the work it measures, with a unique id and the time it happened. A worker sends unsent rows to Stripe using that id as the identifier. A retry sends the same id, so Stripe's uniqueness check drops the duplicate, and your own sent flag covers anything older than Stripe's 24-hour window.

import stripe


def send_usage(event: dict) -> None:
    """Send one stored usage event to Stripe. Safe to call twice.

    event comes from your own usage table, where it was written with a unique
    id in the same transaction as the work it measures.
    """
    try:
        stripe.billing.MeterEvent.create(
            event_name="api_requests",
            payload={
                "stripe_customer_id": event["stripe_customer_id"],
                "value": str(event["quantity"]),
            },
            identifier=event["id"],          # same id on every retry
            timestamp=event["occurred_at"],  # when it happened, not when sent
        )
    except stripe.RateLimitError:
        raise  # leave it unsent; the worker backs off and retries
    except stripe.InvalidRequestError as e:
        mark_failed(event["id"], str(e))  # bad customer or too old: a human looks
        return
    mark_sent(event["id"])

If a customer makes thousands of calls a minute, don't send thousands of events. Sum them per customer per minute or hour in your table and send one event per bucket, with the bucket's key as the identifier. Stripe's own advice for the rate limit is the same: pre-aggregate (Stripe).

Late usage and the invoice cutoff

Pick the policy before the first late event, not during the support ticket that follows it:

  • Close on a schedule. Run the period's last batch well inside the grace period. If your batch job runs nightly, the 1-hour default is too short; set a longer grace period for invoices with metered prices (Stripe lets you scope the rule that way, up to 72 hours).
  • Carry forward what misses. For usage that lands after finalization, add it to the next invoice yourself as a labeled "usage from previous period" invoice item, because Stripe won't. Chapter 24 recommends exactly this.
  • Reconcile at close. Compare the period's total in your table against Stripe's meter summary and an independent count such as request logs. A gap is a billing incident, not a rounding error.

Disputes over usage

Customers don't dispute the unit price. They dispute the quantity, usually because the first time they saw it was on the invoice. What prevents most of them:

  • Show usage while it accrues, in your dashboard, from the same records you bill from.
  • Alert before the bill does. Chapter 7 suggests alerts at 50%, 80% and 100% of typical usage; chapter 24's engine fires at 75%, 90% and 100% of a plan limit. Either works. Silence doesn't.
  • Offer a hard cap for customers who'd rather be cut off than surprised.
  • Keep raw events for at least as long as the customer can dispute the invoice, so you can show the line items behind the total. A card dispute over a usage bill is still a chargeback, and a usage log is your evidence.

What it costs on Stripe

Stripe Billing is 0.7% of Billing volume on pay-as-you-go, on top of payment processing, and its pricing page says basic usage-based billing through the Meters API is included "with up to 100M events per month included". For more complex usage pricing it points to Metronome, which it describes as a Stripe product (Stripe Billing pricing, checked 14 November 2026; the page carries no date).

Duplicates, gaps, late records, credits and overage caps, and what to do about each. From chapter 24.

Metering Edge Cases

Three things go wrong with metering in production, and the sample handles none of them, which is why they get their own section.

Duplicates and gaps. Usage events travel over the same at-least-once plumbing as webhooks (Chapter 9 covers what that means), so a client that times out and retries sends the same event twice, and a failed-over queue drops one. Give every event an idempotency key from the client that generated it, store the key with the record, and reject repeats on insert. The sample has nowhere to put that key except metadata, and nothing checks it. At period close, reconcile the sum of records against an independent count such as request logs, and treat a gap as a billing incident rather than a rounding error.

Late records. The engine stamps each record when it's recorded, not when the usage happened, and for a batch job that reports yesterday's usage overnight that's wrong by a day. At period end, wrong by a day means the wrong invoice, so carry the event's own timestamp and decide what happens to a record that lands after its period has been invoiced. You can hold every invoice for a closing window, bill late usage on the next invoice as its own labeled line, or drop it. Hold-then-carry-forward is the usual answer: a short close window catches most stragglers, and a visible "usage from previous period" line explains the rest without reissuing an invoice.

Credits and overages. The hybrid in the callout needs an included quantity that the rating step subtracts before pricing, and prepaid credits are the same subtraction in reverse, drawn down from a balance bought up front. Enforcement lives at the 100% alert: a hard limit rejects requests and protects the customer from a runaway bill, while a soft limit keeps serving and bills the overage. The first protects you from a dispute; the second protects revenue and the customer's uptime. Make it a per-customer setting, because the customer who'd rather be cut off and the one who'd rather never be cut off are both right.

The four usage pricing patterns and the infrastructure each one needs underneath. From chapter 7.

Metered/Usage-Based Billing

Usage-based billing charges for what the customer actually consumed instead of a flat fee. It's also where surprise bills come from.

Usage-based billing aligns cost with value and hands you four new problems: real-time metering, accurate aggregation, surprise bills for customers, and revenue you can't forecast. AWS, Twilio, and Stripe make it work, but only with infrastructure that tracks and aggregates every usage event accurately.

Four pricing patterns cover most of what you'll see:

Pure usage (Twilio, AWS S3): customer pays per unit consumed (per SMS, per GB-hour). No base fee. Simple to communicate, but creates revenue volatility for you and bill volatility for the customer.

Subscription + usage overage (most CRMs): a base monthly fee covers the typical-usage tier. Above the threshold, per-unit overage charges kick in. This is the most common B2B SaaS model because it gives both parties predictability for the typical case and fair pricing for outliers.

Tiered usage (most cloud APIs): per-unit price drops at higher volumes. The first 100K calls cost X, the next 1M cost Y, above 10M they cost Z. Aligns price with customer scale.

Credit-based prepay: customer buys a credit balance up front; usage draws down from it. Common in AI/ML APIs because GPU costs are uneven and you want cash up front.

The infrastructure problem. Usage-based billing only works if your metering is accurate. That means:

  • Real-time event capture (every API call, every database row, every GB transferred) with at-least-once delivery semantics.
  • Idempotent aggregation - the same event must never be counted twice if your stream replays.
  • A query layer fast enough to surface "how much have I used this month" inside the customer's dashboard without bringing your database down.
  • Reconciliation jobs that compare metered usage to billed usage at end of cycle, because off-by-one errors at 100M-event scale are a customer support nightmare.
  • A billing-cycle close-out window (24-48 hours) where late-arriving events still get counted toward the right period.

Pricing trap to avoid. Don't price units in fractional cents and then send invoices that look like spreadsheet errors. Round per-line-item totals to a clean amount (cent for USD/EUR, hundredth-yen, etc.). Show the unit math in supporting documentation, not in the headline charge.

Bill shock kills usage-based products. Send proactive alerts when a customer crosses 50%, 80%, and 100% of typical usage, and let them set hard caps. A customer who got a $5,000 surprise bill never trusts your billing again, even if it was technically correct.

Implementation: src/examples/7-subscriptions-recurring-billing/billing_engine.py

Before you ship metered billing

  • Every usage event gets a unique id and its own timestamp at the source, not at the point you send it.
  • The sender uses that id as the meter event identifier, and marks rows sent only after Stripe accepts them.
  • Something listens for v1.billing.meter.error_report_triggered and pages a person.
  • The finalization grace period is longer than your slowest usage batch.
  • Late usage has a written policy and a code path: next invoice, labeled.
  • A period-close job reconciles your totals against Stripe's.
  • Customers can see their usage, and get an alert before the bill does.

Retries on the request side are covered in idempotency keys; the subscription object your metered price sits on is in Stripe subscriptions. Usage revenue doesn't belong inside MRR the way a flat fee does; the MRR calculator shows how to count it.

Questions

What is usage-based billing?

Usage-based (metered) billing charges a customer for what they consumed in a billing period, such as API calls, tokens or gigabytes, instead of a fixed price. It runs as four stages: metering, aggregation, rating and invoicing.

Does Stripe still support usage records?

Not on current API versions. Version 2025-03-31.basil removed the UsageRecord and UsageRecordSummary resources and the aggregate_usage parameter, and metered prices now need a meter. You report usage with meter events. Older API versions still work if you pin them, and Stripe publishes a migration guide.

How do I stop Stripe double-counting usage?

Give every meter event a unique identifier from your own system and send the same identifier on every retry. Stripe enforces uniqueness over a rolling period of at least 24 hours, so also keep a sent flag in your own usage table for anything older.

What happens to usage reported after the invoice is finalized?

Stripe accepts it into meter summaries if the timestamp is within the past 35 days, but doesn't add it to the finalized invoice or the next one. The default finalization grace period is 1 hour, configurable up to 72 hours. Usage that misses it has to be billed by you, for example as a labeled line on the next invoice.

How much does Stripe usage-based billing cost?

Stripe Billing is 0.7% of Billing volume on pay-as-you-go, on top of payment processing, and Stripe's pricing page says basic usage-based billing through the Meters API is included with up to 100M events per month, checked 14 November 2026.

What the book adds

What chapters 7 and 24 add

  • A usage engine that records fast and rates reproducibly
  • Per-unit, tiered, volume and graduated rating in one code path
  • Usage alerts that fire once, not once per request
  • Included quantities, prepaid credits and overage caps
  • Proration for the flat part of a hybrid plan

30-day money-back · Instant PDF and EPUB

All 42 chapters