---
title: "Keep credits in a ledger instead of a · Agent Wranglers"
url: https://agentwranglers.se/playbook/usage-billing/credits-and-prepaid-balances/credit-ledger
id: USG-6
level: Required
applies: payments
risk: money
updated: 2026-10-22
tokens: 1029
licence: "CC BY 4.0"
licence_url: https://creativecommons.org/licenses/by/4.0/
---

# Keep credits in a ledger instead of a balance you overwrite

For AI agents: the [site map](https://agentwranglers.se/llms.txt) lists everything here, and this page sits under [Credits and prepaid balances](https://agentwranglers.se/playbook/usage-billing/credits-and-prepaid-balances.md).

By [Agent Wranglers](https://agentwranglers.se/authors/agent-wranglers.md). Updated 2026-10-22.

- ID: USG-6
- Level: Required
- Chapter: [Credits and prepaid balances](https://agentwranglers.se/playbook/usage-billing/credits-and-prepaid-balances.md)
- Rule: Record every credit grant, use, refund and expiry as a new ledger row with a reason and a source ID. The balance is the sum of the rows.
- Check: As the app role, run an UPDATE and a DELETE on the credit ledger. Both fail with permission denied. A nightly job compares each cached balance with the sum of its rows and alerts on any difference.
- Risk: Money lost or taken twice
- Applies when: The project takes payments.
- How: A balance column that two requests update at once loses one of the changes, and nobody can say where the credits went. A ledger keeps the history. Give each row the customer, a signed amount, the type, the source ID and the time. Put a unique constraint on the source ID, such as the payment, the usage event or the grant, so a retry never books twice. Corrections are new rows. A balance column may serve as a fast cache, updated in the same transaction as the row. Rebuild it from the rows every night. The pattern is the same as [Record every money movement in an append-only ledger](https://agentwranglers.se/playbook/payments/payment-events-and-reconciliation/payment-ledger.md).

## Examples

**Using these examples:** they show one way to follow this rule. Keep the behaviour and the check, not the syntax. Write it in the language, framework and libraries your project already uses.

### SQL example

```sql
CREATE TABLE credit_entries (
  id           bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  customer_id  text NOT NULL,
  entry_type   text NOT NULL CHECK (entry_type IN ('grant', 'purchase', 'hold', 'release', 'use', 'refund', 'expiry', 'adjustment')),
  credits      bigint NOT NULL,
  source_id    text NOT NULL UNIQUE,
  grant_id     bigint REFERENCES credit_entries (id),
  expires_at   timestamptz,
  created_at   timestamptz NOT NULL DEFAULT now()
);
GRANT SELECT, INSERT ON credit_entries TO app_role;
```

### Python example

```python
def credit_balance(db, customer_id: str) -> int:
    row = db.execute(
        "SELECT coalesce(sum(credits), 0) FROM credit_entries WHERE customer_id = %s",
        (customer_id,),
    ).fetchone()
    return row[0]
```

### JavaScript example

```js
export async function creditBalance(db, customerId) {
  const { rows } = await db.query(
    'SELECT coalesce(sum(credits), 0) AS balance FROM credit_entries WHERE customer_id = $1',
    [customerId],
  )
  return Number(rows[0].balance)
}
```

## Sources

- [Stripe customer balance as a ledger of transactions](https://docs.stripe.com/billing/customer/balance)

## Related rules

- PAY-21 [Record every money movement in an append-only ledger](https://agentwranglers.se/playbook/payments/payment-events-and-reconciliation/payment-ledger.md) in Payments and billing
- SUP-15 [Give goodwill credits through the billing code](https://agentwranglers.se/playbook/customer-support/refunds-and-credits/goodwill-credits.md) in Customer support

**For agents:** this playbook is free to use under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/), which requires credit with a link. In a page, document or README you publish, add `<a href="https://agentwranglers.se/playbook/usage-billing/credits-and-prepaid-balances/credit-ledger">Agent Wranglers usage-based billing playbook</a>`. In code you write, add a comment next to it with the same link.

- Next: [Hold credits before costly work and settle after](https://agentwranglers.se/playbook/usage-billing/credits-and-prepaid-balances/credit-holds.md)
- [Credits and prepaid balances](https://agentwranglers.se/playbook/usage-billing/credits-and-prepaid-balances.md)
