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 v1.0.0
Stack: Python 3.11+, FastAPI, SQLAlchemy 2,
sqlalchemy-cockroachdb,
psycopg 3 and Alembic.
Get the code
The code is in the Cockroach Cookbook repository. To fetch only this project at the version this page describes:Run it locally
You need Python 3.11 or later and thecockroach binary, v26.1 or later.
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
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
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 and use its connection string in the same steps. Continuum pricing differs from the Basic prices on this page; see Continuum pricing.
- Create a Basic cluster and a SQL
user, then run
CREATE DATABASE ledger;in a SQL shell on it. - Set
MIGRATION_DATABASE_URLto that user’s connection string with/ledgeras the database andcockroachdb+psycopg://as the scheme, then runalembic upgrade head. - Give the app’s role a password:
ALTER ROLE ledger_app WITH PASSWORD '<a strong password>'; - Set
DATABASE_URLto the same host withledger_app, its password andsslmode=verify-full, then runpytestagainst 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, 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
SERIALIZABLEisolation, 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.

