← Back to SQL, page 20

sql-0394 · Hard senior

Design the ledger for an in-app wallet so balances are always explainable.

Use double-entry bookkeeping: every transfer is a transaction with two or more entries whose amounts sum to zero, written atomically. Balances are the sum of an account's entries, optionally cached with the cache updated in the same transaction. Entries are never updated or deleted; corrections are new reversing entries.

Full answer
text
accounts(id, owner_id, currency, kind)                 -- user wallet, cash, fees, ...
ledger_transactions(id, kind, reference, created_at)
ledger_entries(id, transaction_id FK, account_id FK, amount_minor BIGINT, created_at)
account_balances(account_id PK, balance_minor BIGINT, CHECK (balance_minor >= 0 OR kind ...))

A top-up of 500 from a card: entries +500 to the user's wallet and -500 to the external funding account, in one transaction. A purchase moves money from wallet to merchant; a fee adds a third entry to a fees account. A check that SUM(amount_minor) = 0 per transaction (in a trigger or a periodic audit) catches bugs.

Why this shape:

  • Every balance can be recomputed from entries and reconciled with the cached value.
  • History is immutable, which auditors and dispute handling require.
  • Overdraft protection is a conditional update on the cached balance (... WHERE balance_minor >= :amount) in the same transaction as the entries.

Idempotency keys on ledger_transactions.reference stop a retried request from posting twice.

Key points

  • Entries per transaction sum to zero
  • Never update or delete entries
  • Balances are sums, cached atomically
  • Conditional update prevents overdrafts
  • Idempotency keys on transactions

Common mistakes

  • A single mutable balance column with no history
  • Fixing mistakes by editing old rows

Follow-ups

  • How would you reconcile with the payment provider?
  • How would you handle currency conversion in the ledger?

Tips

  • State the sum-to-zero rule