Balanced
Every movement is two or more entries that sum to zero per currency. A deferred constraint trigger makes the database refuse to commit anything else — so money is neither created nor destroyed.
Double-entry ledger over HTTP
Atomic, idempotent and append-only. Whatever the concurrency, the retries or the crashes, each transfer sums to zero in every currency — and PostgreSQL refuses to commit one that doesn't.
numeric(38,18)Every movement is two or more entries that sum to zero per currency. A deferred constraint trigger makes the database refuse to commit anything else — so money is neither created nor destroyed.
Entries and transactions are never updated or deleted — triggers enforce it. Mistakes are undone by reversal transactions, at most once each.
Every write needs an Idempotency-Key. Retries replay the first response, byte for byte, even when it was an error.
Row locks are taken in ascending account id: no overdrafts, no deadlocks, no retry loops.
Never stored. Computed from entries, with snapshots taken only under the account lock.
A transactional outbox emits every change at least once — to a log, a Redis stream or an HMAC-signed webhook — and reconcile re-checks every invariant, exiting 1 on any discrepancy.
INSERT … ON CONFLICT inside the operation's own transaction. A duplicate replays; a different body is 409.SELECT … FOR UPDATE ORDER BY id on every account touched. Opposing transfers queue instead of deadlocking.COMMIT. If it fails, nothing happened.SKIP LOCKED and delivers at least once, with a stable id to dedupe on.Every route but /healthz needs a bearer token; every POST needs an Idempotency-Key. Amounts are decimal strings, never JSON numbers. OpenAPI docs live at /docs.
curl -s localhost:8000/v1/transfers \
-H "Authorization: Bearer $TOKEN" \
-H "Idempotency-Key: $(uuidgen)" \
-H "Content-Type: application/json" \
-d '{"from": "<account-id>", "to": "<account-id>",
"amount": "12.50", "currency": "USD"}'
POST/v1/accountsOpen an account
GET/v1/accounts/{id}Read an account
PATCH/v1/accounts/{id}Freeze / unfreeze
GET/v1/accounts/{id}/balanceledger, held, available; ?as_of=
GET/v1/accounts/{id}/entriesEntries, newest first
POST/v1/depositsMoney in
POST/v1/withdrawalsMoney out
POST/v1/transfersAccount to account
POST/v1/transactionsAny balanced set of 2–50 entries
POST/v1/transactions/{id}/reverseExact, linked negation
GET/v1/transactions[/{id}]List & read, filterable
POST/v1/holdsReserve funds, optional expiry
POST/v1/holds/{id}/captureMove up to the held amount
POST/v1/holds/{id}/releaseLet the funds go
GET/v1/holds[/{id}]active · captured · released · expired
RFC 9457 problem details with a stable code.
Each carries a stable id to deduplicate on.
Publishers: log, redis, or webhook signed with HMAC-SHA256 in X-Ledger-Signature.
| Invariant | Enforced by | Proven by |
|---|---|---|
| Entries sum to zero per currency | Deferred constraint trigger at COMMIT | Hypothesis random programs |
| Entries & transactions never change | BEFORE UPDATE OR DELETE triggers | test_append_only |
| No overdraft, counting holds | Row locks in id order + funds check | 100 racing withdrawals → exactly 10 succeed |
| No deadlocks | Locks in ascending id | Opposing transfers test |
| One key, one effect | INSERT … ON CONFLICT in-transaction | 50 identical requests → 1 transaction |
| Reversed at most once | Unique reverses_id + lock | Contention test |
| One event per change | Outbox row in the same transaction | Parallel workers publish each once |
| Exact amounts | Decimal + numeric(38,18) + scale check | test_money |
k6, 4 gunicorn workers, 20 VUs, every request on a fresh key, on a laptop under Docker Desktop. Runs varied about ±30% — read it as the shape of the trade-off, not a capacity figure. A hot account halves throughput because every posting queues on one row lock.
reconcile catches the rest.Needs Docker. Starts the API on :8000, the outbox worker, PostgreSQL and Redis. Tests run against real PostgreSQL — there is no SQLite fallback.
cp .env.example .env
docker compose up -d --build
TOKEN=$(docker compose exec -T api python manage.py create_api_client demo)
curl -s localhost:8000/v1/accounts \
-H "Authorization: Bearer $TOKEN" -H "Idempotency-Key: $(uuidgen)" \
-H 'Content-Type: application/json' \
-d '{"owner_id": "alice", "currency": "USD"}'
make check # ruff, mypy --strict, pytest
make reconcile # verify every ledger invariant
outbox_worker | Always running; publishes events, finishes its batch on SIGTERM |
reconcile | Nightly; exits 1 on any discrepancy — alert on it |
expire_holds | Optional cron; balances are already correct without it |
snapshot_balances | Optional, off-peak; busy accounts snapshot inline |