knaxuslearn · build · ship

Projects / Bank ledger / Wrap up

Wrap up

Keep going

Pick one when you want more:

  • Point-in-time recovery. Turn on WAL archiving, wreck a table on purpose and rewind to a minute before. The PostgreSQL backup chapter walks through it.
  • Cheaper balances. sum() over an account's entries gets slower as history grows. Keep a running balance per account, updated by the same transaction, and compare.
  • Currencies. Refuse a transfer between accounts in different currencies, then add exchange accounts.
  • Stronger isolation. Redo Phase 4 with SERIALIZABLE transactions instead of row locks, and handle the retry errors it raises.
  • Partitioning. Split entries by month so old data can be archived cheaply.

What this version leaves out, and what a real ledger does

We kept the ideas and dropped the weight.

  • Real systems keep balances as stored columns or periodic snapshots, so reading a balance does not scan history.
  • Real ledgers tag accounts as assets, liabilities and so on, and report on them. Ours only tracks who holds what.
  • We turned the balance trigger off for the bulk load. Real loads go through a reviewed path with checks afterwards.
  • Idempotency keys need an expiry, a stored response and a hash of the request, so a reused key with a different amount is rejected and not silently ignored.
  • We locked rows in PL/pgSQL for clarity. Many teams do it in application code, or with advisory locks. The ideas are the same.

Check yourself

Answer each question in your head first, then open it to check.

  1. Why is a ledger's total always zero, and what would it mean if it were not?
    Every entry has a mirror entry, so the sum of all entries is zero. A non-zero total means money appeared from nowhere or vanished.
  2. The deferred trigger in Step 2.1 runs at COMMIT. What would go wrong if it ran after each row?
    The first entry of every transfer would look lopsided on its own, so the check would fail and no transfer could ever be inserted. Running it at COMMIT lets the check see the whole transfer.
  3. Why did the first race in Step 4.2 pass every one-at-a-time test?
    Each test ran one transfer at a time, so the balance check and the write never overlapped. The bug only exists when two transfers interleave.
  4. Why does locking accounts in id order prevent deadlocks?
    A cycle of waiting needs someone who holds a higher id while waiting for a lower one. A fixed order makes that impossible, so nobody waits in a circle.
  5. Teach it back: explain to a teammate why a foreign key does not make a column fast to search.
    A foreign key only checks that the target row exists. It does not create an index on the column that holds it, so looking rows up by that column needs a separate index.

Sources