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

# Check and track

> Gate any feature with one call before the action and meter it with one call after, recorded exactly once however often you retry.

Ledger gates every feature and meters every use with two calls from your backend, and records each use exactly once however often you retry. `check` before the action asks whether the customer can use the feature now, and `track` after it succeeds records the use. Track is the meter: it spends credits, counts metered units, changes a held count, or logs a boolean use, depending on the [feature's type](https://docs.integrateledger.com/concepts/features.md). For work that costs you real money to run, [reserve with the check](https://docs.integrateledger.com/customers/reservations.md) and settle with the track.

Both calls read everything the customer holds: their plan plus every [recurring add-on](https://docs.integrateledger.com/pricing/add-ons.md#how-it-counts-in-check-and-track). A feature is on if the plan or any add-on has it, allowances and limits add up across them (an add-on's times its quantity), and overage follows the base plan's terms.

```mermaid theme={"system"}
%%{init: {"theme": "base", "themeVariables": {"fontFamily": "IBM Plex Sans, sans-serif", "fontSize": "14px", "primaryColor": "#f7f6f3", "primaryBorderColor": "#c4bfb5", "primaryTextColor": "#1a1816", "lineColor": "#6b655c", "clusterBkg": "#ffffff", "clusterBorder": "#dbd7cf", "edgeLabelBackground": "#ffffff"}}}%%
sequenceDiagram
    participant App as Your backend
    participant L as Ledger
    App->>L: check(customerId, featureId)
    L-->>App: allowed, balance
    alt allowed is false
        Note over App: Show the reason and offer an upgrade
    else allowed is true
        Note over App: Run the action
        App->>L: track(customerId, featureId, requestId)
        L-->>App: what it charged, balance after
        App->>L: Retry with the same requestId
        L-->>App: idempotent: true, nothing charged again
    end
```

The examples use the [Quickstart](https://docs.integrateledger.com/quickstart.md)'s chat app: `messages` is metered (Pro includes 500 a month), `projects` is held (Free allows 3) and `sso` is boolean. A credits feature, such as `image_generation` at 5 credits, works the same way.

## Check, run, track

```typescript TypeScript theme={"system"}
const { allowed } = await billing.checkCredits({
	customerId: user.id,
	featureId: "messages",
});

if (!allowed) {
	return showUpgradeOffer();
}

const message = await sendChatMessage(prompt);

await billing.trackUsage({
	customerId: user.id,
	featureId: "messages",
	requestId: message.id, // unique to this one use
});
```

```python Python theme={"system"}
decision = billing.check_credits(customer_id=user.id, feature_id="messages")

if not decision["allowed"]:
    return show_upgrade_offer()

message = send_chat_message(prompt)

billing.track_usage(
    customer_id=user.id,
    feature_id="messages",
    request_id=message.id,  # unique to this one use
)
```

```bash cURL theme={"system"}
curl https://api.integrateledger.com/v1/check \
  -H "Authorization: Bearer $LEDGER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"customerId": "user_123", "featureId": "messages"}'

# ... send the message, then:
curl https://api.integrateledger.com/v1/track \
  -H "Authorization: Bearer $LEDGER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"customerId": "user_123", "featureId": "messages", "request_id": "msg_0001"}'
```

Check returns the decision and the feature's balance:

```json Response theme={"system"}
{
  "allowed": true,
  "availableCredits": 0,
  "creditCost": 0,
  "featureType": "metered",
  "unlimited": false,
  "balance": {
    "included": 500,
    "used": 120,
    "remaining": 380,
    "overageAllowed": false,
    "resetsAt": "2026-12-07T07:25:02.000Z"
  }
}
```

Track returns what it applied and the balance after it:

```json Response theme={"system"}
{
  "allowed": true,
  "availableCredits": 0,
  "chargedCredits": 0,
  "overageCredits": 0,
  "overageRemainingCents": null,
  "request_id": "msg_0001",
  "idempotent": false,
  "featureType": "metered",
  "chargedQuantity": 1,
  "balance": {
    "included": 500,
    "used": 121,
    "remaining": 379,
    "overageAllowed": false,
    "resetsAt": "2026-12-07T07:25:02.000Z"
  }
}
```

* **`check` never spends.** A refusal is `allowed: false` with a `200`, a [`reason`](#refusals) and the customer's `plan`, so the offer can name it ("Upgrade from Free") without another call.
* **Track only what succeeded,** so customers pay only for work that ran.
* **`balance`** is `null` for credits features (`availableCredits` is that balance) and boolean features. `remaining` is after [reservations](https://docs.integrateledger.com/customers/reservations.md). `overageAllowed` says whether a use past `remaining` would bill as [overage](https://docs.integrateledger.com/pricing/overage.md).

### Credit fields on other feature types

The SDK methods are `checkCredits` and `trackUsage` for every feature type; the names come from the API's operation IDs. Every response also carries the credit fields, whatever the feature:

* **`availableCredits`** is the customer's credit pool, plan, pack and adjustment credits together. On a credits feature, it is that feature's balance.
* **`creditCost`** (check) and **`chargedCredits`** (track) are what this use spends from that pool: always 0 for metered, held and boolean features, which keep their own balances.

So a metered track with `chargedCredits: 0` did charge: the use is in `balance.used`, and `chargedQuantity` says how many units it counted. Read `featureType` to know which fields matter.

## How each feature type answers

| Type | `check` allows when | `track` does | `quantity` |
| - | - | - | - |
| `credits` | The credits cover `quantity × creditCost`, or the rest fits as overage under the cap | Spends the credits in [spend order](https://docs.integrateledger.com/concepts/balances.md), then overage | Units, 1 or more, each costing `creditCost` (0 only to [settle a reservation](https://docs.integrateledger.com/customers/reservations.md) at nothing). At `creditCost: 1`, the cost in credits you work out yourself ([dollar balance](https://docs.integrateledger.com/pricing/dollar-balance.md)) |
| `metered` | `remaining` covers `quantity`, or the rest fits as overage under the cap | Spends the period's allowance, then records overage | Units, 1 or more (0 only to settle a reservation) |
| `held` | The count plus `quantity` stays within the limit | Adds to the count, or removes with a negative `quantity` | Signed: `1` adds one, `-1` removes one |
| `boolean` | The plan includes the feature | Logs the use, charges nothing | Leave it out |
| `ai_tokens` | The balance covers the priced estimate (`model` and `tokens`), or anything is left without one | Prices the call's `model` and `tokens` and spends the dollars, then overage | Send `model` and `tokens` instead |

A use past what's left is all or nothing, for credits and metered alike: it is allowed whole (spending what's left and recording the rest as overage), or refused whole, with nothing charged.

* **Model calls.** On an `ai_tokens` feature, send the call's `model` (`anthropic/claude-sonnet-4-5`) and `tokens` (`input`, `output`, `cacheRead`, `cacheWrite`, …) instead of `quantity`. Ledger prices them at the model's rates plus your markup; the response adds `chargedUsd`, `availableUsd` and an `ai` block with the cost and markup. On `check` they're an estimate. A call the balance can't fully cover is charged as far as it fits and reports the rest as `uncoveredCredits`. See [AI usage in dollars](https://docs.integrateledger.com/pricing/ai-credits.md).

* **Unlimited.** A plan item with `unlimited: true` always allows. `unlimited` is `true` in the response, a credits feature's `creditCost` is 0, and `balance` has `included` and `remaining` set to `null` while `used` still counts.

* **Track gates held features itself.** An add past the limit is refused with `409 limit_reached` and changes nothing, so a separate check before it is optional ([Limits](https://docs.integrateledger.com/pricing/limits.md), [Concurrency](https://docs.integrateledger.com/pricing/recipes/concurrency.md)).

* **Held removes always work.** A remove at 0 applies 0 (`chargedQuantity: 0`). A held count above the limit, after a downgrade say, is kept, and removes bring it back under; adds resume once it is.

* **Set a held count outright** with `count` instead of `quantity`, to reconcile with your app. It applies even above the plan's limit, since it reports what exists.

```typescript TypeScript theme={"system"}
// One more project
await billing.trackUsage({
	customerId: "user_123",
	featureId: "projects",
	requestId: "project_create_88",
	quantity: 1,
});

// A batch of 40 messages, checked and tracked as one use
await billing.checkCredits({
	customerId: "user_123",
	featureId: "messages",
	quantity: 40,
});

// Reconcile: the customer has 5 projects
await billing.trackUsage({
	customerId: "user_123",
	featureId: "projects",
	requestId: "projects_sync_2026_11_23",
	count: 5,
});
```

```python Python theme={"system"}
# One more project
billing.track_usage(
    customer_id="user_123",
    feature_id="projects",
    request_id="project_create_88",
    quantity=1,
)

# A batch of 40 messages, checked and tracked as one use
billing.check_credits(customer_id="user_123", feature_id="messages", quantity=40)

# Reconcile: the customer has 5 projects
billing.track_usage(
    customer_id="user_123",
    feature_id="projects",
    request_id="projects_sync_2026_11_23",
    count=5,
)
```

```bash cURL theme={"system"}
# One more project
curl https://api.integrateledger.com/v1/track \
  -H "Authorization: Bearer $LEDGER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"customerId": "user_123", "featureId": "projects", "request_id": "project_create_88", "quantity": 1}'

# A batch of 40 messages, checked and tracked as one use
curl https://api.integrateledger.com/v1/check \
  -H "Authorization: Bearer $LEDGER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"customerId": "user_123", "featureId": "messages", "quantity": 40}'

# Reconcile: the customer has 5 projects
curl https://api.integrateledger.com/v1/track \
  -H "Authorization: Bearer $LEDGER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"customerId": "user_123", "featureId": "projects", "request_id": "projects_sync_2026_11_23", "count": 5}'
```

## Request IDs

The request ID makes `track` idempotent.

* **Use an ID you already store** with the action: a message ID, a job ID, or a UUID you save with it. Up to 255 characters. Over HTTP the field is `request_id`.
* **Retry with the same ID.** If a `track` response is lost, send it again with the **same** request ID. Ledger returns the original result with `"idempotent": true` and charges nothing more. A new ID records a second use.
* **One ID, one feature.** Request IDs are one namespace across every feature and type, so each ID names exactly one use of one feature.

Ledger stamps each use itself when it records it, and the use counts toward the billing period current then. A track sent after a renewal spends the new period's allowance. Every request, allowed or refused, lands in the usage log. See [Usage events](https://docs.integrateledger.com/concepts/usage-events.md).

## Refusals

A refused check answers `200` with `allowed: false` and one `reason`. A refused track answers `409` with the same code as `error`, and charges nothing. Ledger asks in this order and stops at the first that fails:

| Order | `reason` | Means | Offer |
| - | - | - | - |
| 1 | `no_plan` | The customer has no current plan, and the feature isn't a credits feature their credits cover ([Customers without a plan](https://docs.integrateledger.com/concepts/balances.md#customers-without-a-plan)). On a credits feature, `track` answers this as `409 insufficient_credits`. | Choose a plan |
| 2 | `feature_not_in_plan` | A metered, held or boolean feature neither the current plan nor any add-on the customer holds includes. | Upgrade, or an add-on that has it |
| 3 | `entity_cap_reached` | With `entityId`, on a credits feature: the [entity's](https://docs.integrateledger.com/customers/entities.md) allowance is spent and its cap leaves too little of the shared credits. | Raise the entity's cap |
| 4 | `overage_cap_reached` | The use would bill as overage past the customer's one monthly cap. | A higher cap, an upgrade or a pack |
| 5 | `limit_reached` | A metered use past `remaining` with no overage (none priced, or the plan is past due), or a held add past the limit. | Upgrade |
| 5 | `insufficient_credits` | On a plan, the credits don't cover the use and no overage is available. | Upgrade or a [credit pack](https://docs.integrateledger.com/pricing/credit-packs.md) |

Treat any other `reason` as `insufficient_credits`. A refused check's `plan` is `{ "id", "name", "status" }`, or `null` with `no_plan`.

```json Response theme={"system"}
{
  "allowed": false,
  "availableCredits": 0,
  "creditCost": 0,
  "featureType": "held",
  "unlimited": false,
  "balance": { "included": 3, "used": 3, "remaining": 0, "overageAllowed": false, "resetsAt": null },
  "reason": "limit_reached",
  "plan": { "id": "free", "name": "Free", "status": "active" }
}
```

[Errors](https://docs.integrateledger.com/errors.md) lists every code.

## Handle a refused track

A plain `check` answers for that moment, so another request can spend the last of a balance between your `check` and your `track`. `track` decides again in its own transaction and can refuse with a `409`. Nothing is charged, and the same request ID can succeed later, for example after the customer buys a pack. If a refusal after the work has run would cost you money, [reserve](https://docs.integrateledger.com/customers/reservations.md) with the check instead.

```typescript TypeScript theme={"system"}
import { TrackError } from "integrateledger/models/errors";

try {
	await billing.trackUsage({ customerId, featureId: "messages", requestId });
} catch (error) {
	if (!(error instanceof TrackError) || error.statusCode !== 409) {
		throw error;
	}
	logRefusal(error.data$.error); // "limit_reached", "insufficient_credits", ...
}
```

```python Python theme={"system"}
from integrateledger import LedgerAPIError

try:
    billing.track_usage(customer_id=customer_id, feature_id="messages", request_id=request_id)
except LedgerAPIError as error:
    if error.status != 409:
        raise
    log_refusal(error.code)  # "limit_reached", "insufficient_credits", ...
```

```bash cURL theme={"system"}
curl -i https://api.integrateledger.com/v1/track \
  -H "Authorization: Bearer $LEDGER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"customerId": "user_123", "featureId": "messages", "request_id": "msg_0002"}'
# HTTP/2 409
# {"error": "limit_reached", "balance": {"included": 500, "used": 500, "remaining": 0, ...}}
```

| `error` | Body also has | What to do |
| - | - | - |
| `insufficient_credits` | `availableCredits`, `creditCost` | Treat it like `allowed: false`. |
| `limit_reached` | `balance` | Treat it like `allowed: false`. |
| `overage_cap_reached` | `overageRemainingCents`; `balance` on a metered feature | Offer a higher cap, an upgrade or a pack. |
| `entity_cap_reached` | `capRemaining` | Raise the entity's cap, or spend from the shared pool. |
| `feature_not_in_plan`, `no_plan` | | The plan or add-ons changed since the check. Offer a plan or add-on that includes the feature. |
| `request_id_conflict` | | The request ID was already used for another feature or entity. Make IDs unique per action. |

## When Ledger is unreachable

The SDKs [fail open](https://docs.integrateledger.com/fail-open.md) by default: `check` is allowed and `track` is replayed later with the same request ID, both marked `failedOpen: true`, so an outage never blocks your users. Pass `failOpen: false` (Python `fail_open=False`) to handle outages yourself, for example to refuse paid work with a 503 before it runs. A check with `reserve` raises instead, because a reservation guards expensive work.

**Usage** in the dashboard lists every tracked request, charged or refused, with the reason.

> [!NOTE]
>
> **Other ways.** Without an SDK, call [`POST /v1/check`](https://docs.integrateledger.com/api-reference/usage/check) and [`POST /v1/track`](https://docs.integrateledger.com/api-reference/usage/track).

## Rules

* Call Ledger from your backend, never from a browser or mobile app, so your API key stays secret.
* Leave `quantity` out on boolean features.
* Branch on the code, `reason` on a check and `error` on a track, never the message; treat an unknown one as `insufficient_credits`.
* Reusing a request ID for another feature or entity returns `409 request_id_conflict`.
* A customer or feature outside the key's environment returns `404 customer_not_found` or `feature_not_found`.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.