Most payment code starts with a line like UPDATE wallets SET balance = balance - 5000 WHERE id = $1. Most reconciliation nightmares start there too. When a customer says "my balance is wrong", that line can't tell you why, because it doesn't remember anything. It just overwrote a number.
I built a proper ledger for Bloomgram, a currency-exchange product where money moves between wallets, currencies and banks all day, and it's the design I'd reach for again on any product that holds people's money. This post is that design. Production runs it in TypeScript; the code here is the same shape in Python, because the ideas matter more than the language.
The model
Three tables.
A transaction is one movement of money. Its entries say where the money came from and where it went. A wallet is any place money can sit: a customer's wallet, or one of a handful of system wallets per currency (deposits, withdrawals, fees, escrow).
Money columns are numeric, and in application code they are Decimal. Never a float. 0.1 + 0.2 is a fun interview question and a terrible way to store someone's salary.
Four invariants
Everything else in the design exists to protect these four rules.
1. Every transaction balances. At least two entries, every amount positive, total debits equal total credits. Money is never created or destroyed inside the ledger, only moved.
2. The reference is the idempotency key. Every transaction carries a unique reference derived from what caused it: dep_<provider_ref> for a deposit webhook, po_<payout_id> for a payout. A replayed webhook or a retried request finds the existing transaction instead of creating a second one. The code checks first, and the unique constraint catches the race the check can't.
3. Balances change in one serializable transaction, with locks taken in a fixed order. Every wallet a transaction touches is locked with SELECT ... FOR UPDATE, sorted by id. Two transfers between the same pair of wallets in opposite directions can't deadlock, because they both lock the lower id first.
4. Only customer wallets have a floor. A user wallet can't go below zero. System wallets can, and must.
The fourth rule surprises people, so here is why. When ₦50,000 arrives from a bank, the ledger has to record it as a balanced transaction. The money came from outside, so the other side of the entry is the deposits system wallet:
The deposits wallet goes to −50,000. That negative number isn't an error. It's the ledger saying "we are holding ₦50,000 of customer money that came in through the bank", and it's exactly the number you reconcile against the bank statement.
Posting a transaction
Here is the chokepoint. Every balance change in the system goes through this one function, and nowhere else is allowed to touch wallets.balance.
A few details worth calling out:
- The overdraft check runs against the locked balance, inside the transaction, entry by entry. Checking before you lock is how two simultaneous withdrawals both succeed.
- Serialization failures (
40001) are normal underSERIALIZABLE, not bugs. Retry a bounded number of times and surface the error after that. balance_afteron every entry costs one column and gives you a statement's running balance for free, without a window function over the wallet's whole history.
Pending money and reversals
Payouts to a bank are the awkward case. You ask the bank to send money, and you find out whether it worked minutes later, in a webhook.
If you wait for the webhook before debiting the customer, they can spend the same money twice in the gap. So the payout is posted immediately as a pending transaction: the balance changes now, and the transaction stays pending until the bank answers.
- The bank confirms: mark it
completed. No balances move. - The bank rejects: mark it
failed, then post a reversal, a new transaction whose entries mirror the original with debits and credits swapped.
Disputes work the same way. You never edit or delete an entry. You post a reversal with reference rev_<original>, link the two with reversed_by and reversal_of, and refuse to reverse anything twice. The history only ever grows, which is the whole point: every number on a statement can be traced to the entries that made it.
Store the balance, but don't trust it
So is the balance computed or stored? Both, and they have different jobs.
wallets.balance is a cache. It makes reads fast, and it's the number the overdraft check reads under lock. The entries are the truth. The ledger is correct when the two agree, and you prove that on a schedule, not on faith:
Two things in that query are deliberate.
It sums every entry, whatever the transaction's status. It's tempting to filter to completed transactions. Don't. A failed payout's entries really did move the balance, and its reversal really did move it back. Filter out the original and keep the reversal, and every wallet that has ever had a reversal shows a mismatch that isn't there.
It aggregates in a subquery before joining. Join entries to anything else first and the sums multiply quietly. The numbers will look plausible and be wrong.
There's a second check that costs one line. Every transaction balances, so the whole system must too:
If that ever returns a row, something changed a balance without going through the ledger.
What I'd do again
- One chokepoint. One function posts transactions. In review, any other
UPDATE walletsis a bug. - References that come from the event. If the reference is derived from the provider's ID, a replayed webhook can't double-credit, even across deploys and restarts.
- Sorted locks, serializable isolation, bounded retries. Boring, and it holds up under load.
- Reversals, never edits. Your auditors, your support team and future you will all want the history.
- Reconcile nightly. Stored versus computed, the zero-sum check, and the system wallets against the bank's statements. A ledger you don't reconcile is just a slower
UPDATE.