> ## Documentation Index
> Fetch the complete documentation index at: https://docs.retempo.xyz/llms.txt
> Use this file to discover all available pages before exploring further.

# Record Usage Events for Metered API and Agent Billing

> Track subscriber API usage in Retempo by recording usage events. Sum them yourself to compute invoice amounts for usage-based billing plans.

Usage events are the core metering mechanism behind usage-based billing in Retempo. Every time a subscriber consumes a unit of your service — whether that's an API call, a generated token, or a gigabyte of stored data — you record a usage event. Those events accumulate against a subscription throughout the billing period, giving you a precise, auditable record of exactly what each subscriber consumed. At billing time, you sum those events yourself and pass the computed total to `POST /api/v1/invoices`.

## What is a usage event?

A usage event represents a single metered action taken by a subscriber. Each event captures two key pieces of information:

* **`eventKey`** — a string identifier for the *type* of action (e.g. `'token_generated'`, `'api_request'`, `'gb_stored'`). You define these keys to match the billable dimensions of your service.
* **`quantity`** — the number of units consumed in this event (e.g. `1000` tokens, `5.25` gigabytes, `1` API call).

Every usage event is tied to a specific subscription via `subscriptionId`, and to the service and subscriber via `serviceId` and `userId`. The subscription must be in an **ACTIVE** state before you can record events against it.

For **USAGE\_BASED** plans, usage events are the source of truth for what gets billed — you sum the event quantities at the end of the billing period, compute the invoice amount, and create the invoice with that value. Retempo stores the amount you provide; it does not automatically aggregate events into an invoice. For **FIXED\_RECURRING** plans, you can still record usage events for analytics and visibility, but they do not affect the billed amount.

## Recording a usage event

Send a `POST` request to `/api/v1/usage-events` each time a subscriber consumes a unit of your service. The required fields are `serviceId`, `subscriptionId`, `userId`, `eventKey`, and `quantity`. The optional `occurredAt` timestamp defaults to the current time if you omit it; `invoiceId` is also optional and lets you link the event to a specific invoice.

```curl theme={null}
curl --request POST \
  --url https://api.retempo.xyz/api/v1/usage-events \
  --header 'Authorization: Bearer <YOUR_API_KEY>' \
  --header 'Content-Type: application/json' \
  --data '{
    "serviceId": "svc_ai_token_api",
    "subscriptionId": "sub_9f3a2c1d",
    "userId": "usr_b4e7f812",
    "eventKey": "api_request",
    "quantity": 100
  }'
```

A successful response returns the created usage event object with all resolved relationships:

```json theme={null}
{
  "usageEvent": {
    "id": "ue_4d8c1e7b",
    "serviceId": "svc_ai_token_api",
    "subscriptionId": "sub_9f3a2c1d",
    "userId": "usr_b4e7f812",
    "invoiceId": null,
    "eventKey": "api_request",
    "quantity": "100",
    "occurredAt": "2025-01-15T14:32:00.000Z",
    "createdAt": "2025-01-15T14:32:01.847Z",
    "service": {
      "id": "svc_ai_token_api",
      "name": "AI Token API"
    },
    "subscription": {
      "id": "sub_9f3a2c1d",
      "status": "ACTIVE"
    },
    "user": {
      "id": "usr_b4e7f812"
    },
    "invoice": null
  }
}
```

**Validation rules:**

* The `subscriptionId` must belong to both the given `serviceId` and `userId`. Mismatches return a validation error.
* If you supply an `invoiceId`, it must be associated with the same service and user.
* The subscription must be `ACTIVE` at the time of the request.

<Tip>
  Record usage events as they occur rather than batching them to keep your billing data accurate and real-time.
</Tip>

## Linking events to invoices

The optional `invoiceId` field lets you attach a usage event directly to an existing invoice. This is useful when you want to pre-associate events with a specific billing period or invoice as they happen, rather than looking them up at invoice-creation time.

```curl theme={null}
curl --request POST \
  --url https://api.retempo.xyz/api/v1/usage-events \
  --header 'Authorization: Bearer <YOUR_API_KEY>' \
  --header 'Content-Type: application/json' \
  --data '{
    "serviceId": "svc_ai_token_api",
    "subscriptionId": "sub_9f3a2c1d",
    "userId": "usr_b4e7f812",
    "invoiceId": "inv_7c2a9e1f",
    "eventKey": "token_generated",
    "quantity": 50000,
    "occurredAt": "2025-01-15T14:30:00.000Z"
  }'
```

<Warning>
  Retempo does **not** automatically sum usage events into an invoice amount. Whether or not you attach an `invoiceId`, you are responsible for computing the total from your recorded events and passing it as `amount` when you call `POST /api/v1/invoices`.
</Warning>

<Note>
  Each combination of `subscriptionId` + `eventKey` must be unique. Use distinct `eventKey` values for different action types on the same subscription. For example, if a subscriber generates tokens and makes API requests, record separate events with `token_generated` and `api_request` rather than reusing the same key.
</Note>

## Common eventKey patterns

Choose `eventKey` values that clearly describe the billable action and map directly to the pricing dimensions of your service. Retempo does not enforce a fixed schema — you define the keys that make sense for your product.

Here are common patterns used by API providers and AI agent services:

| `eventKey`        | Description                             | Example `quantity` |
| ----------------- | --------------------------------------- | ------------------ |
| `api_request`     | A single inbound API call               | `1`                |
| `token_generated` | Tokens produced by an LLM               | `8192`             |
| `token_consumed`  | Total tokens processed (input + output) | `12500`            |
| `gb_stored`       | Gigabytes of data stored                | `2.75`             |
| `gb_transferred`  | Gigabytes of data transferred out       | `0.5`              |
| `task_completed`  | A discrete agent task or job run        | `1`                |
| `image_rendered`  | Images generated or processed           | `25`               |
| `compute_second`  | Seconds of compute time consumed        | `300`              |

When you have multiple independent billable dimensions — for example, both storage and egress — record a separate usage event for each `eventKey` in the same request cycle. This keeps your billing data granular and lets you price each dimension independently.
