Double-entry ledger over HTTP

Every debit
has a credit.
Always.

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.

  • Python 3.12+
  • Django 6.1
  • Django Ninja
  • PostgreSQL 16
  • Redis (optional)
113
tests, incl. property-based & 40-thread races
11
invariants, each with the test that proves it
8
reconciliation checks against the raw tables
0
floats — decimal strings and numeric(38,18)

Guarantees, not good intentions

01

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.

02

Append-only

Entries and transactions are never updated or deleted — triggers enforce it. Mistakes are undone by reversal transactions, at most once each.

03

Idempotent

Every write needs an Idempotency-Key. Retries replay the first response, byte for byte, even when it was an error.

04

Deadlock-free

Row locks are taken in ascending account id: no overdrafts, no deadlocks, no retry loops.

05

Derived balances

Never stored. Computed from entries, with snapshots taken only under the account lock.

06

Observable

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.

Life of a transfer

  1. Claim the keyINSERT … ON CONFLICT inside the operation's own transaction. A duplicate replays; a different body is 409.
  2. Lock in orderSELECT … FOR UPDATE ORDER BY id on every account touched. Opposing transfers queue instead of deadlocking.
  3. ValidateAmounts fit the currency's minor unit, legs sum to zero per currency, available funds (ledger minus holds) cover the debit.
  4. Write onceEntries, any snapshot and the outbox event land in the same transaction. Nothing is ever updated.
  5. CommitA deferred constraint trigger re-checks the balance at COMMIT. If it fails, nothing happened.
  6. PublishA worker drains the outbox with SKIP LOCKED and delivers at least once, with a stable id to dedupe on.

One request.
One atomic transfer.

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"}'

Accounts

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

Money movement

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

Holds

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

Errors you can program against

RFC 9457 problem details with a stable code.

  • 422validation_error · invalid_amount · unknown_currency · currency_mismatch · unbalanced_transaction · incompatible_accounts · insufficient_funds · invalid_expiry
  • 409idempotency_conflict · already_reversed · not_reversible · hold_not_active · account_inactive
  • 400idempotency_key_required · invalid_cursor
  • 401 · 404unauthenticated · not_found

Events, at least once

Each carries a stable id to deduplicate on.

  • transaction.posted
  • account.created
  • hold.created
  • hold.captured
  • hold.released
  • hold.expired

Publishers: log, redis, or webhook signed with HMAC-SHA256 in X-Ledger-Signature.

Every claim has a test

InvariantEnforced byProven by
Entries sum to zero per currencyDeferred constraint trigger at COMMITHypothesis random programs
Entries & transactions never changeBEFORE UPDATE OR DELETE triggerstest_append_only
No overdraft, counting holdsRow locks in id order + funds check100 racing withdrawals → exactly 10 succeed
No deadlocksLocks in ascending idOpposing transfers test
One key, one effectINSERT … ON CONFLICT in-transaction50 identical requests → 1 transaction
Reversed at most onceUnique reverses_id + lockContention test
One event per changeOutbox row in the same transactionParallel workers publish each once
Exact amountsDecimal + numeric(38,18) + scale checktest_money

Performance, honestly

spread · no contention78 /sp95 364 ms
hot · one shared account35 /sp95 1.08 s

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.

Known limitations

Run it in two minutes

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_workerAlways running; publishes events, finishes its batch on SIGTERM
reconcileNightly; exits 1 on any discrepancy — alert on it
expire_holdsOptional cron; balances are already correct without it
snapshot_balancesOptional, off-peak; busy accounts snapshot inline

Build on a ledger that
can't lose a cent.