For six years a balance on Ledgerly was a sum. Ask for an account's balance and we added up its entries. It was always correct, and at the end of a busy month it was also slow: our largest customer has accounts with forty million entries.
This autumn we changed that. Balances are now stored, updated in the same transaction as every entry, and readable in under five milliseconds at any size. This post is about how, and about the property we refused to trade for it: every transaction still balances, to the penny, before it is allowed to exist.
Double entry, briefly
Every movement of money touches at least two accounts: what leaves one arrives in another. Debits on the left, credits on the right; the two sides of every transaction add up to the same amount. Read along and the ledger beside this text will post a small marketplace's first afternoon.
- 1
A buyer pays £120 for a jacket. The money arrives in the platform's bank account, and the platform now owes most of it to the seller and keeps a fee.
- 2
The payment processor takes its cut. Cash goes down and a cost goes up by the same amount: two lines, one transaction, still balanced.
- 3
The buyer returns a scarf from an earlier order for £20. The platform refunds them and claws the money back from that seller.
- 4
At five o'clock the platform pays the seller what it owes. The liability is cleared; the cash leaves. Every transaction balanced, so the whole ledger balances.
Where the time went
Summing entries is linear in the number of entries. We had indexes, caches and a nightly snapshot, and each helped until it did not. The snapshot made reads fast and made every write after it a little more expensive to reason about.
-- before: a balance was a sumSELECT COALESCE(SUM(CASE side WHEN 'dr' THEN amount ELSE -amount END), 0)FROM entriesWHERE account_id = $1 AND posted_at <= $2;Posting with the balance
Now an entry and the balance it changes are written together. A transaction takes a row lock on each account it touches, in account-id order so two transactions can never wait on each other, checks that its lines sum to zero, writes the entries and moves the balances. If any step fails, none of it happened.
BEGIN;-- lock accounts in a fixed order: no deadlocksSELECT id FROM accounts WHERE id = ANY($1) ORDER BY id FOR UPDATE;-- the lines must sum to zero, or nothing is writtenINSERT INTO entries (txn_id, account_id, side, amount) SELECT * FROM unnest($2, $3, $4, $5);UPDATE accounts a SET balance = a.balance + d.deltaFROM (SELECT account_id, SUM(CASE side WHEN 'dr' THEN amount ELSE -amount END) AS delta FROM entries WHERE txn_id = $2[1] GROUP BY account_id) dWHERE a.id = d.account_id;COMMIT;The lock we kept
Hot accounts, like a platform's fee account that every payment touches, were the worry. A row lock on one account serialises every transaction that touches it. We measured before guessing: at our busiest minute in October the fee account of our largest customer saw 1,900 postings, and each lock was held for 0.4 milliseconds. Serial is fast enough.
- balance read at p99, any account size
- 4.2 ms
- unbalanced transactions since launch
- 0
- postings a minute on the hottest account
- 1,900
For the few customers above that we offer sharded system accounts: the fee account becomes sixteen, each posting picks one, and the balance you read is their sum. It is the only place a balance is still a sum, and it is a sum of sixteen.
What we would tell ourselves
- Keep the invariant in the database, not just the code.
- Lock in a fixed order and you will never debug a deadlock at month end.
- Measure the hot account before designing for it.
- Ship the new read path behind a comparison: for three weeks we computed both and alerted on any difference. There were two, both in the old path.