# Send usage (/docs/usage-billing/send-usage)

Your server sends usage events to the usage meter at `https://usage.comecero.com/v1/events`, with a [usage key](/docs/usage-billing/set-up#5-create-a-usage-key) in the `Authorization` header. Send events as they happen or in batches of up to 1,000. Each event is counted right away, in the UTC hour of its `timestamp`.

<Callout type="warn">Call the usage meter from your server only. It does not answer browsers (it sends no CORS headers), and a usage key must never be in a web page or mobile app.</Callout>

## Send events [#send-events]

````bash
curl -X POST https://usage.comecero.com/v1/events \
  -H "Authorization: Bearer $COMECERO_USAGE_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "events": [
      {
        "operation_id": "req_7Hk2p9",
        "external_customer_id": "cust_8412",
        "metric_key": "ai_tokens",
        "quantity": "1250",
        "timestamp": "2026-11-01T09:41:07Z",
        "properties": { "model": "large" }
      }
    ]
  }'
````

| Field | Required | What it is |
| --- | --- | --- |
| `operation_id` | Yes | Your id for this usage, for example the id of the request or job that used it. 1 to 128 letters, digits, `_`, `.`, `:` or `-`. The same `operation_id` for the same metric is counted once. |
| `external_customer_id` | Yes | Your id for the customer: the `customer_id` of their billing agreement. Same characters as `operation_id`. |
| `metric_key` | Yes | The metric's `event_key`. |
| `quantity` | Yes | How much was used, as a decimal string such as `"1250"` or `"0.75"`. At most 12 digits before the point and 6 after. No negatives. |
| `timestamp` | No | When it happened, ISO 8601 with a time zone. At most 30 days in the past and 5 minutes ahead. Defaults to the time the meter receives it. |
| `properties` | No | Up to 20 extra values, only the metric's `allowed_properties`. Strings (up to 256 characters), numbers or booleans. |

Send `quantity` as a string. A JSON number is also accepted when it prints exactly (no exponent, at most 6 decimals), but a string never loses precision.

## From your server [#from-your-server]

A small Node.js example (Node 18 or later). It sends a batch, logs events that were rejected, and resends the whole batch when the meter asks for it.

````javascript
const USAGE_URL = "https://usage.comecero.com/v1/events";

async function sendUsage(events) {
  for (let attempt = 1; attempt <= 5; attempt++) {
    let response;
    try {
      response = await fetch(USAGE_URL, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${process.env.COMECERO_USAGE_KEY}`,
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ events }),
      });
    } catch {
      response = null; // network error or timeout: resending is safe
    }

    if (response && response.status === 200) {
      const answer = await response.json();
      for (const result of answer.results) {
        if (result.status === "rejected" || result.status === "conflict") {
          console.error("usage event not counted", result);
        }
      }
      return answer;
    }

    // 429 or 5xx: resend the same batch. Events already counted come back as "duplicate".
    if (response && response.status !== 429 && response.status < 500) {
      throw new Error(`usage meter refused the request: ${response.status} ${await response.text()}`);
    }
    await new Promise((resolve) => setTimeout(resolve, 2 ** attempt * 1000));
  }
  throw new Error("usage meter did not take the batch; keep it and try again later");
}

await sendUsage([
  {
    operation_id: "req_7Hk2p9",
    external_customer_id: "cust_8412",
    metric_key: "ai_tokens",
    quantity: "1250",
    timestamp: new Date().toISOString(),
  },
]);
````

Keep events you could not send and send them later with the same `operation_id`s: anything up to 30 days old is still taken and billed. Always set `timestamp`, so a late event counts in the hour it happened.

## Check that usage arrived [#check-that-usage-arrived]

The meter counts an event for any `external_customer_id`, even one with no billing agreement. Usage is billed only when the id is the `customer_id` of an agreement, so a typo is `counted` but never billed.

To check, open **Usage Billing** in the dashboard, then **Customers**, the customer, and **Events**. Events show there a few minutes after they are counted. From your server, read [usage so far](/docs/usage-billing/follow-usage#this-period-so-far).

## Answers [#answers]

The meter answers every event, in the order you sent them.

````json
{
  "counted": 1,
  "duplicate": 1,
  "conflict": 0,
  "rejected": 1,
  "retry": 0,
  "results": [
    { "index": 0, "operation_id": "req_7Hk2p9", "status": "counted" },
    { "index": 1, "operation_id": "req_7Hk2p8", "status": "duplicate" },
    { "index": 2, "operation_id": "req_7Hk2p7", "status": "rejected", "code": "property_not_allowed", "field": "properties.region" }
  ]
}
````

| `status` | Meaning | What to do |
| --- | --- | --- |
| `counted` | Counted now. | Nothing. |
| `duplicate` | This `operation_id` was already counted for this metric with the same customer, quantity and timestamp. Not counted again. | Nothing. A resend is safe. |
| `conflict` | This `operation_id` was already counted for this metric with a different customer, quantity or timestamp. The first one stays. | Fix your ids: use a new `operation_id` for new usage. |
| `rejected` | Not counted. `code` says why and `field` says where. The value is never echoed back. | Fix the event and send it again. |
| `retry` | Not counted yet, because the meter was busy. | Resend the batch. |

The HTTP status is `200` when every event has a final answer, and `429` when any event got `retry`. Resending the whole batch is always safe: events that were counted come back as `duplicate`.

`properties` are not compared: resending an event with other properties but the same customer, quantity and timestamp is a `duplicate`. If you leave `timestamp` out, a resend is still a `duplicate`, and the event counts in the hour it first arrived.

### Request errors [#request-errors]

These answer the whole request, with no `results`. The body is `{ "error": "<code>" }`, sometimes with a `detail`.

| Status | `error` | Meaning |
| --- | --- | --- |
| `400` | `empty_body`, `invalid_json` | The body is empty or not JSON. |
| `400` | `events_missing`, `events_empty` | No `events` array, or an empty one. |
| `400` | `too_many_events` | More than 1,000 events. |
| `401` | | No `Authorization` header. The body is `{ "message": "Unauthorized" }`. |
| `403` | | The usage key is unknown, revoked, for the other mode, not active yet, or the header is not `Bearer <key>`. The body is `{ "message": "Forbidden" }`. A new key starts working within about 5 minutes, and a refused key stays refused for up to a minute after that. |
| `413` | `body_too_large` | The body is over 1 MiB. |
| `429` | `too_many_requests` | Over 5,000 events or 50 requests this second for the account. Nothing was counted: wait a second and resend. Send events in batches (up to 1,000 per request) to stay well under it. Rejected events count toward the 5,000 too. |
| `503` | `try_again` | A temporary problem. Resend the batch. |

A timeout or any `5xx` also means: resend the batch.

## What is rejected and why [#what-is-rejected-and-why]

Each rejected event has a `code`:

| `code` | Why |
| --- | --- |
| `invalid_event` | The event is not a JSON object. |
| `invalid_operation_id` | Missing, or not 1 to 128 letters, digits, `_`, `.`, `:` or `-`. |
| `invalid_external_customer_id` | Missing, or not 1 to 128 letters, digits, `_`, `.`, `:` or `-`. |
| `invalid_metric_key` | Missing, or not 1 to 64 lowercase letters, digits, `_`, `.` or `-`. |
| `unknown_metric` | No active metric with this `event_key` in this mode. The meter checks again before it refuses, so a new metric works as soon as it has reached the meter (usually seconds, at most a few minutes). Archived metrics are refused. |
| `negative_quantity` | The quantity is below zero. |
| `invalid_quantity` | Not a plain decimal, more than 12 digits before the point or 6 after, or a JSON number that does not print exactly or has more than 15 significant digits (send those as a string). |
| `invalid_timestamp` | Not an ISO 8601 date with a time zone (`Z` or `+01:00`). |
| `timestamp_too_old` | More than 30 days ago. |
| `timestamp_in_future` | More than 5 minutes ahead. |
| `invalid_properties` | `properties` is not an object. |
| `too_many_properties` | More than 20 properties. |
| `invalid_property_name` | A name that is not 1 to 64 letters, digits or `_`. |
| `property_not_allowed` | A name that is not in the metric's `allowed_properties`. |
| `property_too_long` | A string over 256 characters. |
| `invalid_property_value` | A value that is not a string, a finite number or a boolean. |
| `pan_like_data` | Looks like a card number (see below). |
| `track_data` | Looks like card track data. |
| `email` | Looks like an email address. |
| `ip_address` | Looks like an IPv4 or IPv6 address. |

### No card data or personal data [#no-card-data-or-personal-data]

The usage meter keeps card data and personal data out. It checks `operation_id`, `external_customer_id` and every property value:

- **Card numbers** (`pan_like_data`): any run of 13 to 19 digits, with or without one space, dash, dot, colon, underscore, slash or comma between digits, that is not joined to a letter or `_`. `4111 1111 1111 1111`, `4111:1111:1111:1111`, `card 4111111111111111` and `20261101-000123` are refused. Send long numeric ids with a prefix: in `operation_id` and `external_customer_id`, `ord_123456789012345` and `cus_5555555555554444` are always accepted.
  In property values, a number that looks exactly like a card (starts with 2 to 6 and has a valid card check digit) is refused even with a prefix: `ord_4111111111111111` is refused there. A number property with 13 or more digits before the point is also refused.
  Anywhere, a card number written in groups the way cards are printed (`4111 1111 1111 1111`, or `3782 822463 10005`) is refused even when joined to a letter: `card4111 1111 1111 1111` is refused.
- **Track data** (`track_data`): the patterns of a card's magnetic stripe.
- **Emails** (`email`) and **IP addresses** (`ip_address`). Use your own customer id, never an email, as `external_customer_id`. An id with four dotted numbers in it, such as `v1.2.3.4`, looks like an IP address and is refused: use `v1-2-3-4`.

## Sum and gauge metrics [#sum-and-gauge-metrics]

- For a `sum` metric, send what was used each time: 1,250 tokens, 1 API call. The bill uses the total for the period.
- For a `gauge` metric, send a reading of the current level: "12 seats in use". Each hour keeps its highest reading, and the bill uses the highest hour of the period. Send a reading at least once an hour, each with its own `operation_id`, for example `seats_cust_8412_2026-11-01T09`.
- For something measured over time, like storage, measure it every hour and send it as a `sum` metric in GB-hours.

There are no negative quantities. To lower a bill after usage was billed, correct it in Comecero, for example with a refund on the invoice it was billed on.

## Limits [#limits]

| Limit | Value |
| --- | --- |
| Events per request | 1 to 1,000 |
| Request body | 1 MiB |
| Repeat window for `operation_id` | 35 days, per metric |
| `timestamp` | At most 30 days old, at most 5 minutes ahead |
| `quantity` | 0 or more, at most 12 digits before the point and 6 after |
| `properties` | 20 per event, string values up to 256 characters |
| Events and requests per second | 5,000 events and 50 requests per account, live and test counted together. Over the limit the request gets `429` and nothing in it is counted: wait a second and resend. |

## Test mode [#test-mode]

An `apk_test_` key sends test usage and an `apk_live_` key sends live usage. A key can never write the other mode. Test usage is only billed to agreements made with a test token, and test metrics are separate from live ones, so create your test metrics with a test token too.
