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

# Payments ledger on CockroachDB (FastAPI)

> A double-entry payments ledger that stays correct under concurrent transfers: accounts with balances, transfers that move money between them, and an entry for each side of every transfer.

> [!NOTE]
>
> **Blueprint** · **Works on:** Cockroach Continuum, CockroachDB Cloud, self-hosted · **Tested:** weekly in CI against the latest CockroachDB · **Stack:** Python, FastAPI, SQLAlchemy 2 · **Code:** [`blueprints/payments-ledger-fastapi`](https://github.com/cockroachlabs/cockroach-cookbook/tree/blueprints/payments-ledger-fastapi/v1.0.0/blueprints/payments-ledger-fastapi) v1.0.0

A double-entry payments ledger that stays correct under concurrent transfers: accounts with balances,
transfers that move money between them, and an entry for each side of every transfer. It goes with the
Cockroach University course **Build a Payments Ledger That Stays Correct Under Concurrency**.

What keeps it correct:

| Rule | Enforced by |
| - | - |
| A customer balance never goes below zero | The `accounts_no_overdraft` CHECK constraint, whatever the code does |
| A retried request moves money once | An `Idempotency-Key` header stored under a UNIQUE constraint, which also makes an ambiguous commit (`40003`) safe to run again |
| Concurrent transfers don't conflict | `SELECT ... FOR UPDATE` on both accounts, in id order, before anything else |
| A conflict that still happens is retried | `run_transaction` from `sqlalchemy-cockroachdb`, on SQLSTATE `40001` |
| History can't be rewritten | The app's role can insert transfers and entries but not update or delete them |

Stack: Python 3.11+, FastAPI, SQLAlchemy 2, [`sqlalchemy-cockroachdb`](https://github.com/cockroachdb/sqlalchemy-cockroachdb),
psycopg 3 and Alembic.

## Get the code

The code is in the [Cockroach Cookbook](https://github.com/cockroachlabs/cockroach-cookbook) repository. To fetch only this project at the version this page describes:

```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
git clone --filter=blob:none --sparse https://github.com/cockroachlabs/cockroach-cookbook.git
cd cockroach-cookbook
git sparse-checkout set blueprints/payments-ledger-fastapi
git checkout blueprints/payments-ledger-fastapi/v1.0.0
cd blueprints/payments-ledger-fastapi
```

## Run it locally

You need Python 3.11 or later and the [`cockroach` binary](https://docs.cockroachlabs.com/docs/stable/install-cockroachdb), v26.1 or later.

```sh theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
python3 -m venv .venv && . .venv/bin/activate
pip install -r requirements.txt
sh scripts/local-db.sh          # starts an insecure local node and creates the ledger database
cp .env.example .env
alembic upgrade head            # tables, constraints and the ledger_app role
pytest                          # 14 tests, including the concurrency tests
uvicorn ledger.api:app --reload # http://localhost:8000/docs
```

`python scripts/isolation-demo.py` shows what the CHECK constraint is for: 20 naive transfers race to
spend the same 1,000 under READ COMMITTED with and without it, and under SERIALIZABLE without retries.

## The API

| Method and path | What it does |
| - | - |
| `POST /accounts` | Create an account: `{"name", "currency", "kind"}`, where `kind` is `customer` or `external` |
| `GET /accounts/{id}` | An account and its balance |
| `GET /accounts/{id}/entries` | The account's entries, newest first |
| `POST /transfers` | Move money. Needs an `Idempotency-Key` header. `201` when it moves money, `200` when it replays an earlier transfer with the same key, `422` for insufficient funds, a currency mismatch or a key reused for a different transfer, `404` for an unknown account |

Amounts are integers in the currency's minor unit (cents for USD). An `external` account stands for money
outside the ledger, such as a bank, and can go negative; fund customer accounts from one.

## Run it on CockroachDB Basic

> [!NOTE]
>
> These steps use a CockroachDB Basic cluster, which existing CockroachDB Cloud organizations can create. New organizations are on Cockroach Continuum: create a cluster with the [Continuum quickstart](https://docs.cockroachlabs.com/docs/continuum/tutorial-quickstart.md) and use its connection string in the same steps. Continuum pricing differs from the Basic prices on this page; see [Continuum pricing](https://docs.cockroachlabs.com/docs/continuum/pricing.md).

1. [Create a Basic cluster](https://docs.cockroachlabs.com/docs/cockroachcloud/create-a-basic-cluster.md) and a SQL
   user, then run `CREATE DATABASE ledger;` in a SQL shell on it.
2. Set `MIGRATION_DATABASE_URL` to that user's [connection string](https://docs.cockroachlabs.com/docs/cockroachcloud/connect-to-your-cluster.md)
   with `/ledger` as the database and `cockroachdb+psycopg://` as the scheme, then run `alembic upgrade head`.
3. Give the app's role a password: `ALTER ROLE ledger_app WITH PASSWORD '<a strong password>';`
4. Set `DATABASE_URL` to the same host with `ledger_app`, its password and `sslmode=verify-full`, then run
   `pytest` against it and deploy the app with both variables set.

## What it costs

CockroachDB Basic charges for Request Units (RUs) and storage, and scales to zero when idle: $0.20 per million
RUs and $0.50 per GiB-month, with a \$15 monthly allowance for pay-as-you-go organizations
([Plan a CockroachDB Basic cluster](https://docs.cockroachlabs.com/docs/cockroachcloud/plan-your-cluster-basic.md), October 2026).
A transfer here is one transaction of four statements; the cluster's **Overview** page shows the RUs yours use.

## Start small, grow without switching

* A ledger needs correct transactions from its first transfer, not only at scale. Here that comes from
  constraints, one transaction per transfer and `SERIALIZABLE` isolation, which is CockroachDB's default.
* The same code runs on a laptop node and on a CockroachDB Basic cluster that scales to zero when idle. If the
  ledger later needs more throughput, more regions or to survive a region failure, the database you started
  on already does that, behind the same PostgreSQL wire protocol.

## License

The code is Apache-2.0 licensed.
