Usage-based billing
Report metered usage with usage.report. Provider support, lists of events, the deliberate no-retry rule, idempotency keys, backdating windows, and Subscription.meters.
Metered pricing bills for what a customer consumed, so the provider needs a stream of usage events from
your application. client.usage.report sends a list of events. Each event goes to the meter that
matches its eventName.
await client.usage.report({
events: [
{
customerId: 'cus_123',
eventName: 'api_request',
value: 25,
metadata: { region: 'eu' },
idempotencyKey: 'evt_abc',
timestamp: new Date(),
},
],
});
It resolves to void: providers acknowledge ingestion, they do not hand back a usage record.
Parameters
events?UsageEvent[]
The events to report. More than one event needs the usageBatchReporting capability. An empty list sends no request.
UsageEvent[]signal?AbortSignal
Abort the request.
AbortSignalEach UsageEvent takes these fields:
customerId?string
The provider's customer identifier — Customer.id or Subscription.customerId, never your own user ID.
stringeventName?string
The meter event name. It must match the meter configuration exactly — providers match case-sensitively.
stringvalue?number
Shorthand for a value entry in the event properties, the key meters aggregate on by default.
numbermetadata?Record<string, string | number | boolean>
Event properties the meter can filter or aggregate on.
Record<string, string | number | boolean>idempotencyKey?string
Deduplicates replays. Sent as external_id (Polar), identifier (Stripe), event_id (Dodo Payments).
stringtimestamp?Date
When the usage occurred. Defaults to receipt time; the accepted window differs sharply per provider.
DateThe client checks every event in the list before any request is made. It rejects an empty
customerId, an empty eventName, and any non-finite number with RevenueError { code: 'validation' },
whether the number arrives as value or as a numeric metadata entry. The error message names the
position of the bad event, for example events[3].value. Every numeric entry is checked, not just
value, because a meter aggregates on a key you configure: a NaN under any name is a corrupted billed
quantity, and it would otherwise reach the provider as null or "NaN". A provider without the
usageReporting capability throws unsupported, also before any request.
value versus metadata
value is shorthand for a value entry in the event properties — the key every provider’s meters
aggregate on by default. These two calls send the same payload:
await client.usage.report({ events: [{ customerId, eventName: 'api_request', value: 25 }] });
await client.usage.report({
events: [{ customerId, eventName: 'api_request', metadata: { value: 25 } }],
});
An explicit value wins over a metadata.value. Everything else in metadata is passed through
untouched, which is what meter filters and non-default aggregation keys read.
Provider support
Usage reporting is gated by the usageReporting capability, and a list of more than one event by the
usageBatchReporting capability. The capability matrix has both
values for every provider.
| Provider | usageReporting |
Endpoint | Customer key | Idempotency parameter |
|---|---|---|---|---|
| Polar | true |
POST /v1/events/ingest |
customer_id |
external_id — permanent unique index |
| Lemon Squeezy | false |
— | — | — |
| Stripe | true |
POST /v1/billing/meter_events |
payload[stripe_customer_id] |
identifier — rolling window of at least 24 h |
| Paddle | false |
— | — | — |
| Dodo Payments | true |
POST /events/ingest |
customer_id |
event_id — required by the API |
if (client.capabilities.usageReporting) {
await client.usage.report({ events: [{ customerId, eventName: 'api_request', value: 1 }] });
}
Lemon Squeezy and Paddle have no safely idempotent ingestion upstream, so usageReporting is false
there and usage.report throws unsupported — see Lemon Squeezy and
Paddle. Polar caps metadata and can key events by your own customer ID; see
Polar.
Reporting many events
Polar and Dodo Payments take the whole list in one request. A job that reports one event per customer makes one call, not one call per customer:
await client.usage.report({
events: customers.map((customer) => ({
customerId: customer.id,
eventName: 'api_request',
value: customer.requestCount,
idempotencyKey: `api_request:${customer.id}:${periodStart}`,
})),
});
Polar checks the whole list before it stores anything. If one event names a customer Polar does not
know, Polar refuses the request, none of the events is recorded, and the call rejects with
RevenueError { code: 'validation' }.
POST /v1/billing/meter_events, the Stripe endpoint the SDK uses, records one meter event per call, so
usageBatchReporting is false for Stripe. A list with more than one event throws unsupported
before any request, and a list of one still works. Portable code
checks the capability and falls back to one call per event:
if (client.capabilities.usageBatchReporting) {
await client.usage.report({ events });
} else {
for (const event of events) {
await client.usage.report({ events: [event] });
}
}
An empty list sends no request. The SDK never splits a list, so keep each call within the provider’s limit. Dodo Payments takes at most 1,000 events per call.
Usage writes are never retried
Every other client method gets one bounded rate_limited retry. usage.report
deliberately bypasses it.
If you want retries, own them — and pass a stable idempotencyKey that does not change between
attempts:
import { RevenueError } from 'revenue-sdk';
const idempotencyKey = crypto.randomUUID(); // generated once, reused by every attempt
for (let attempt = 0; ; attempt++) {
try {
await client.usage.report({
events: [{ customerId, eventName: 'api_request', value: 1, idempotencyKey }],
});
break;
} catch (error) {
if (attempt === 2 || !(error instanceof RevenueError) || !error.retryable) {
throw error;
}
await sleep((error.retryAfter ?? 2 ** attempt) * 1000);
}
}
A key derived from the thing you are billing for — a request ID, a job ID, a log line ID — is better than a random one: it also deduplicates across process restarts and queue redeliveries.
When you retry a list, every event needs its own stable key, unique per event. A failed call may have been recorded anyway, and the keys are what stop the replay from billing those events twice. A key shared by several events makes the provider keep one of them and drop the rest as duplicates.
Backdating windows differ sharply
timestamp is not portable. The three supporting providers disagree on how far into the past an event
may be dated, and on what a backdated event means for money:
| Provider | Accepted timestamp |
Out of range | What timestamp affects |
|---|---|---|---|
| Polar | any past timestamp | accepted | reporting only — never the invoice |
| Stripe | past 35 calendar days, up to 5 minutes ahead | error | which billing period the usage lands in |
| Dodo Payments | past 1 hour, up to 5 minutes ahead | 400 → validation |
which billing period the usage lands in |
Dodo Payments is the one to design around: a queue that has been down for two hours has lost its
billable window, and there is no way to backfill it. Omitting timestamp — reporting at the moment the
usage happens — is the only behavior that is the same everywhere.
Reading usage back: Subscription.meters
Subscription carries an optional meters array with the current period’s usage per meter. When the
product has a meter cycle, this period runs from currentMeterPeriodStart to currentMeterPeriodEnd.
Otherwise it is the billing period.
const subscription = await client.subscriptions.get({ id: 'SUBSCRIPTION_ID' });
for (const meter of subscription.meters ?? []) {
console.log(meter.name, meter.consumedUnits, meter.amount);
}
id?string
The meter's identifier.
stringname?string
The meter name as configured in the provider.
stringconsumedUnits?number
Units consumed in the current meter period.
numbercreditedUnits?number
Units granted upfront — an included allowance or credits.
numberamount?number
Amount accrued for this meter so far this period, in the currency's minor units.
numberraw?unknown
The untouched provider payload.
unknownTesting
The in-memory provider records every reported event on state.usageEvents, so you can assert on what
your code would have billed. capabilities: { usageReporting: false } exercises the Lemon Squeezy and
Paddle fallback path, and capabilities: { usageBatchReporting: false } the Stripe one. See
Testing provider.
Out of scope
- Meter CRUD and management — configure meters in the provider dashboard.
- Reading usage back beyond Polar’s inline
Subscription.meters; there is nousage.getCurrent. - Normalized amounts for metered and tiered prices —
Price.amountstaysnulloutsidefixed, see Products & prices. - Splitting a long list into calls that fit a provider’s limit.
- Tier tables and seat management.