RecordUsage is the action you call each time a billable consumes units under a metered plan. It persists a usage record to subscribd_usage_records and forwards the report to the configured gateway. At the end of each billing period, the gateway sums all reported units and produces the final invoice. This pattern is suited to API call billing, cloud resource consumption, or any service measured in discrete units.
When to call RecordUsage
CallRecordUsage at the point of consumption — typically at the end of a queued job, after an API request completes, or in a batch at regular intervals. You must have a SubscriptionItem reference to pass to the action. Retrieve it from the subscription.
execute() signature
| Parameter | Type | Required | Description | |
|---|---|---|---|---|
$subscriptionItem | SubscriptionItem | Yes | The subscription item associated with the metered plan | |
$units | int | Yes | Number of units consumed in this report | |
$idempotencyKey | `string | null` | No | A unique key to prevent duplicate records on retries |
Full example
Idempotency
Passing anidempotencyKey prevents the same usage from being counted twice if the action is called more than once with identical arguments — for example, when a job is retried after a transient failure.
- If no record with that key exists, the usage is recorded normally.
- If a record with the same key already exists, the call is a no-op and the existing record is returned.
- Concurrent calls with the same key are handled safely — only one record is saved regardless of race conditions.
When you omit
idempotencyKey, each call creates a new record. This is appropriate for batch-style reporting where each call represents a distinct consumption event, but risky in job contexts where retries are possible.Relation to the metered plan rule
RecordUsage is only meaningful on subscriptions backed by a plan with 'rule' => 'metered'. The plan’s rule_config.unit_price defines the per-unit charge that the gateway applies when summing usage at period end.
Getting the subscription item
TheSubscriptionItem model sits between the Subscription and the gateway’s line-item representation. For metered plans there is typically one item per subscription.