Sub topic 8
Recording money movement in a double-entry ledger
This chapter assumes you know relational transactions and unique constraints, can read short Python and SQL snippets, and have read the chapters on money representation and the payment state machine. Here you will build the ledger, the record of where every unit of money is.
Why a payment table is not enough
The payments table says what happened to a payment: it was created, authorized, then captured. It does not say where the money is. Suppose a merchant asks why their balance is 96.80 after a 100.00 sale. A status column cannot answer that. A ledger can, because it lists every movement, with the fee, the refund and the payout each shown as its own record.
A ledger is an append-only record of money movements between accounts. It is separate from payment status. The payment state machine drives the ledger, but the ledger does not depend on the state machine to be correct.
Double-entry in one rule
Every ledger transaction contains two or more entries. Each entry is a debit or a credit against one account. For each currency, the total debits must equal the total credits.
Money never appears or disappears. It moves from one account to another, so an unbalanced transaction is a bug and is rejected.
Accounts have a normal side:
| Account type | Example | Increases with | Typical meaning |
|---|---|---|---|
| Asset | `psp_receivable` | Debit | Money someone owes us or holds for us |
| Liability | `merchant_payable` | Credit | Money we owe to a merchant |
| Revenue | `fee_revenue` | Credit | Fees we have earned |
| Expense | `chargeback_loss` | Debit | Costs we absorb |
In a payment platform, most of the money is owed to merchants, so liabilities dominate the books.
A capture as a ledger transaction
Take a 100.00 USD capture with a fee of 2.9% plus 0.30 USD, which is 3.20 USD. In minor units, the sale is 10000, the fee is 320, and the merchant's share is 9680.
| Entry | Account | Direction | Amount (minor units) |
|---|---|---|---|
| 1 | `psp_receivable` | debit | 10000 |
| 2 | `merchant_payable` | credit | 9680 |
| 3 | `fee_revenue` | credit | 320 |
Debits total 10000 and credits total 10000, so the transaction balances. A transaction may have more than two entries. Splitting a payment between a merchant and a fee account is a normal case.
Validating balance in code
The check works on integer minor units. Floats would make equality tests unreliable, which is why the money representation chapter ruled them out. This code converts amounts, checks balance per currency, and builds the capture transaction above.
from decimal import Decimal
from collections import defaultdict
def to_minor_units(amount: str, exponent: int = 2) -> int:
"""Convert a decimal string such as '19.99' to integer minor units (1999)."""
value = Decimal(amount).scaleb(exponent)
if value != value.to_integral_value():
raise ValueError("amount has more precision than the currency allows")
return int(value)
def assert_balanced(entries):
"""entries: iterable of (account, direction, amount_minor, currency)."""
net = defaultdict(int)
for _account, direction, amount, currency in entries:
if amount <= 0:
raise ValueError("entry amounts must be positive")
if direction not in ("debit", "credit"):
raise ValueError("direction must be debit or credit")
net[currency] += amount if direction == "debit" else -amount
if any(total != 0 for total in net.values()):
raise ValueError("ledger transaction is not balanced")
sale = to_minor_units("100.00")
fee = to_minor_units("3.20")
capture = [
("psp_receivable", "debit", sale, "USD"),
("merchant_payable", "credit", sale - fee, "USD"),
("fee_revenue", "credit", fee, "USD"),
]
assert_balanced(capture)
print("capture is balanced")The check runs per currency. A transaction that debits 10000 USD and credits 10000 EUR is not balanced, even though the numbers match. Converting currencies needs its own entries against a conversion account, one per currency.
Storing the ledger
Two tables are enough: one transaction header per business event and one row per entry.
CREATE TABLE ledger_transactions (
id UUID PRIMARY KEY,
payment_id UUID NOT NULL,
kind TEXT NOT NULL, -- 'capture', 'refund', 'payout', ...
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE (payment_id, kind)
);
CREATE TABLE ledger_entries (
id BIGSERIAL PRIMARY KEY,
transaction_id UUID NOT NULL REFERENCES ledger_transactions (id),
account TEXT NOT NULL,
direction TEXT NOT NULL CHECK (direction IN ('debit', 'credit')),
amount_minor BIGINT NOT NULL CHECK (amount_minor > 0),
currency CHAR(3) NOT NULL
);Write the header and all its entries in one database transaction. Either every entry is committed or none is, so a crash cannot leave half of a posting behind.
The UNIQUE (payment_id, kind) constraint is the idempotency guard for the ledger. If a worker retries a capture and tries to post it twice, the second insert fails and the money is not counted twice. This only works if each payment can have one capture. Refunds can be partial and repeated, so they need a refund identifier in the key instead.
Immutability and corrections
Never update or delete a posted entry. Auditors, reconciliation and incident investigations all rely on history that cannot change. If a posting was wrong, post a new transaction that reverses it and then post the correct one.
A full refund of the sale above reverses the capture:
| Account | Direction | Amount (minor units) |
|---|---|---|
| `merchant_payable` | debit | 9680 |
| `fee_revenue` | debit | 320 |
| `psp_receivable` | credit | 10000 |
Whether the platform returns the fee on a refund is a business rule. Some PSPs keep it. If yours does, the fee entry stays and the merchant bears the cost. Encode the chosen rule in one place, because a different rule in each code path is how books drift.
Enforce immutability in the database as well as in the application. Revoke UPDATE and DELETE on the entries table for the application role, or add a trigger that raises an error.
Computing balances
A balance is derived from entries, not stored as the source of truth. For a credit-normal account, such as a merchant's payable, the balance is credits minus debits:
SELECT COALESCE(SUM(
CASE direction WHEN 'credit' THEN amount_minor ELSE -amount_minor END
), 0) AS balance_minor
FROM ledger_entries
WHERE account = 'merchant_payable:' || :merchant_id
AND currency = 'USD';Here the account name includes the merchant ID, so each merchant has a separate sub-account. Summing every entry becomes slow as the table grows. Keep a cached balance table that you update in the same database transaction as the entries. Verify it periodically against the full sum. Treat the entries as truth and the cache as an optimization.
If many requests update the same hot account, such as the platform's fee_revenue, the single balance row becomes a lock bottleneck. Common fixes are splitting the balance across several shard rows and summing them on read, or updating the hot balance asynchronously in batches.
Common errors
- Posting on the request path before the PSP answers. If the authorization is still uncertain, wait. Post to the ledger on confirmed events, such as capture, not on attempts.
- Storing floats or mixed units. Use integer minor units and store the currency with every entry.
- Updating entries in place. Always reverse and repost.
- Forgetting the currency exponent. JPY has no minor unit and some currencies have three decimal places. Look the exponent up per currency instead of hard-coding 2.
- Checking balance only in application code. A second service writing to the same tables can skip your check. Consider a deferred database constraint or trigger that verifies each transaction balances at commit time.
Exercises
Exercise
A merchant sells an item for 50.00 USD. The platform fee is 1.75 USD. Write the ledger entries for the capture using the accounts in this chapter, and state the total debits and credits.
Show answer
Debit pspreceivable 5000. Credit merchantpayable 3325. Credit fee_revenue 175. Total debits are 5000 and total credits are 3325 + 175 = 5000, so the transaction balances.
Exercise
A capture worker crashes after posting the ledger transaction but before marking the job done. It retries. Which design element stops the merchant from being credited twice, and why must the entries and the header be written in one database transaction?
Show answer
The UNIQUE (paymentid, kind) constraint on ledgertransactions rejects the second capture posting for the same payment. The header and entries must share one database transaction so a crash cannot leave a header without its entries, or entries that do not balance, committed.