knaxuslearn · build · ship

Projects / Bank ledger

PostgreSQL · about 10 hours · 4 phases

Build a bank ledger in PostgreSQL

How does a bank make sure money never appears from nowhere or vanishes into thin air, even when thousands of people pay each other at the same moment? In about 10 hours you will build the answer yourself: a small ledger in PostgreSQL that refuses bad data, balances to zero, runs fast on a million rows and holds up when transfers race each other.

You work in four phases of about 2.5 hours each. Every phase ends with something you can run and see, so you always know whether you are done. By the end you will have:

  • a schema that rejects five kinds of bad data on its own,
  • a transfer() function that never breaks the books and is safe to retry,
  • a million-row ledger where the slow queries went from tens of milliseconds to well under one,
  • twenty transfers fired at once that leave exactly the right balance.

You only need to know basic SQL: SELECT, INSERT and CREATE TABLE. Everything else is explained when it first shows up.

The four phases

  1. Tables that refuse bad data

    You end with five bad rows, and the database refuses all five by itself.

    • 1.1 Accounts30 min
    • 1.2 Transfers and entries40 min
    • 1.3 Put in three accounts20 min
    • 1.4 Try to break it60 min
  2. Transfers that never break the books

    You end with a transfer() function that moves money, can be retried safely, and a ledger that always adds up to zero.

    • 2.1 Every transfer must add up to zero35 min
    • 2.2 History cannot be rewritten25 min
    • 2.3 The transfer function45 min
    • 2.4 A balances view20 min
    • 2.5 Use it25 min
  3. Make it fast on a million rows

    You end with a ledger of a million entries, and the numbers that show what two indexes did.

    • 3.1 Load a million entries45 min
    • 3.2 Measure before you fix anything45 min
    • 3.3 Add two indexes30 min
    • 3.4 Measure again30 min
  4. Make it survive a crowd

    You end with twenty transfers fired at the same moment against an account that can only afford ten, and exactly ten go through.

    • 4.1 Refuse to overdraw20 min
    • 4.2 Break it with two people35 min
    • 4.3 Fix it with a row lock20 min
    • 4.4 Find the next bug, a deadlock35 min
    • 4.5 Lock in a fixed order25 min
    • 4.6 The final test15 min

Start with the setup →