Video in progress
How do you model a wallet or account balance: updating a `balance` column, or a ledger that records every change?
In a system that handles money, the foundation is immutable ledger entries (each credit/debit as its own row), with the balance derived from them. For speed I also keep a balance column, but I update it in the same transaction as the ledger entry and under a row lock.
📖 Answer
With only a balance column, there's no answer to "why is the balance 100,000 and not 120,000?". No history, no audit, and a mistake can't be reconstructed.
I usually build it like this:
CREATE TABLE ledger_entry (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
account_id bigint NOT NULL REFERENCES account(id),
amount numeric(19,2) NOT NULL, -- + credit, - debit
op_id uuid NOT NULL, -- idempotency key
created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (account_id, op_id)
);
A withdrawal:
BEGIN;
UPDATE account
SET balance = balance - 50000
WHERE id = 7 AND balance >= 50000; -- if 0 rows, there are insufficient funds
INSERT INTO ledger_entry (account_id, amount, op_id) VALUES (7, -50000, :opId);
COMMIT;
UPDATE ... WHERE balance >= ? is a single atomic operation: the row lock is taken, the condition is re-checked, and two parallel withdrawals can't leave a negative balance. Because op_id is unique, a retried request isn't written a second time.
You never modify or delete a ledger entry; if there's a mistake, you add a reversing entry. A reconciliation job runs every night comparing sum(amount) with balance; if there's a difference, an alert goes out.
For a transfer between two accounts, I always lock both rows in the same order (the smaller id first), otherwise you get a deadlock.
Sign up to mark studied questions and save your progress.