Sub topic 8
Recording money movement in a double-entry ledger
This chapter assumes you know relational transactions and unique constraints. It also assumes you have read the chapters on the payment state machine and on representing money as integer minor units.
Why a payment table is not enough
A payments row says what state a payment is in. It does not say where the money is. When a payment is captured, refunded, or charged a fee, you need a record of every movement that you can audit later. A double-entry ledger provides that record.
In a double-entry ledger, every transaction has at least two entries. Each entry names an account, a direction (debit or credit), an amount, and a currency. The total debits must equal the total credits within each currency. If they don't, the transaction is rejected.
Core rules
- Entries are append-only. Never update or delete an entry. To correct a mistake, write a new reversing transaction.
- Amounts are positive integers in minor units. The direction carries the sign.
- Each ledger transaction is written in one database transaction, so either all its entries exist or none do.
- Balances are derived by summing entries, or cached and checked against that sum.
Checking balance before writing
The code below converts a decimal string to minor units and refuses to accept an unbalanced transaction. It runs as shown.
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:
net[currency] += amount if direction == "debit" else -amount
if any(total != 0 for total in net.values()):
raise ValueError("ledger transaction is not balanced")
assert_balanced([
("customer_funds_receivable", "debit", to_minor_units("19.99"), "USD"),
("merchant_payable", "credit", to_minor_units("19.99"), "USD"),
])A capture with a fee
Suppose the platform keeps a fee of 0.59 on a 19.99 capture. The debit side has one entry. The credit side splits into two.
capture = [
("customer_funds_receivable", "debit", to_minor_units("19.99"), "USD"),
("merchant_payable", "credit", to_minor_units("19.40"), "USD"),
("fee_revenue", "credit", to_minor_units("0.59"), "USD"),
]
assert_balanced(capture)Common errors
- Mixing currencies in one balance check. Sum per currency, as
assert_balanceddoes. A 10 USD debit does not offset a 10 EUR credit. - Using floats. Rounding error makes balance checks fail or, worse, pass wrongly.
- Writing the ledger outside the payment's transaction. A crash between the two writes leaves state and money out of agreement. Write both in one database transaction, or use the outbox pattern covered later.
- Editing old entries. This destroys the audit trail and breaks reconciliation.
Exercise
A refund of 5.00 USD is issued against the captured payment above, and the fee is not returned. Which entries record it, and why not edit the original capture entries?
Show answer
Post a new transaction that debits merchantpayable by 500 and credits customerfunds_receivable by 500. Both entries are USD, so debits equal credits. The original entries stay unchanged because the ledger is append-only. Editing them would erase the history that auditors and reconciliation depend on.