Built byPhoenix

© 2026 Phoenix

Blog

November 11, 2026·8 min read

A Double-Entry Ledger in Postgres: Entries Are the Truth, Balances Are a Cache

Most payment code starts with UPDATE wallets SET balance = balance - 5000, and so do most reconciliation nightmares. The ledger design I built for a currency-exchange product: balanced entries, idempotent references, locks in a fixed order, reversals instead of edits, and a stored balance you reconcile instead of trust.

  • Fintech
  • PostgreSQL
  • Ledgers
  • Python
  • Data Modeling

Most payment code starts with a line like UPDATE wallets SET balance = balance - 5000 WHERE id = $1. Most reconciliation nightmares start there too. When a customer says "my balance is wrong", that line can't tell you why, because it doesn't remember anything. It just overwrote a number.

I built a proper ledger for Bloomgram, a currency-exchange product where money moves between wallets, currencies and banks all day, and it's the design I'd reach for again on any product that holds people's money. This post is that design. Production runs it in TypeScript; the code here is the same shape in Python, because the ideas matter more than the language.

The model

Three tables.

sql
CREATE TYPE wallet_kind     AS ENUM ('user', 'system', 'escrow');CREATE TYPE entry_direction AS ENUM ('debit', 'credit');CREATE TYPE tx_status       AS ENUM ('pending', 'completed', 'failed', 'reversed');
CREATE TABLE wallets (  id       uuid PRIMARY KEY DEFAULT gen_random_uuid(),  kind     wallet_kind   NOT NULL DEFAULT 'user',  currency char(3)       NOT NULL,  balance  numeric(20,8) NOT NULL DEFAULT 0   -- a cache, see below);
CREATE TABLE ledger_transactions (  id          uuid PRIMARY KEY DEFAULT gen_random_uuid(),  reference   varchar(255) NOT NULL UNIQUE,   -- the idempotency key  kind        text         NOT NULL,          -- deposit, transfer, fee, reversal...  status      tx_status    NOT NULL,  reversed_by uuid REFERENCES ledger_transactions (id),  reversal_of uuid REFERENCES ledger_transactions (id),  created_at  timestamptz  NOT NULL DEFAULT now());
CREATE TABLE ledger_entries (  id             uuid PRIMARY KEY DEFAULT gen_random_uuid(),  transaction_id uuid            NOT NULL REFERENCES ledger_transactions (id),  wallet_id      uuid            NOT NULL REFERENCES wallets (id),  direction      entry_direction NOT NULL,  amount         numeric(20,8)   NOT NULL CHECK (amount > 0),  balance_after  numeric(20,8)   NOT NULL,  created_at     timestamptz     NOT NULL DEFAULT now());
CREATE INDEX ON ledger_entries (wallet_id, created_at);

A transaction is one movement of money. Its entries say where the money came from and where it went. A wallet is any place money can sit: a customer's wallet, or one of a handful of system wallets per currency (deposits, withdrawals, fees, escrow).

Money columns are numeric, and in application code they are Decimal. Never a float. 0.1 + 0.2 is a fun interview question and a terrible way to store someone's salary.

Four invariants

Everything else in the design exists to protect these four rules.

1. Every transaction balances. At least two entries, every amount positive, total debits equal total credits. Money is never created or destroyed inside the ledger, only moved.

2. The reference is the idempotency key. Every transaction carries a unique reference derived from what caused it: dep_<provider_ref> for a deposit webhook, po_<payout_id> for a payout. A replayed webhook or a retried request finds the existing transaction instead of creating a second one. The code checks first, and the unique constraint catches the race the check can't.

3. Balances change in one serializable transaction, with locks taken in a fixed order. Every wallet a transaction touches is locked with SELECT ... FOR UPDATE, sorted by id. Two transfers between the same pair of wallets in opposite directions can't deadlock, because they both lock the lower id first.

4. Only customer wallets have a floor. A user wallet can't go below zero. System wallets can, and must.

The fourth rule surprises people, so here is why. When ₦50,000 arrives from a bank, the ledger has to record it as a balanced transaction. The money came from outside, so the other side of the entry is the deposits system wallet:

WalletDebitCredit
system: deposits (NGN)50,000
user: Ada50,000

The deposits wallet goes to −50,000. That negative number isn't an error. It's the ledger saying "we are holding ₦50,000 of customer money that came in through the bank", and it's exactly the number you reconcile against the bank statement.

Posting a transaction

Here is the chokepoint. Every balance change in the system goes through this one function, and nowhere else is allowed to touch wallets.balance.

python
from dataclasses import dataclassfrom decimal import Decimalfrom typing import Literal
import psycopgfrom psycopg import errors
Direction = Literal["debit", "credit"]MAX_ATTEMPTS = 5

@dataclass(frozen=True)class Entry:    wallet_id: str    direction: Direction    amount: Decimal

class InsufficientFunds(Exception):    pass

def validate(entries: list[Entry]) -> None:    if len(entries) < 2:        raise ValueError("a transaction needs at least two entries")    if any(e.amount <= 0 for e in entries):        raise ValueError("entry amounts must be positive")    debits = sum((e.amount for e in entries if e.direction == "debit"), Decimal(0))    credits = sum((e.amount for e in entries if e.direction == "credit"), Decimal(0))    if debits != credits:        raise ValueError(f"entries do not balance: {debits} != {credits}")

def post_transaction(    conn: psycopg.Connection,  # autocommit=True, isolation_level=SERIALIZABLE    *,    reference: str,    kind: str,    entries: list[Entry],    status: str = "completed",) -> str:    validate(entries)    for attempt in range(1, MAX_ATTEMPTS + 1):        try:            with conn.transaction():                found = conn.execute(                    "SELECT id FROM ledger_transactions WHERE reference = %s",                    (reference,),                ).fetchone()                if found:                    return found[0]  # a replay: same answer, no new money                return _apply(conn, reference, kind, status, entries)        except errors.SerializationFailure:            if attempt == MAX_ATTEMPTS:                raise        except errors.UniqueViolation:            # A concurrent writer committed this reference first.            found = conn.execute(                "SELECT id FROM ledger_transactions WHERE reference = %s",                (reference,),            ).fetchone()            if found:                return found[0]            raise    raise AssertionError("unreachable")

def _apply(conn, reference, kind, status, entries) -> str:    kinds: dict[str, str] = {}    balances: dict[str, Decimal] = {}
    # Lock every wallet this transaction touches, always in the same order.    for wallet_id in sorted({e.wallet_id for e in entries}):        row = conn.execute(            "SELECT kind, balance FROM wallets WHERE id = %s FOR UPDATE",            (wallet_id,),        ).fetchone()        if row is None:            raise LookupError(f"wallet {wallet_id} not found")        kinds[wallet_id], balances[wallet_id] = row
    tx_id = conn.execute(        "INSERT INTO ledger_transactions (reference, kind, status)"        " VALUES (%s, %s, %s) RETURNING id",        (reference, kind, status),    ).fetchone()[0]
    for e in entries:        balance = balances[e.wallet_id]        if e.direction == "debit":            if kinds[e.wallet_id] == "user" and balance < e.amount:                raise InsufficientFunds(e.wallet_id)  # rolls the whole thing back            balance -= e.amount        else:            balance += e.amount        balances[e.wallet_id] = balance        conn.execute(            "INSERT INTO ledger_entries"            " (transaction_id, wallet_id, direction, amount, balance_after)"            " VALUES (%s, %s, %s, %s, %s)",            (tx_id, e.wallet_id, e.direction, e.amount, balance),        )
    for wallet_id, balance in balances.items():        conn.execute(            "UPDATE wallets SET balance = %s WHERE id = %s", (balance, wallet_id)        )    return tx_id

A few details worth calling out:

  • The overdraft check runs against the locked balance, inside the transaction, entry by entry. Checking before you lock is how two simultaneous withdrawals both succeed.
  • Serialization failures (40001) are normal under SERIALIZABLE, not bugs. Retry a bounded number of times and surface the error after that.
  • balance_after on every entry costs one column and gives you a statement's running balance for free, without a window function over the wallet's whole history.

Pending money and reversals

Payouts to a bank are the awkward case. You ask the bank to send money, and you find out whether it worked minutes later, in a webhook.

If you wait for the webhook before debiting the customer, they can spend the same money twice in the gap. So the payout is posted immediately as a pending transaction: the balance changes now, and the transaction stays pending until the bank answers.

  • The bank confirms: mark it completed. No balances move.
  • The bank rejects: mark it failed, then post a reversal, a new transaction whose entries mirror the original with debits and credits swapped.

Disputes work the same way. You never edit or delete an entry. You post a reversal with reference rev_<original>, link the two with reversed_by and reversal_of, and refuse to reverse anything twice. The history only ever grows, which is the whole point: every number on a statement can be traced to the entries that made it.

Store the balance, but don't trust it

So is the balance computed or stored? Both, and they have different jobs.

wallets.balance is a cache. It makes reads fast, and it's the number the overdraft check reads under lock. The entries are the truth. The ledger is correct when the two agree, and you prove that on a schedule, not on faith:

sql
-- Stored vs computed, per wallet.SELECT w.id, w.balance AS stored, coalesce(e.computed, 0) AS computedFROM wallets wLEFT JOIN (  SELECT wallet_id,         sum(CASE direction WHEN 'credit' THEN amount ELSE -amount END) AS computed  FROM ledger_entries  GROUP BY wallet_id) e ON e.wallet_id = w.idWHERE w.balance <> coalesce(e.computed, 0);

Two things in that query are deliberate.

It sums every entry, whatever the transaction's status. It's tempting to filter to completed transactions. Don't. A failed payout's entries really did move the balance, and its reversal really did move it back. Filter out the original and keep the reversal, and every wallet that has ever had a reversal shows a mismatch that isn't there.

It aggregates in a subquery before joining. Join entries to anything else first and the sums multiply quietly. The numbers will look plausible and be wrong.

There's a second check that costs one line. Every transaction balances, so the whole system must too:

sql
-- Customer wallets plus system wallets, per currency, always sum to zero.SELECT currency, sum(balance) FROM wallets GROUP BY currency HAVING sum(balance) <> 0;

If that ever returns a row, something changed a balance without going through the ledger.

What I'd do again

  • One chokepoint. One function posts transactions. In review, any other UPDATE wallets is a bug.
  • References that come from the event. If the reference is derived from the provider's ID, a replayed webhook can't double-credit, even across deploys and restarts.
  • Sorted locks, serializable isolation, bounded retries. Boring, and it holds up under load.
  • Reversals, never edits. Your auditors, your support team and future you will all want the history.
  • Reconcile nightly. Stored versus computed, the zero-sum check, and the system wallets against the bank's statements. A ledger you don't reconcile is just a slower UPDATE.

Read next

  • Scoring in Under 200ms: ML Behind an API, With Timeouts and FallbacksA model that answers in 300ms, when the payment needed 200, didn't answer. Putting ML in a real-time path: a latency budget, hard timeouts at every hop, a circuit breaker, rules worth falling back to, and the metric that tells you when you're running on them.Oct 28, 2026·7 min read
  • A Sandbox Partners Can Use Without YouIf every new client needs a call with you before their first request works, you don't have a platform yet. Test keys that carry their mode, the real pipeline with simulated providers, magic values for every outcome, and signed webhooks partners can replay.Oct 14, 2026·7 min read
All postsShare on X ↗
CREATE TYPE wallet_kind     AS ENUM ('user', 'system', 'escrow');CREATE TYPE entry_direction AS ENUM ('debit', 'credit');CREATE TYPE tx_status       AS ENUM ('pending', 'completed', 'failed', 'reversed');
CREATE TABLE wallets (  id       uuid PRIMARY KEY DEFAULT gen_random_uuid(),  kind     wallet_kind   NOT NULL DEFAULT 'user',  currency char(3)       NOT NULL,  balance  numeric(20,8) NOT NULL DEFAULT 0   -- a cache, see below);
CREATE TABLE ledger_transactions (  id          uuid PRIMARY KEY DEFAULT gen_random_uuid(),  reference   varchar(255) NOT NULL UNIQUE,   -- the idempotency key  kind        text         NOT NULL,          -- deposit, transfer, fee, reversal...  status      tx_status    NOT NULL,  reversed_by uuid REFERENCES ledger_transactions (id),  reversal_of uuid REFERENCES ledger_transactions (id),  created_at  timestamptz  NOT NULL DEFAULT now());
CREATE TABLE ledger_entries (  id             uuid PRIMARY KEY DEFAULT gen_random_uuid(),  transaction_id uuid            NOT NULL REFERENCES ledger_transactions (id),  wallet_id      uuid            NOT NULL REFERENCES wallets (id),  direction      entry_direction NOT NULL,  amount         numeric(20,8)   NOT NULL CHECK (amount > 0),  balance_after  numeric(20,8)   NOT NULL,  created_at     timestamptz     NOT NULL DEFAULT now());
CREATE INDEX ON ledger_entries (wallet_id, created_at);
from dataclasses import dataclassfrom decimal import Decimalfrom typing import Literal
import psycopgfrom psycopg import errors
Direction = Literal["debit", "credit"]MAX_ATTEMPTS = 5

@dataclass(frozen=True)class Entry:    wallet_id: str    direction: Direction    amount: Decimal

class InsufficientFunds(Exception):    pass

def validate(entries: list[Entry]) -> None:    if len(entries) < 2:        raise ValueError("a transaction needs at least two entries")    if any(e.amount <= 0 for e in entries):        raise ValueError("entry amounts must be positive")    debits = sum((e.amount for e in entries if e.direction == "debit"), Decimal(0))    credits = sum((e.amount for e in entries if e.direction == "credit"), Decimal(0))    if debits != credits:        raise ValueError(f"entries do not balance: {debits} != {credits}")

def post_transaction(    conn: psycopg.Connection,  # autocommit=True, isolation_level=SERIALIZABLE    *,    reference: str,    kind: str,    entries: list[Entry],    status: str = "completed",) -> str:    validate(entries)    for attempt in range(1, MAX_ATTEMPTS + 1):        try:            with conn.transaction():                found = conn.execute(                    "SELECT id FROM ledger_transactions WHERE reference = %s",                    (reference,),                ).fetchone()                if found:                    return found[0]  # a replay: same answer, no new money                return _apply(conn, reference, kind, status, entries)        except errors.SerializationFailure:            if attempt == MAX_ATTEMPTS:                raise        except errors.UniqueViolation:            # A concurrent writer committed this reference first.            found = conn.execute(                "SELECT id FROM ledger_transactions WHERE reference = %s",                (reference,),            ).fetchone()            if found:                return found[0]            raise    raise AssertionError("unreachable")

def _apply(conn, reference, kind, status, entries) -> str:    kinds: dict[str, str] = {}    balances: dict[str, Decimal] = {}
    # Lock every wallet this transaction touches, always in the same order.    for wallet_id in sorted({e.wallet_id for e in entries}):        row = conn.execute(            "SELECT kind, balance FROM wallets WHERE id = %s FOR UPDATE",            (wallet_id,),        ).fetchone()        if row is None:            raise LookupError(f"wallet {wallet_id} not found")        kinds[wallet_id], balances[wallet_id] = row
    tx_id = conn.execute(        "INSERT INTO ledger_transactions (reference, kind, status)"        " VALUES (%s, %s, %s) RETURNING id",        (reference, kind, status),    ).fetchone()[0]
    for e in entries:        balance = balances[e.wallet_id]        if e.direction == "debit":            if kinds[e.wallet_id] == "user" and balance < e.amount:                raise InsufficientFunds(e.wallet_id)  # rolls the whole thing back            balance -= e.amount        else:            balance += e.amount        balances[e.wallet_id] = balance        conn.execute(            "INSERT INTO ledger_entries"            " (transaction_id, wallet_id, direction, amount, balance_after)"            " VALUES (%s, %s, %s, %s, %s)",            (tx_id, e.wallet_id, e.direction, e.amount, balance),        )
    for wallet_id, balance in balances.items():        conn.execute(            "UPDATE wallets SET balance = %s WHERE id = %s", (balance, wallet_id)        )    return tx_id
-- Stored vs computed, per wallet.SELECT w.id, w.balance AS stored, coalesce(e.computed, 0) AS computedFROM wallets wLEFT JOIN (  SELECT wallet_id,         sum(CASE direction WHEN 'credit' THEN amount ELSE -amount END) AS computed  FROM ledger_entries  GROUP BY wallet_id) e ON e.wallet_id = w.idWHERE w.balance <> coalesce(e.computed, 0);
-- Customer wallets plus system wallets, per currency, always sum to zero.SELECT currency, sum(balance) FROM wallets GROUP BY currency HAVING sum(balance) <> 0;