Video in progress

How do you build the data model for a wallet and payments system, and why isn't storing the balance in a single column enough?

Money movement is stored as immutable double-entry ledger records: each operation is a debit and credit pair that sums to zero. The balance is a number derived from the records (and cached); the payment itself is kept in check by an explicit state machine and regular reconciliation with the provider.

📖 Answer

Systems that start with UPDATE wallets SET balance = balance - 100 run into the same question a year later: "why does this user's balance say 37,000 soums while the history shows a different amount?". A column knows only the latest state, not how it got there. When there's an error or a duplicate, you can't reconstruct what happened.

The ledger. Every operation is at least two entries, summing to zero:

CREATE TABLE ledger_entries (
  id          BIGSERIAL PRIMARY KEY,
  txn_id      UUID NOT NULL,
  account_id  BIGINT NOT NULL,
  amount      BIGINT NOT NULL,     -- in tiyin; negative = debit
  created_at  TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- SUM(amount) = 0 for every txn_id

A user paid 50,000 soums: user_wallet -50000, merchant_payable +49000, platform_fee +1000. Entries are never modified or deleted; a mistake is fixed with a reversing entry. This is exactly what audits, taxes and disputes need.

The balance isn't computed with SUM every time: accounts.balance + version are stored too and updated in the same transaction as the ledger entry. Not going negative is enforced by UPDATE ... WHERE balance >= :amount or a CHECK constraint. A check that balance = SUM(entries) runs periodically — if there's a difference, that's an alert.

The payment status is separate: CREATED → AUTHORIZED → CAPTURED → SETTLED, or FAILED, REFUNDED. Transitions follow only the allowed ones (UPDATE ... WHERE status = 'AUTHORIZED'), and each is written to history. The most dangerous state is UNKNOWN: the request went to the provider and no response came. You can't just retry it; a separate job that asks the provider for the status resolves it.

Reconciliation. Every day, the provider's report (the settlement file) is compared with your ledger: present on your side but not theirs; amount differences; charged twice. Without it, errors go unnoticed for months.

Extra rules: money is only an integer (tiyin) or BigDecimal, never double; an idempotency key on every operation; the currency on every entry.