qodebase logoqodebase
← qodebase

Unit 2 — record every cent twice and prove the books always balance

Double-Entry Ledger & Reconciliation

In Unit 1 we charged a card exactly once. But "the charge succeeded" is not the same as "the money is accounted for." That same $20 has to land in the merchant's balance, minus your fee, and every party's books have to agree — forever, across millions of transactions a day, even when a process crashes mid-write.

The data structure that makes this tractable is six centuries old: the double-entry ledger. This unit builds one, derives the invariant that guarantees it can never silently lose money, and writes the reconciliation pass that catches corruption.

Sub-unit 1 of 6

Why a balance can't be a single number

The tempting design is a balances table with one row per account and an amount column you increment. It falls apart immediately:

  • An increment is a destructive update — if it runs twice (hello, retries from Unit 1) or half-completes, the balance is silently wrong and there is no record of what it should be.
  • You cannot answer "why is this balance what it is?" There is no history, only a final number.
  • Two concurrent updates race on the same row.

A ledger flips this around. You never mutate a balance. You only ever append immutable entries, and a balance is derived by summing entries. The history is the source of truth.

Finished reading? Mark this sub-unit complete to unlock the next.