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

# Real-Time Credits

> Check a customer's credit before work runs and draw it down as the work completes, with a hard stop or overflow to metered billing when credit runs out

Real-time credits let your application ask Alguna whether a customer has enough credit **before** it does billable work, and draw the credit down **as** the work completes. Use it when running out of credit has to change what your product does in the moment: refuse an expensive inference run, stop an agent mid-task, or let the work continue and bill the excess as usage. Credit that is only settled on the next invoice does not need the gate; see [invoice-time consumption](https://alguna.com/docs/credits/credit-consumption.md#invoice-time-consumption). Credits sit on the customer's record with the rest of their agreement, as described in [How Alguna works](https://alguna.com/docs/concepts/how-alguna-works.md).

The gate is two endpoints: [`POST /credits/check`](https://alguna.com/docs/api-reference/v2/2026-04-01/credits/reserve-credits) before the work and [`POST /credits/track`](https://alguna.com/docs/api-reference/v2/2026-04-01/credits/track-credit-consumption) after it. Neither request carries a credit amount. You describe the work as the usage events it produces, and Alguna prices those events against the metric's consumption rule.

![Requests draw down a live balance of 166 credits. When the balance reaches zero, the next request, an AI summary that needs 50 credits, is not run and the balance shows Stopped at zero](https://mintcdn.com/alguna-20/Or9p2rr5SKOnkvHy/images/credits/realtime-credits-stop-at-zero.gif?s=74eaa8ce138cbcc27f6bcf43a21670e7)

***

## How it works

1. **Configure once, in the dashboard.** Each metric that should draw credit gets a consumption rule with a price in credits and an at-zero policy. Each grant that should pay for gated work gets gate funding.
2. **Check before the work.** Your application calls `/credits/check`. With `reserve`, Alguna places a hold on the credit and returns a `reservation_id`.
3. **Track after the work.** Your application calls `/credits/track` with the events that actually happened. Alguna draws the credit, records the usage, and releases what the hold did not need.

Small, instant actions can skip the hold and [draw directly](#draw-without-a-reservation) with one `/credits/track` call.

***

## Before you start

Setup is dashboard configuration. There is no public API for consumption rules or for gate funding.

### Set a consumption rule for each metric

Under **Settings → Workflows → Billing → Credits**, add a rule for each [billable metric](https://alguna.com/docs/billable-metrics/define-metrics.md) whose usage draws credit. A rule sets:

| Setting | What it does |
| - | - |
| Credits per event | The rate at which the metric's usage converts into credits |
| At-zero policy | What the gate reports when credit runs out: `stop` (hard deny) or `overflow` (fall through to metered billing) |

The rule is also shown under **Credit consumption** on the metric page. See [Consumption rules](https://alguna.com/docs/credits/credit-consumption.md#consumption-rules).

### Fund the gate from a grant

Open **Customers**, select the customer, and open the **Credits** card, or the **Credits & Entitlements** section of one of their subscriptions. Click **Add Credits**, choose `Units`, and set **Gate funding**:

| Gate funding | What the grant pays for at the gate |
| - | - |
| `off` | Nothing. This is the default. |
| `all` | Any metric with an active consumption rule, including rules added later |
| `chosen` | Only the metrics listed on the grant |

> [!WARNING]
>
> Grants created through the API, including `POST /subscriptions/{id}/credits/grant`, have gate funding `off`. A gate with no funded grant has no credit to draw, so every check on a `stop` metric returns `allowed: false`. Set gate funding in the dashboard.

Recurring allowances come from a `credit_allocation` [entitlement](https://alguna.com/docs/entitlements/overview.md) on the plan or subscription, which creates a grant each period. See [Realtime gate funding](https://alguna.com/docs/credits/credit-grants.md#realtime-gate-funding).

### Confirm the gate is enabled

Real-time credits are enabled per organization. Until it is enabled for yours, `/credits/check` returns `allowed: false` with an empty `balances` array, and `/credits/track` accepts no new draws.

***

## Create a client

The examples on this page use the official SDKs. Each one reads the API key from `ALGUNA_API_KEY`. Create a key under **Settings → Connections → Developers → API Keys**. Sandbox requests go to `https://api.sandbox.alguna.io` with a sandbox key.

```bash cURL theme={null}
export ALGUNA_API_KEY="<key_id>.<key_secret>"
```

```python Python theme={null}
from alguna import Alguna, ReserveCreditsRequest, TrackCreditEvent

client = Alguna(api_version="2026-04-01")
```

```typescript TypeScript theme={null}
import { Alguna } from "@alguna/sdk";

const alguna = new Alguna({ apiVersion: "2026-04-01" });
```

```go Go theme={null}
import (
	"context"
	"errors"
	"fmt"

	alguna "github.com/alguna-io/alguna-go"
	"github.com/alguna-io/alguna-go/client"
	"github.com/alguna-io/alguna-go/option"
)

c := client.NewAlguna(option.WithAPIVersion("2026-04-01"))
ctx := context.Background()
```

```rust Rust theme={null}
use alguna::prelude::*;
use alguna::ApiClientBuilder;

let client = ApiClientBuilder::default()
    .api_version("2026-04-01")
    .build()?;
```

The examples use an account `cust_abc123` and a count metric fed by the event `api_call`. For a metric that sums a property, put that property in each event's `properties`: it is the quantity that gets priced.

***

## Price work without spending credit

Call `/credits/check` without `reserve` to learn what work would cost. Nothing is recorded, no credit moves, and the response's `charges` carry the price per metric.

```bash cURL theme={null}
curl -X POST https://api.alguna.io/credits/check \
  -H "Authorization: Bearer $ALGUNA_API_KEY" \
  -H "Alguna-Version: 2026-04-01" \
  -H "Content-Type: application/json" \
  -d '{
    "account": "cust_abc123",
    "events": [{ "event_name": "api_call", "unique_id": "quote_001" }]
  }'
```

```python Python theme={null}
quote = client.credits.check(
    account="cust_abc123",
    events=[TrackCreditEvent(event_name="api_call", unique_id="quote_001")],
)
print(quote.allowed, quote.charges)
```

```typescript TypeScript theme={null}
const quote = await alguna.credits.check({
  account: "cust_abc123",
  events: [{ event_name: "api_call", unique_id: "quote_001" }],
});
console.log(quote.allowed, quote.charges);
```

```go Go theme={null}
quote, err := c.Credits.Check(ctx, &alguna.CheckCreditsRequest{
	Account: "cust_abc123",
	Events:  []*alguna.TrackCreditEvent{{EventName: "api_call", UniqueID: "quote_001"}},
})
if err != nil {
	return err
}
fmt.Println(quote.Allowed, quote.Charges)
```

```rust Rust theme={null}
let quote = client
    .credits
    .check(
        &CheckCreditsRequest {
            account: "cust_abc123".to_string(),
            events: Some(vec![TrackCreditEvent {
                event_name: "api_call".to_string(),
                unique_id: "quote_001".to_string(),
                ..Default::default()
            }]),
            ..Default::default()
        },
        None,
    )
    .await?;
println!("{} {:?}", quote.allowed, quote.charges);
```

***

## Reserve credit before the work

Add `reserve` to open a hold. A hold needs an `Idempotency-Key`: it identifies the hold, so a retry with the same key returns the same reservation instead of opening a second one.

```bash cURL theme={null}
curl -X POST https://api.alguna.io/credits/check \
  -H "Authorization: Bearer $ALGUNA_API_KEY" \
  -H "Alguna-Version: 2026-04-01" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: run_001_reserve" \
  -d '{
    "account": "cust_abc123",
    "reserve": {},
    "events": [{ "event_name": "api_call", "unique_id": "run_001_call1" }]
  }'
```

```python Python theme={null}
hold = client.credits.check(
    account="cust_abc123",
    reserve=ReserveCreditsRequest(),
    events=[TrackCreditEvent(event_name="api_call", unique_id="run_001_call1")],
    idempotency_key="run_001_reserve",
)
if not hold.allowed and hold.at_zero_action == "stop":
    raise RuntimeError("Out of credit")
reservation_id = hold.reservation_id
```

```typescript TypeScript theme={null}
const hold = await alguna.credits.check(
  {
    account: "cust_abc123",
    reserve: {},
    events: [{ event_name: "api_call", unique_id: "run_001_call1" }],
  },
  { idempotencyKey: "run_001_reserve" },
);
if (!hold.allowed && hold.at_zero_action === "stop") {
  throw new Error("Out of credit");
}
const reservationId = hold.reservation_id;
```

```go Go theme={null}
hold, err := c.Credits.Check(ctx, &alguna.CheckCreditsRequest{
	Account: "cust_abc123",
	Reserve: &alguna.ReserveCreditsRequest{},
	Events:  []*alguna.TrackCreditEvent{{EventName: "api_call", UniqueID: "run_001_call1"}},
}, option.WithIdempotencyKey(alguna.String("run_001_reserve")))
if err != nil {
	return err
}
if !hold.Allowed && hold.AtZeroAction == "stop" {
	return errors.New("out of credit")
}
reservationID := hold.ReservationID
```

```rust Rust theme={null}
let hold = client
    .credits
    .check(
        &CheckCreditsRequest {
            account: "cust_abc123".to_string(),
            reserve: Some(ReserveCreditsRequest::default()),
            events: Some(vec![TrackCreditEvent {
                event_name: "api_call".to_string(),
                unique_id: "run_001_call1".to_string(),
                ..Default::default()
            }]),
            ..Default::default()
        },
        Some(RequestOptions::new().idempotency_key("run_001_reserve")),
    )
    .await?;
if !hold.allowed && hold.at_zero_action == "stop" {
    // Out of credit: refuse the work.
}
let reservation_id = hold.reservation_id.clone();
```

### Read the decision

Insufficient credit is not an error. The call returns `200` and the decision is in the body:

| `allowed` | `at_zero_action` | What to do |
| - | - | - |
| `true` | any | Run the work. A hold was opened and `reservation_id` names it. |
| `false` | `stop` | Refuse the work. No hold was opened. |
| `false` | `overflow` | You may run the work. The uncovered part is billed as metered usage. |

When the work feeds several metrics with different policies, `at_zero_action` reports the strictest, `stop`. `balances` lists availability per ledger, and it can be empty, so check its length before reading it.

### Size the hold

| `reserve` | Hold size | Use it for |
| - | - | - |
| `{}` | Exactly what the request's `events` price to | Work whose size you know up front |
| `{ "max_quantity": "5000" }` with `event_name` | `max_quantity` metric units at the metric's rate, summed over the metrics the event feeds | Open-ended runs. Do not send `events` with it. |

A hold lasts 15 minutes. Set `ttl_seconds` (1 to 14400, which is 4 hours) for longer work. Each accepted settle moves the expiry forward.

***

## Track what the work used

Send the events that actually happened, with the `reservation_id` and `close`. Alguna draws the credit, records the events as usage, and releases what the hold did not need.

```bash cURL theme={null}
curl -X POST https://api.alguna.io/credits/track \
  -H "Authorization: Bearer $ALGUNA_API_KEY" \
  -H "Alguna-Version: 2026-04-01" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: run_001_settle" \
  -d '{
    "reservation_id": "crt_abc123",
    "close": true,
    "events": [{ "event_name": "api_call", "unique_id": "run_001_call1" }]
  }'
```

```python Python theme={null}
settled = client.credits.track(
    reservation_id=reservation_id,
    close=True,
    events=[TrackCreditEvent(event_name="api_call", unique_id="run_001_call1")],
    idempotency_key="run_001_settle",
)
print(settled.allowed, settled.balances)
```

```typescript TypeScript theme={null}
const settled = await alguna.credits.track(
  {
    reservation_id: reservationId,
    close: true,
    events: [{ event_name: "api_call", unique_id: "run_001_call1" }],
  },
  { idempotencyKey: "run_001_settle" },
);
console.log(settled.allowed, settled.balances);
```

```go Go theme={null}
settled, err := c.Credits.Track(ctx, &alguna.TrackCreditsRequest{
	ReservationID: alguna.String(reservationID),
	Close:         alguna.Bool(true),
	Events:        []*alguna.TrackCreditEvent{{EventName: "api_call", UniqueID: "run_001_call1"}},
}, option.WithIdempotencyKey(alguna.String("run_001_settle")))
if err != nil {
	return err
}
fmt.Println(settled.Allowed, settled.Balances)
```

```rust Rust theme={null}
let settled = client
    .credits
    .track(
        &TrackCreditsRequest {
            reservation_id: Some(reservation_id.clone()),
            close: Some(true),
            events: vec![TrackCreditEvent {
                event_name: "api_call".to_string(),
                unique_id: "run_001_call1".to_string(),
                ..Default::default()
            }],
            ..Default::default()
        },
        Some(RequestOptions::new().idempotency_key("run_001_settle")),
    )
    .await?;
println!("{} {:?}", settled.allowed, settled.balances);
```

`close` is required whenever `reservation_id` is set:

* `false` records progress and keeps the hold open. Use it for long runs that report as they go.
* `true` is the final call. The hold closes and its remainder is released.

The hold also closes on its own when the events consume all of it.

Events sent to `/credits/track` are already metered. Do not also send them to `POST /events`, or the usage is counted twice.

### Settles that price past the hold

On a `stop` metric, a settle can price past what the hold authorized, or arrive after credit ran out. `on_envelope_exceeded` decides what happens:

| Value | Behavior |
| - | - |
| `reject` (default) | The call returns `422` and nothing is drawn, recorded or metered. The body's `code` is `credit_close_exceeds_envelope` when the usage priced past the hold, or `credit_close_coverage_shortfall` when credit ran out. |
| `record` | Draws what is available and reports the remainder as `overflow` in `charges`. This deliberately weakens the hard stop. |

`on_envelope_exceeded` is valid on settles only, not on direct draws.

***

## Release a hold the work never used

If the work is cancelled, close the reservation with no events. Nothing is charged and the whole hold is released. An unclosed hold also expires on its own.

```bash cURL theme={null}
curl -X POST https://api.alguna.io/credits/track \
  -H "Authorization: Bearer $ALGUNA_API_KEY" \
  -H "Alguna-Version: 2026-04-01" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: run_001_release" \
  -d '{ "reservation_id": "crt_abc123", "close": true, "events": [] }'
```

```python Python theme={null}
client.credits.track(
    reservation_id=reservation_id,
    close=True,
    events=[],
    idempotency_key="run_001_release",
)
```

```typescript TypeScript theme={null}
await alguna.credits.track(
  { reservation_id: reservationId, close: true, events: [] },
  { idempotencyKey: "run_001_release" },
);
```

```go Go theme={null}
_, err = c.Credits.Track(ctx, &alguna.TrackCreditsRequest{
	ReservationID: alguna.String(reservationID),
	Close:         alguna.Bool(true),
	Events:        []*alguna.TrackCreditEvent{},
}, option.WithIdempotencyKey(alguna.String("run_001_release")))
```

```rust Rust theme={null}
client
    .credits
    .track(
        &TrackCreditsRequest {
            reservation_id: Some(reservation_id.clone()),
            close: Some(true),
            events: vec![],
            ..Default::default()
        },
        Some(RequestOptions::new().idempotency_key("run_001_release")),
    )
    .await?;
```

***

## Draw without a reservation

Send `account` instead of `reservation_id` to draw the account's credit directly, with no hold. Use it for small, instant actions where a separate check adds nothing. `close` and `on_envelope_exceeded` are not valid on a direct draw.

```bash cURL theme={null}
curl -X POST https://api.alguna.io/credits/track \
  -H "Authorization: Bearer $ALGUNA_API_KEY" \
  -H "Alguna-Version: 2026-04-01" \
  -H "Content-Type: application/json" \
  -d '{
    "account": "cust_abc123",
    "events": [{ "event_name": "api_call", "unique_id": "evt_002" }]
  }'
```

```python Python theme={null}
draw = client.credits.track(
    account="cust_abc123",
    events=[TrackCreditEvent(event_name="api_call", unique_id="evt_002")],
)
if not draw.allowed:
    print("Not covered by credit", draw.charges)
```

```typescript TypeScript theme={null}
const draw = await alguna.credits.track({
  account: "cust_abc123",
  events: [{ event_name: "api_call", unique_id: "evt_002" }],
});
if (!draw.allowed) {
  console.log("Not covered by credit", draw.charges);
}
```

```go Go theme={null}
draw, err := c.Credits.Track(ctx, &alguna.TrackCreditsRequest{
	Account: alguna.String("cust_abc123"),
	Events:  []*alguna.TrackCreditEvent{{EventName: "api_call", UniqueID: "evt_002"}},
})
if err != nil {
	return err
}
if !draw.Allowed {
	fmt.Println("not covered by credit", draw.Charges)
}
```

```rust Rust theme={null}
let draw = client
    .credits
    .track(
        &TrackCreditsRequest {
            account: Some("cust_abc123".to_string()),
            events: vec![TrackCreditEvent {
                event_name: "api_call".to_string(),
                unique_id: "evt_002".to_string(),
                ..Default::default()
            }],
            ..Default::default()
        },
        None,
    )
    .await?;
if !draw.allowed {
    println!("not covered by credit: {:?}", draw.charges);
}
```

***

## Common patterns

### One balance across your product

Sell one credit balance and price each action on its own.

1. Define a [billable metric](https://alguna.com/docs/billable-metrics/define-metrics.md) for each action, such as `search`, `report` and `ai_summary`.
2. Give each metric a consumption rule with its own rate, for example 1, 25 and 50 credits per event.
3. Give the customer one `Units` grant with gate funding `all`.

Every check and track prices the event against its own metric and draws from the same grant. A grant with gate funding `all` also funds metrics that get a consumption rule later. To change what an action costs, edit its consumption rule in the dashboard. Your code does not change.

### Free plan with a hard limit

Give free accounts a fixed amount of credit and stop usage when it runs out.

1. Set the metric's consumption rule to `stop` at zero.
2. Give each free account a `Units` grant with gate funding on.
3. Before each fixed-cost action, [draw directly](#draw-without-a-reservation) with `/credits/track`. When `allowed` is `true`, run the action. When it is `false`, show an upgrade prompt instead.

A direct draw charges as soon as it is accepted, and there is no hold to release. If the action can fail after you draw, [reserve](#reserve-credit-before-the-work) first and settle only what succeeded.

### Prompting a top-up

When a check on a `stop` metric returns `allowed: false`, your product knows the customer is out of credit and can show a top-up or upgrade prompt. To reach the customer outside your product, subscribe to the `account.credits.balance_depleted` [webhook](https://alguna.com/docs/api-reference/v2/webhooks.md#supported-events), which fires when a credit balance reaches zero. The `credits_depleted` [automation trigger](https://alguna.com/docs/automations/reference.md) fires on the same condition, so you can email the customer without writing a webhook handler.

Credit added for a top-up must have gate funding turned on to count for real-time usage. Add it from the customer's **Credits** card. Recurring allowances come from a `credit_allocation` [entitlement](https://alguna.com/docs/entitlements/overview.md).

***

## How gated usage is invoiced

![A request from your product goes to Alguna, which runs the credit check, records the draw on the ledger, and carries it through to the invoice and payment in the same platform](https://mintcdn.com/alguna-20/Or9p2rr5SKOnkvHy/images/credits/realtime-credits-flow.png?fit=max\&auto=format\&n=Or9p2rr5SKOnkvHy\&q=85\&s=7891a0f8d851b1ea4affe7829c90fff3)

Events settled through `/credits/track` are metered like any other usage. When the invoice for the period is priced, Alguna subtracts the usage that credit already covered from each metric's quantity before pricing it. The invoice bills only what credit did not cover, which is the `overflow` the gate reported.

Covered usage is removed before pricing, so on a tiered price the remaining usage is priced from the first tier. Gated usage is never invoiced twice.

***

## Read a reservation

[`GET /credits/reservations/{reservation_id}`](https://alguna.com/docs/api-reference/v2/2026-04-01/credits/read-a-reservation) returns a hold's `status`, what it has `remaining`, the metrics it covers, and every close already committed against it. It settles nothing. Use it when a client lost track of a settle and needs to find out what already landed before it sends anything again. In the SDKs it is `credits.getReservation` (TypeScript) and `credits.get_reservation` (Python).

```bash theme={null}
curl https://api.alguna.io/credits/reservations/crt_abc123 \
  -H "Authorization: Bearer $ALGUNA_API_KEY" \
  -H "Alguna-Version: 2026-04-01"
```

***

## Retries and idempotency

* **`unique_id` identifies each event.** It must be unique within a payload, at most 72 characters, and the same on every retry. A resent event is applied once.
* **`Idempotency-Key` is required with `reserve`.** It is optional on `/credits/track`, where the events' `unique_id`s identify the draw.
* **The SDKs generate no key for these calls.** They still retry them, because the events identify the work, and they send a key that you pass on every attempt. See [Writes identified by their events](https://alguna.com/docs/api-reference/v2/idempotency.md#writes-identified-by-their-events).
* **Reusing a key for a different request returns `409`.** Retry with a new key.

***

## Errors

| Status | When | What to do |
| - | - | - |
| `200` with `allowed: false` | Not enough credit | Apply `at_zero_action`. This is not an error. |
| `404` | The account or reservation does not exist | Fix the identifier. |
| `409` | An `Idempotency-Key` or `unique_id` was already used for a different request, or the key's reservation is no longer open | Retry with a new key or identity. |
| `422` | The request breaks a rule: for example an event that feeds no metric with a consumption rule, a missing `close` on a settle, or a settle refused by `on_envelope_exceeded` | Fix the request. Usage for a metric without a consumption rule belongs on `POST /events`. |
| `429` | The gate is busy, or the ledger has too many open holds | Back off and retry. The SDKs retry it twice, honoring `Retry-After`. |
| `503` | The gate is temporarily unavailable | Retry with backoff. |

See [Errors](https://alguna.com/docs/api-reference/v2/errors.md) for the error body and retry guidance.

***

## Limits

| Limit | Value |
| - | - |
| Events per call | 100 |
| `unique_id` length | 72 characters |
| Hold lifetime (`ttl_seconds`) | Default 900 seconds, maximum 14400 seconds (4 hours) |

***

## Next steps

> [card] [Credit Grants](https://alguna.com/docs/credits/credit-grants.md)
>
> Create grants and set gate funding.

> [card] [Credit Consumption](https://alguna.com/docs/credits/credit-consumption.md)
>
> Consumption rules and invoice-time draws.

> [card] [Errors](https://alguna.com/docs/api-reference/v2/errors.md)
>
> Error bodies and retry guidance.

> [card] [Idempotency](https://alguna.com/docs/api-reference/v2/idempotency.md)
>
> How retries stay safe.


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