PAYMENT LEDGER
Money is never created or destroyed, only moved
You move both legs of every transfer (the debit and the credit) into one database transaction. A client sends a transfer, the server commits it, and the response is lost on the way back. The client retries. What happens?
A ledger has one law: money only moves. Every transfer debits one account and credits another by the same amount, so the sum of all balances never changes. Two things break that law in practice. A crash between the debit and the credit destroys money. A client that times out and retries applies the transfer twice. The fix is two mechanisms together: write both legs as journal entries in one transaction, so a crash leaves all or nothing, and commit an idempotency key in that same transaction, so a retry finds the key and returns the original result.
-- one autocommit statement per leg, no key
UPDATE accounts SET balance = balance - 30 WHERE id = 'alice';
-- crash here: $30 is gone
UPDATE accounts SET balance = balance + 30 WHERE id = 'bob';
-- response lost here: the client retries and both run againBEGIN;
INSERT INTO idempotency_keys (key, result) VALUES ('k-7f3a', 'ok')
ON CONFLICT (key) DO NOTHING RETURNING key;
-- no row back: a retry. ROLLBACK and return the stored result instead
SELECT balance FROM accounts WHERE id = 'alice' FOR UPDATE;
-- funds check: locking the account row serializes transfers from alice
-- (row locks on entries would not stop a concurrent INSERT)
INSERT INTO entries (txn, account, amount) VALUES
('k-7f3a', 'alice', -30),
('k-7f3a', 'bob', +30); -- the legs of one transfer always sum to 0
UPDATE accounts SET balance = balance - 30 WHERE id = 'alice';
UPDATE accounts SET balance = balance + 30 WHERE id = 'bob';
-- cached balance = SUM(amount), kept in the same txn
COMMIT; -- both legs and the key, or none of them Watch both invariants and the “legs that took effect” row. UPDATE IN PLACE double-applies T1 when the response is lost, then loses $50 when the crash lands between T2’s two statements. TRANSACTION, NO KEY survives the crash with the books balanced, but T1 still moves twice. FIX: JOURNAL + KEY rolls back the half-written T2, answers the T1 retry from its key, and ends with $150. Even the fault-free in-place run turns the sum red between each pair of UPDATEs: that is what any reader sees at that instant.
Balances updated in place, one statement per leg, a client that retries on timeout. Inject one fault so that money is created or destroyed, or a transfer is applied twice.
GOAL: the sum of balances changes, or a transfer is applied twice
Rewrite transfer so that a crash at any point leaves the books balanced, a retry with the same key applies nothing new and returns the original result, and an overdraft is refused. Return { ok: true } or { ok: false, reason }. The grader crashes the process at every ledger call and retries, and runs two transfers at once in every order.
Wallets, payout systems, marketplace balances, loyalty points, ad-spend budgets, game currencies: anything where a number stands for money. Stripe-style Idempotency-Key headers, double-entry tables (journal, entries, accounts), and nightly jobs that assert the sum is zero.
“Design the ledger for a payments app.” Draw accounts and a balance column, then break it: a crash between debit and credit, and a client retry after a timeout. Replace the column with an append-only entries table, each transfer a pair of rows summing to zero, written in one transaction. Add a unique idempotency key in that transaction so retries return the stored result. Mention the funds check under a row lock or serializable isolation, balances as a derived cache, and the reconciliation job that sums every account and pages someone when it is not zero.
USED IN
Chapters that build on this lesson.
- Choosing a database: a decision frameworkDatabases
- Distributed transactions: 2PC, Percolator, and Spanner's clockDatabases
- Double-entry bookkeeping for engineersPayments
- Project: a double-entry ledger for a walletPayments
- Platform, API and technical PMProduct Manager
- API, contract and integration testingQA and Quality Engineering
- Testing money and regulated systemsQA and Quality Engineering
- Testing philosophies: pyramid, trophy, exploratory, risk-basedQA and Quality Engineering