Database & Performance··2 min read

Designing an Immutable Double-Entry Financial Ledger in PostgreSQL With Serializable Isolation and Zero Race Conditions

Shafikul Islam

Shafikul Islam

Backend & Cloud Infrastructure Engineer · Infrastructure & Cloud Team Lead

Designing an Immutable Double-Entry Financial Ledger in PostgreSQL With Serializable Isolation and Zero Race Conditions

Why UPDATE users SET balance = balance - 100 Is Dangerous

In early prototypes, developers often store wallet or tenant credit balances as a single mutable column on the accounts table.

When an invoice dispute, partial refund, or concurrent payout happens six months later, a mutable column destroys the audit trail. Worse, under PostgreSQL's default READ COMMITTED isolation, two concurrent withdrawal checks can read the same starting balance unless row locking and ledger constraints are enforced strictly.


1. The Append-Only Double-Entry Schema

In a true double-entry ledger, money never appears or disappears. Every financial event records a journal_transaction with two or more ledger_entries whose signed integer minor units (cents) sum to 0:

CREATE TABLE ledger_accounts (
    account_id UUID PRIMARY KEY,
    tenant_id UUID NOT NULL,
    currency CHAR(3) NOT NULL,
    cached_balance_cents BIGINT NOT NULL DEFAULT 0,
    version BIGINT NOT NULL DEFAULT 0,
    CONSTRAINT positive_operating_balance CHECK (cached_balance_cents >= 0)
);

CREATE TABLE ledger_entries (
    entry_id UUID PRIMARY KEY,
    transaction_id UUID NOT NULL,
    account_id UUID NOT NULL REFERENCES ledger_accounts(account_id),
    amount_cents BIGINT NOT NULL, -- negative for debit, positive for credit
    idempotency_key VARCHAR(120) NOT NULL UNIQUE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

2. Deterministic Lock Ordering to Prevent Deadlocks

When transferring funds between Account A and Account B inside a transaction, locking A then B in Request 1 while Request 2 locks B then A triggers a classic PostgreSQL deadlock.

We enforce sorted UUID lock ordering in every transfer transaction:

BEGIN;

-- Always lock both accounts in deterministic lexicographical UUID order
SELECT account_id, cached_balance_cents
FROM ledger_accounts
WHERE account_id IN ($1, $2)
ORDER BY account_id ASC
FOR UPDATE;

INSERT INTO ledger_entries (entry_id, transaction_id, account_id, amount_cents, idempotency_key)
VALUES
  ($3, $4, $1, -5000, $5 || ':debit'),
  ($6, $4, $2,  5000, $5 || ':credit');

UPDATE ledger_accounts
SET cached_balance_cents = cached_balance_cents + CASE WHEN account_id = $1 THEN -5000 ELSE 5000 END,
    version = version + 1
WHERE account_id IN ($1, $2);

COMMIT;

3. Blocking UPDATE and DELETE via Trigger

Finally, we attach a BEFORE UPDATE OR DELETE trigger on ledger_entries that raises an exception on any mutation attempt. Corrections can only happen by inserting a new reversing journal entry, giving finance and compliance teams a 100% verifiable audit trail.

Infrastructure & PostgreSQL Advisory

Scaling Infrastructure or Diagnosing P95 Latency?

I help engineering teams diagnose PostgreSQL indexing bottlenecks, concurrency limits, and K3s/Docker deployments. Book a 20-minute call with me to review your setup.

Related Technical Articles