# Manage balance consumption and reservations

Operation / SDK: `mutateBalance` · `mutate_balance` · `MutateBalance`

Consume, reserve, confirm, refund or release balance; refunds also need `credits:manage`. Use quoteBalance for quotes.

Last updated: 2026-11-06

[Web version](https://www.longplayai.com/docs/api/mutate-balance)

<a id="request"></a>

## Request

- **Credential**: Server Key with `credits:consume`. Call from your backend only.
- **SDK**: JavaScript `createLongplayServer().mutateBalance` · Python `mutate_balance` · Go `MutateBalance`
- **Success**: HTTP 200

The response shows example data.

**cURL: request.sh**

```bash
curl -X POST "$LONGPLAY_API_URL/api/v1/balances/execute" \
  -H "Authorization: Bearer $LONGPLAY_SERVER_KEY" \
  -H "X-Indiana-Protocol: 0.10" \
  -H "Content-Type: application/json" \
  -d '{
  "customerId": "8b258f8b-4228-40fa-8d24-5b16428e686d",
  "command": {
    "operation": "consume",
    "internal_feature_id": "f317c851-0ef2-4d7a-8e3c-e8a29df676ed",
    "quantity": "1",
    "properties": {},
    "idempotencyKey": "job:job_123:consume"
  }
}'
```

**TypeScript: mutateBalance.ts**

```ts
import { createLongplayServer } from "@tinkerlandai/longplay-sdk/server";

const longplay = createLongplayServer({
  baseUrl: process.env.LONGPLAY_API_URL!,
  apiKey: process.env.LONGPLAY_SERVER_KEY!,
  scope: { projectId: process.env.LONGPLAY_PROJECT_ID!, environment: "sandbox" },
});

export async function mutateBalance() {
  return longplay.mutateBalance({
    customerId: "8b258f8b-4228-40fa-8d24-5b16428e686d",
    command: {
      operation: "consume",
      internal_feature_id: "f317c851-0ef2-4d7a-8e3c-e8a29df676ed",
      quantity: "1",
      properties: {},
      idempotencyKey: "job:job_123:consume",
    },
  });
}
```

**Request body: request.json**

```json
{
  "customerId": "8b258f8b-4228-40fa-8d24-5b16428e686d",
  "command": {
    "operation": "consume",
    "internal_feature_id": "f317c851-0ef2-4d7a-8e3c-e8a29df676ed",
    "quantity": "1",
    "properties": {},
    "idempotencyKey": "job:job_123:consume"
  }
}
```

**Response: response.json**

```json
{
  "requestId": "44f5fcb8-6ed8-41b8-818f-7571941c5fd5",
  "scope": {
    "projectId": "df5426d6-b335-403c-8f3e-b0f73d2e3511",
    "environment": "sandbox"
  },
  "receipt": {
    "id": "a8b14e0c-6576-49a4-812c-7a1587e55255",
    "internal_feature_id": "13fca2b7-63e8-4e82-881f-173a43762c65",
    "kind": "consume",
    "originalId": null,
    "quantity": "1",
    "accepted": true,
    "reason": null,
    "createdAt": "2026-10-03T12:00:00.000Z",
    "reservationStatus": null,
    "expiresAt": null,
    "allocations": [
      {
        "funding": "postpaid",
        "invoiceLineId": "73701ec0-ca86-4128-81a7-f9d99b63dd8d",
        "units": "1",
        "authorizationId": "ec0718b4-46db-4174-8885-e2ed6354c9e5"
      }
    ]
  }
}
```

<a id="parameters"></a>

## Body parameters

**application/json**

- `customerId` (uuid, required): The Customer's UUID.
- `command` (object | object | object | object | object | object, required): The command to run; its `action` or `operation` selects the other fields.
- `command.operation` ("quote" | "consume" | "reserve" | "confirm" | "refund" | "release", required): The operation to run; it selects the other fields.
- `command.overageBehavior` (enum | enum, optional): cap accepts the largest permitted quantity, possibly zero. overflow requests the full quantity subject to overage permission, usage caps and cash budgets. Omission keeps all-or-nothing behavior.
- `command.internal_feature_id` (uuid | uuid | uuid, optional): Feature ID.
- `command.entityId` (uuid | uuid | uuid, optional): Entity ID within the current customer scope, for configured Entity and license Features.
- `command.quantity` (string | string | string | string | string, optional): Quantity as a decimal string, avoiding floating-point error.
- `command.properties` (object | object | object | object, optional): Validated pricing properties used to match dimensions and multipliers.
- `command.occurredAt` (date-time | date-time, optional): Timestamp (ISO 8601).
- `command.idempotencyKey` (string | string | string | string | string, optional): Stable business idempotency key. The same key and payload replay the result; do not randomize on retries.
- `command.expiresInSeconds` (integer, optional): Reservation lifetime in seconds, up to 86400. min: 1 · max: 86400
- `command.operationId` (uuid | uuid | uuid, optional): Business operation UUID. Subscription execution references operationId from previewAttach; balance refunds reference the original consumption.

<a id="response"></a>

## Response fields

Every successful response includes `requestId` (this request's ID, for support) and `scope` (App and environment).

**HTTP 200 · application/json**

- `requestId` (uuid, required): UUID the server generated for this HTTP request; include it when reporting a problem. It is not your business requestId.
- `scope` (object, required): The App and environment of this response. Headers only verify scope; they cannot switch key scope.
- `scope.projectId` (string, required): App ID bound to the credential. minLength: 1
- `scope.environment` (enum, required): Separate data scope: sandbox or live. Values: `"sandbox"`, `"live"`.
- `receipt` (object, required): Accepted business facts and idempotent result of the operation.
- `receipt.id` (uuid, required): The receipt's ID.
- `receipt.internal_feature_id` (uuid, required): Feature ID.
- `receipt.kind` (enum, required): Kind; see the allowed values. Values: `"consume"`, `"reserve"`, `"confirm"`, `"refund"`, `"release"`, `"expire"`.
- `receipt.originalId` (uuid | null, required): original record ID.
- `receipt.quantity` (string, required): Quantity as a decimal string, avoiding floating-point error. pattern: ^(0|[1-9]\d{0,11})(\.\d{1,6})?$
- `receipt.requestedQuantity` (string, optional): Original quantity for explicit cap/overflow. quantity is the quantity accepted or rejected by the operation. pattern: ^(0|[1-9]\d{0,11})(\.\d{1,6})?$
- `receipt.overageBehavior` (enum, optional): cap accepts the largest permitted quantity, possibly zero. overflow requests the full quantity subject to overage permission, usage caps and cash budgets. Omission keeps all-or-nothing behavior. Values: `"cap"`, `"overflow"`.
- `receipt.accepted` (boolean, required): Whether business rules accepted the operation. HTTP 200 does not imply accepted is true.
- `receipt.reason` (enum | null, required): Rejection reason or ledger operation description; interpret with accepted and status.
- `receipt.createdAt` (date-time, required): ISO 8601 UTC time when the record was created.
- `receipt.reservationStatus` (enum | null, required): Reservation status; see the allowed values.
- `receipt.expiresAt` (date-time | null, required): Expiry time (ISO 8601, UTC).
- `receipt.allocations` (array, required): Balance allocations involved in this evaluation or ledger operation. maxItems: 500
- `receipt.allocations.funding` ("balance" | "unbilled" | "prepaid" | "postpaid", required): Funding source; see the allowed values.
- `receipt.allocations.sourceId` (uuid | uuid, optional): balance source ID.
- `receipt.allocations.rolloverId` (uuid | null, optional): rollover ID.
- `receipt.allocations.units` (string | string | string | string, required): Part of the operation's quantity covered by this allocation, in units of the operation's Feature; decimal string. The units of all allocations add up to `quantity`.
- `receipt.allocations.amount` (string | string, optional): Credit or ledger amount, using the field’s decimal-string or integer type.
- `receipt.allocations.pricing` (array, optional): Pricing details. minItems: 1 · maxItems: 12
- `receipt.allocations.pricing.internal_credit_feature_id` (uuid | null, required): credit Feature ID.
- `receipt.allocations.pricing.internal_metered_feature_id` (uuid, required): metered Feature ID.
- `receipt.allocations.pricing.dimension` (string, required): Pricing dimension. minLength: 1 · maxLength: 64
- `receipt.allocations.pricing.counterKey` (string, required): Counter key. minLength: 1 · maxLength: 240
- `receipt.allocations.pricing.cycleStart` (date-time, required): Cycle start.
- `receipt.allocations.pricing.unitCost` (string, required): Unit cost. pattern: ^(0|[1-9]\d{0,11})(\.\d{1,6})?$
- `receipt.allocations.pricing.units` (string, required): Units as a decimal string. pattern: ^(0|[1-9]\d{0,11})(\.\d{1,6})?$
- `receipt.allocations.pricing.amount` (string, required): Credit or ledger amount, using the field’s decimal-string or integer type. pattern: ^(0|[1-9]\d{0,12})(\.\d{1,12})?$
- `receipt.allocations.pricing.tier` (integer | null, required): Price tier.
- `receipt.allocations.invoiceLineId` (uuid | null, optional): invoice line ID.
- `receipt.allocations.authorizationId` (uuid, optional): authorization ID.

<a id="errors"></a>

## Errors

Failures return an error object; handle them by `error.code` and `error.recovery`. The table lists the errors that follow from this operation's credential, scope and idempotency fields; depending on the request it can also return `NOT_FOUND` (a referenced resource doesn't exist), `NOT_CONFIGURED` (a required integration isn't connected) or `PAYLOAD_TOO_LARGE`. Some refusals, such as insufficient balance, are not errors but a `reason` in a successful response.

**Possible errors**

| code | HTTP | When | recovery |
| --- | --- | --- | --- |
| `INVALID_REQUEST` | 400 | The request doesn't match this page's parameters. A missing or malformed protocol header returns `UNSUPPORTED_PROTOCOL_VERSION` or `INVALID_PROTOCOL_VERSION` instead. | `fix_request` |
| `UNAUTHENTICATED` | 401 | The credential is missing, invalid, expired or revoked. | `authenticate` |
| `FORBIDDEN` | 403 | The credential lacks `credits:consume`. | `check_permissions` |
| `SCOPE_MISMATCH` | 403 | `X-Indiana-Project` or `X-Indiana-Environment` doesn't match the credential's App and environment. | `check_scope` |
| `CONFLICT` | 409 | The same `idempotencyKey` was sent with different input (`reason: IDEMPOTENCY_CONFLICT`). | `resolve_conflict` |
| `RATE_LIMITED` | 429 | Too many requests; wait for `Retry-After` and retry the same request. | `retry_same_request` |
| `SERVICE_UNAVAILABLE` | 503 | The service is temporarily unavailable; retry the same request. | `retry_same_request` |
| `INTERNAL_ERROR` | 500 | The outcome is unknown; read the original operation or replay the original ID and input. | `recover_operation` |

- [Error codes and recovery](https://www.longplayai.com/docs/api/errors.md)
- [Request conventions](https://www.longplayai.com/docs/api.md)
- [All operations](https://www.longplayai.com/docs/api/operations.md#credits)
