Most payment systems start with a balance column and an audit table next to it. Within a couple of years the two disagree, and nobody can say which is right, because the only record of why a balance is what it is lives in logs that have since rotated. A double-entry ledger fixes this by making the explanation the primary data: every movement is a balanced entry, balances are derived from entries, and every entry is permanent. That part is more than five hundred years old. The engineering is in keeping those properties at millions of entries a day, with hot accounts, late data, corrections and shards, without anyone ever needing to run an UPDATE.
The atomic unit is the entry (journal entry, transaction), not the posting. An entry is a set of two or more postings, each a signed amount against one account, and the rule is that the postings in an entry sum to zero per currency. Store amounts signed, debit positive. Separate debit and credit columns double your predicates, and every query that forgets one of them is wrong in a way that still returns numbers. Liabilities and revenue are credit-normal, so a customer wallet holding 50.00, which is money you owe the customer, is stored as −50.00. Flip the sign at the presentation boundary and never in storage. The classic bug is an API that exposes raw signs, and a client team that "fixes" it with abs().
The per-currency rule has a consequence people miss. An FX conversion cannot be a single balanced entry across two currencies, because 100 EUR plus −108 USD does not sum to anything meaningful. It has to go through a pair of FX position accounts, one per currency: the EUR side balances in EUR and the USD side balances in USD. The position accounts then carry your open currency exposure, which treasury wants anyway. Rates, their provenance and their rounding belong to chapter 01, Modelling Money Correctly. The ledger only records the rate that was used and what it pointed at.
processor_receivable
clearing
merchant_payable
liability
fee_revenue
income
processing_expense
expense
bank_operating
asset
payouts_in_transit
clearing
The two clearing accounts are the distributed system's in-flight state made visible: non-zero between E1 and E2 means "the processor owes us"; non-zero after E3 means "money is on the wire". A clearing balance that stays non-zero past its expected age is a break, found without scanning any logs.
What is left is the P&L of one payment: +3.00 fee revenue, 2.20 processing cost, +0.80 cash. Raw signs are the storage convention. Credit-normal accounts (revenue, payables) show negative raw balances and get flipped for display, never in the database.
The most useful design tool in the chart of accounts is the clearing account, sometimes called a suspense or in-transit account. Every asynchronous step in a money flow gets one. Money leaves the source account into clearing when the step starts and leaves clearing when the step resolves. Clearing accounts should trend to zero, and any balance left in one is a precise, queryable list of work that has not finished. That turns a distributed-systems problem, "which of our in-flight operations are stuck?", into a SQL query that finance can read. It is also what makes chapter 04, Reconciliation: Proving the Books, tractable, because each external counterparty lines up with exactly one clearing account to be matched.
Granularity decides everything else. One account per (owner, currency, purpose) is the right default: wallet-available, wallet-reserved, merchant-payable and merchant-reserve are separate accounts rather than a single account with tags. The reason is mechanical. Constraints, locks and balance projections all operate per account, so anything that needs its own rule needs its own account. Teams that model a merchant as one account with a purpose column end up re-implementing account semantics with a GROUP BY, and they lose the ability to constrain one purpose without locking all of them.
Architect's note · what does not belong in the ledger
Once entries are the truth, a balance is a fold over postings, and the design question becomes where you materialise that fold. There are three options, and serious ledgers use all of them for different reads. Compute on read (Σ postings) is always correct and is fine for low-volume accounts, but its cost grows with account history. A running balance on the account row is O(1) to read but turns every write into a row update, which is the root of the hot-account problem in 2.3. Balance-after on each posting, together with a per-account sequence number, gives O(log n) point-in-time reads through an index on (account_id, seq) and a cheap self-check: balance_after[n] must equal balance_after[n−1] + amount[n], and seq must have no gaps.
A unique constraint on (account_id, account_seq) also gives you optimistic concurrency for free. Insert with seq = last + 1, and a concurrent writer loses on the constraint and retries. That is excellent for low-contention accounts and a trap for hot ones. Under contention OCC throughput collapses, because every conflict throws away a full round trip of work while the retry storm raises the conflict rate. Past a small number of concurrent writers per account, pessimistic locking or a single writer beats optimistic retries.
Asynchronous projections (checkpoints, CDC-fed balance caches, warehouse snapshots) have a failure mode that is easy to ship and very hard to see. A job that folds "every posting with id ≤ N" and seals the result assumes ids become visible in order. They do not. The id or timestamp is assigned at insert, visibility happens at commit, and a transaction that took id 1,000 and then waited 40 ms on a lock or a synchronous replica commits after id 1,001 is already visible. The checkpointer reads through 1,001, seals, and posting 1,000 is excluded from every balance built on that checkpoint, while a full recompute includes it. It happens only under load, and it presents as a small, unreproducible reconciliation break. The fix is a safe horizon: fold only what no in-progress transaction can still precede. In Postgres, store pg_current_xact_id() on each posting and fold only rows whose xid is below pg_snapshot_xmin(pg_current_snapshot()), or lag the horizon well past a transaction timeout that is actually enforced. In a single-writer design the problem does not arise, because sequence order is commit order.
The horizon's lag is bounded by your longest open transaction, so one forgotten idle-in-transaction session freezes every checkpoint behind it. Alert on horizon age, and enforce idle_in_transaction_session_timeout on ledger roles, or the correct fix turns into a stale-balance incident.
The same race hits every consumer that uses a monotonic column as a cursor: "give me postings since id N" polling APIs, warehouse loaders keyed on created_at, and outbox relays that page by id. It is invisible in staging because it needs two concurrent commits and a stall between id assignment and commit. A useful review test: ask what the cursor is, and whether anything could commit behind it. If the answer is "a sequence", the consumer loses rows under load. Logical replication and CDC avoid it because they follow commit (LSN) order, not id order.
One account has more than one balance. Posted is the sum of committed entries. Pending covers two-phase entries such as authorization holds and payouts that have been initiated but not confirmed. Available is posted minus pending debits, and it deliberately ignores pending credits. That asymmetry is the whole point. Letting someone spend an incoming credit before it posts is how a payout gets funded by a card payment that is later declined or charged back. Pending entries need an expiry, because card authorizations lapse and a hold with no timeout eventually becomes permanently frozen customer money that nobody owns. The opposite error is subtler. A hold that expires earlier than the network's capture window releases funds the merchant can still claim.
day 0
auth 80.00
pending hold posts · available 100 → 20
day N
ledger hold expires
void posts · available back to 100
day N+1
customer spends 90
allowed · available 10
day N+2
late capture 80 arrives
network still honours it → posted −70
The capture cannot be rejected: the money has already moved at the network. So it must post through the overdraft-capable correction path from 2.4, as a receivable from the customer. Set ledger hold expiry from the network's rules, not from a round number, and treat every post-expiry capture as a metric.
Neither clock is wrong on its own terms, which is why this survives design review. The ledger's timeout is a product decision about how long to freeze customer money. The capture window belongs to the card network and the merchant category, and a capture that arrives inside it is not optional for you. Model them separately: the hold's release time (when available is restored) and its claim horizon (until when a capture must still be accepted). Between the two, the funds are available but at risk, and the size of that exposure, Σ expired-but-claimable holds, is a number risk should see every day. How the authorization lifecycle itself behaves is chapter 03.
Every balance is Σ postings with effective ≤ t and recorded ≤ k: a rectangle anchored at the origin. Without a close, the late entry sits in Q2 but not Q1, so the same report run twice returns two answers. The close forbids the hatched region; the fee lands in April with a pointer back to its March source.
The dimension most teams miss is time. Every posting has a recorded time, when the ledger learned about it, and an effective time, when it happened economically. The two diverge all the time: a processor's fee file arrives three days late, a chargeback is dated to the original transaction, an interest accrual is computed after month end. A balance "as of March 31" is therefore ambiguous until you also say as known when. Without a period close that forbids new postings with an effective time inside a closed period, the March report you sent the auditor and the March report you run today will quietly differ. The close does not throw information away. The late item posts with an effective time in the open period and a reference back to its source, so the history stays stable and the correction stays visible.
Pitfall · effective time as the partition key
In a marketplace, every payment touches the platform's fee-revenue account. In a card issuing program, every authorization touches the program's funding account. These hot accounts are where naive ledgers fail, and they fail at load levels that look embarrassingly low. The mechanism is simple. If each entry updates a balance row under a row lock, the lock is held until commit, and in Postgres and most other databases that includes the WAL flush and the wait for synchronous replicas to acknowledge. So the throughput of the whole system is capped at 1 ÷ lock hold time, for every entry that touches that account.
The ceiling is set by how long the row lock is held, not by CPU, disk bandwidth or table size. Running at 80% of the ceiling, M/M/1 queueing puts mean wait at 4× the hold time; at 95% it is 19×. Batching is the only lever that moves the curve rather than sliding along it.
Put illustrative numbers on it. Suppose the application runs an interactive transaction: BEGIN, SELECT … FOR UPDATE, INSERT the entry, INSERT the postings, UPDATE the balance, COMMIT. At about 0.5 ms per same-AZ round trip plus a commit that waits on a synchronous replica, the lock is held for about 4 ms, which caps you at 250 entries per second. Queueing makes that worse well before the ceiling: at 80% utilisation the mean wait is 4× the hold time, and at 95% it is 19×. Collapse the transaction into a single statement or stored procedure and the ceiling moves to roughly 600 per second. Then someone enables cross-region synchronous replication for durability, commit latency rises to 30 ms, and the platform's checkout ceiling is now 33 per second. That is a reliability change that shows up as a throughput cliff, three weeks later, on Black Friday.
The way out starts from one observation: addition commutes. Postings to an account with no write-time constraint can be applied in any order, concurrently, on any shard, and the balance comes out the same. Contention is not caused by writing to an account. It is caused by checking the account's balance at write time, because the check needs a serial order. Fee revenue has no constraint, since no one declines a payment because revenue would go negative, so it never needs a locked balance row. Append its postings and compute the balance asynchronously or on read. Most "hot account" problems disappear once you stop maintaining synchronous balances on accounts that nobody constrains. That also means dropping the account_seq and balance_after chain from 2.2 on those accounts. A per-account sequence is a serial order, and it would bring the lock straight back. Give hot unconstrained accounts periodic checkpoints over sealed windows, behind the safe horizon, and keep the chain for accounts you serialize anyway.
Addition commutes. An account nobody checks at write time is a grow-only counter, and its postings can land in any order on any shard. Contention comes from the check, not the write.
The accounts that really are constrained and hot, such as program funding or a large merchant's payable that funds instant payouts, have four real options. The first is split the paths: credits arrive unconstrained and append-only, and only debits serialize against the balance. That works because debits are usually far rarer than credits. The second is sharded sub-accounts: N sub-accounts, each holding a share of the limit, with the balance being their sum. This is O'Neil's escrow method from the 1980s in ledger form. It scales well but strands capacity: a sub-account can decline a debit while the aggregate has plenty of headroom. Treat these false declines as a metric you measure, not something you reason about. Route each debit to the fuller of two randomly chosen sub-accounts (power of two choices), which keeps them far more even than random routing does. Add a rebalancing sweep, and a slow path that locks all N sub-accounts when the chosen one cannot cover the amount. As the aggregate balance nears the limit, every debit takes the slow path and the design collapses back into one serialized account. Sharding the limit buys throughput only while there is headroom, and that is exactly when you needed it least. The third is a single writer with group commit: one owner per account, in memory, validating sequentially and committing batches. At 1,000 entries per 5 ms commit, that is 200k per second on one account. The fourth is a purpose-built ledger database that does the same thing natively (2.6). What does not work is adding database replicas, a bigger instance or a faster disk, because none of them change the lock hold time enough.
The right panel still has 64k of real headroom, so declining the debit is a false decline. Any debit larger than the per-sub-account share (here ~8k average) now serializes, and any debit above 100k always did. Throughput collapses precisely when the account is closest to its limit.
Sizing N is a two-sided trade, and the diagram gives the shape of it. More sub-accounts raise the fast-path ceiling roughly N-fold, but each holds 1/N of the limit, so the largest debit that can take the fast path shrinks by the same factor. Work it through with the illustrative numbers: an 800k limit at 8 sub-accounts caps fast-path debits at 100k even when the account is empty; at 64 sub-accounts it is 12.5k. If the debit-size distribution has a fat tail (B2B payouts, treasury sweeps), the tail serializes regardless of N, and the slow path now holds 64 locks instead of 8. Two rules follow. Size N from the p99 debit, not from throughput alone: keep L ÷ N comfortably above it at your normal utilisation. And keep a reservation floor, a share of the limit held back in a central sub-account that the slow path draws from, so a near-limit account degrades to one lock rather than N. The metrics that tell you the design is failing are slow-path rate and false-decline rate by aggregate utilisation. If either rises before 80% utilisation, N is wrong for your debit sizes.
1 ÷ h
per-account ceiling
~250/s
4 ms interactive txn
~33/s
30 ms x-region commit
b ÷ h
with group commit
Postings are never updated and never deleted. The audit argument for this is well known. The engineering argument is stronger and less often made: every derived artefact assumes append-only. Balance projections, the balance_after chain, CDC streams into the warehouse, reconciliation matches, cached balances in product services and last month's regulatory report were all computed from the entries as they stood. One UPDATE during an incident silently invalidates every one of them, and nothing tells you which. A ledger that has been mutated once has to be re-verified from the beginning before anyone can trust it again. In practice that means the verification never happens, and the ledger is trusted by habit afterwards. Revoke UPDATE and DELETE on the posting tables from every role, including the one your on-call engineers use, and add a trigger that raises on either. Superusers bypass privilege checks and an owner can re-grant itself anything, so the trigger is what an owner-role migration script hits first. Know its gaps too. Row-level triggers do not fire on TRUNCATE, which needs its own statement-level trigger. session_replication_role = replica, a common trick in bulk-load and restore scripts, skips ordinary triggers entirely. And the owner can simply disable them. The durable control is that no human or migration role owns the ledger tables, and that a periodic hash over sealed postings (chapter 07) detects what the permissions failed to prevent.
Corrections come in four shapes, and each needs its own semantics. A void cancels a pending entry before it posts. It is not a reversal, because nothing had posted. A reversal is the exact negation of a posted entry, carrying a reversed-entry reference and a unique constraint so that each entry can be reversed at most once. That constraint prevents the reversal-of-a-reversal loop that a retrying ops tool will otherwise produce. An adjustment is a new entry for a delta: the fee was 2.20 and should have been 2.40. A reclassification moves value between two accounts without touching anything else. Reversal-and-repost gives the cleanest lineage, where the original is plainly dead and its replacement plainly live, and it is the right default for anything a customer or auditor will read. Reclassification is cheaper and is fine for internal account moves.
E-1001 · Mar 3
capture (wrong merchant)
Dr processor_recv 100.00
Cr payable:A 97.00
Cr fee_revenue 3.00
E-1207 · Mar 9
reversal
reverses: E-1001
exact negation, all 3 legs
reason: MISROUTED · actor: ops-42
E-1001 now marked reversed_by
E-1208 · Mar 9
re-post
Dr processor_recv 100.00
Cr payable:B 97.00
Cr fee_revenue 3.00
corrects: E-1001
alternative
reclassification
Dr payable:A 97.00
Cr payable:B 97.00
one entry, fee + receivable untouched
But merchant A was paid out on Mar 5.
Either shape drives payable:A to −97.00. A "payables never go negative" constraint now blocks the correction. The negative balance is not a bug; it is a receivable from merchant A (a collections case, or netted from their next payout). Corrections need a privileged posting path that may overdraw, and it must emit an event that someone owns.
The failure mode worth designing for is the one in the diagram. By the time a mistake is found, money has usually moved on from the account it was booked to. Corrections will therefore regularly drive accounts through the constraints you placed on them. If the same posting path serves corrections and product traffic, the correction is rejected, and an engineer under pressure reaches for SQL. So build a privileged correction path: it bypasses balance constraints (never the zero-sum rule), requires a reason code and an actor, and emits an event when it produces a negative balance, so that the resulting debt becomes a tracked case rather than a surprise in next month's reconciliation. Keep corrections that cross a closed period, discussed in 2.2, on the same path.
Idempotency belongs in the ledger too, not only in the services above it. Every entry carries an external idempotency key under a unique constraint, derived from the business event and never generated at post time. A retry that generates a fresh UUID has turned an at-least-once delivery into a double posting. How the key is kept stable across an external provider boundary is chapter 03, Payment Flows & Unknown Outcomes. The ledger's job is to make the second attempt a no-op that returns the first result.
The volume numbers are less frightening than they sound. Take 5 million entries a day at an average of three postings each: 15 million posting rows a day, about 170 per second on average and perhaps 1,700 at a 10× peak. At a few hundred bytes per row including indexes, that is on the order of 1.5 TB a year (illustrative). A single well-tuned relational primary with time-partitioned postings handles that. The scaling pressure in a ledger comes from hot rows and query shape, not from size. Teams that shard on volume grounds early take on the hardest problem in this section without needing to.
The minimum schema is accounts, entries and postings (entry_id, account_id, amount, currency, account_seq, balance_after), plus the metadata tables. Enforce zero-sum inside the database, not only in application code. A deferred constraint trigger that sums an entry's postings at commit works, but it re-reads rows you just wrote. A single posting function that takes the whole entry, validates it and inserts it is cheaper and gives you one choke point. Multi-leg entries bring deadlocks: entry 1 locks A then B while entry 2 locks B then A. Always acquire account locks in account-id order. It is a one-line sort that ops teams tend to rediscover after their first deadlock storm. Keep balance history in the posting rows, and use periodic balance checkpoints so that an as-of query reads the nearest checkpoint plus a bounded tail.
When you do have to shard, shard by the entity that owns most of the entries, usually the tenant or merchant, so that most entries stay on one shard. The ones that cannot, such as a transfer between customers on different shards, must not become a distributed transaction. Split them into two local entries, each balanced on its own shard, joined by a pair of inter-shard clearing accounts.
Each shard stays balanced at every instant, so the global trial balance is still zero. The inter-shard pair is the saga's state, held in the ledger itself and summable by a query: in-flight money is Σ over clearing pairs, and every stuck transfer is a non-zero pair older than its SLA.
This is a saga, of the kind covered in the Distributed Systems Deep Dive's chapter Distributed Transactions & Sagas, with a property most sagas lack: the saga's intermediate state is inside the books. At every instant each shard's trial balance is zero, the global one is zero, and in-flight money is exactly the sum of the non-zero clearing pairs. You do not need a saga-state table that can drift from reality, because the ledger is the saga log. The outbox row written in the first local transaction, with the transfer id as idempotency key on the second, gives at-least-once delivery and exactly-once effect. The rejection path is a compensating entry on shard A, not a rollback.
Resharding follows the same rule. Moving a merchant from shard A to shard B is not a row copy. Copied postings put the same history in two books, and the balance chain on B starts from a balance that B never posted. Instead, freeze the merchant's accounts for writes, post a closing transfer of each balance through the inter-shard clearing pair into freshly opened accounts on B, and leave the history on A, where every existing audit reference already points. The physical account changes, so every consumer has to address a stable logical account id through a mapping (logical → shard, physical account) that carries effective dates. That way an as-of query for last quarter still routes to A. Moving the money is the easy part of a resharding project. The schedule usually slips on finding every service that cached a physical account id.
Pitfall · the platform account on every shard
A ledger looks like the textbook case for event sourcing: an append-only sequence of facts from which state is folded. The Data Engineering track's chapter Event Sourcing & CQRS covers the pattern. The ledger-specific catch is the balance check. Validating "available ≥ amount" requires reading consistent current state and appending on the condition that it has not changed since. Event stores give you that per stream through an expected-version check, and most do not give it across streams. A transfer between two accounts, each its own stream, is therefore back to a saga. The alternative is one stream for the whole ledger, which serialises everything and brings back the hot-account ceiling globally.
Kafka specifically offers no conditional append: a producer cannot say "append only if the partition is still at offset N". A Kafka-backed ledger therefore needs a single consumer per partition acting as validator. It reads a command, checks it against its in-memory balances and emits accepted or rejected entries. That is a replicated state machine you now own, with the recovery, fencing and snapshotting problems covered in Kafka & the Log and in the Distributed Systems chapter Consensus: Raft & Paxos. It can be done well, but you have built a database. Be honest about that before choosing it.
Purpose-built ledger databases take the single-writer idea and make it the whole architecture. TigerBeetle is the clearest public example. Debit/credit transfers between accounts are its only write primitive. Accounts and transfers are fixed-size records. Balance constraints are account flags (debits must not exceed credits, or the reverse). Two-phase pending transfers with post, void and timeout are built in. Linked chains of transfers succeed or fail together. The state machine executes on a single thread, so a hot account involves no lock contention at all, and requests carry large batches, so replication and fsync costs are amortised across thousands of transfers. The price is scope. The records carry ids and a handful of integer user-data fields, not your metadata, and transfers are confined to accounts on the same ledger (in practice, the same currency), so cross-currency movements are linked pairs through position accounts, exactly as in 2.1.
No column is all green, which is why mature ledgers end up hybrid: a constrained core that holds balances and enforces invariants, plus a relational or warehouse store for the metadata, keyed by the same entry id.
Distributed SQL deserves a specific warning. It fixes multi-account atomicity across ranges and keeps SQL, but a hot row is still one row, owned by one leader, and every commit on it now includes a consensus round. Its hot-account ceiling is therefore rarely higher than a single-primary Postgres in one AZ, and often lower once contention retries are counted. The chart in 2.3 explains why. It is a good choice for the long tail of cold accounts and a poor one for your hottest five.
Most mature designs converge on a hybrid: a constrained core, either a ledger database or a single-writer service over a relational store, that holds balances and enforces invariants, and a relational or warehouse store for metadata, keyed by the same entry id. That creates a dual write, and the ordering rule is not negotiable. Write metadata first, keyed by the pre-assigned entry id, then post the entry. A crash between the two leaves orphaned metadata, which is harmless and can be swept up later. The other order leaves money that moved with no explanation of why, which is exactly the state the ledger exists to prevent.
The last design decision is organisational, and it decides whether the ledger stays correct after the fifth product team integrates with it. If product services construct postings themselves, every team has to understand the chart of accounts, and every team will eventually book something to the wrong account in a balanced, valid-looking way that no invariant catches. Zero-sum proves an entry is balanced, not that it is right. A payment credited to fee revenue instead of merchant payable balances perfectly.
business event
payment.captured
amount 100.00 USD
fee 3.00 · merchant m_A
event_id = idempotency key
posting rule v14
template: card_capture
resolve accounts by
(merchant, currency, purpose)
pure function, unit-tested
validate
Σ = 0 per currency
accounts open, currency match
constraints + period open
rule_version stamped
append
entry + postings
atomic, immutable
balance projections update
no rule / validation fails
The event is parked with its reason; it is never dropped and never force-posted. Unmapped events are a financial-close blocker with an owner, not a log line.
rule v14 was wrong
Diff v14 against v15 over the affected events and post the difference as adjusting entries stamped v15. Replaying history is how you compute the correction, never how you apply it.
The pattern that holds up is posting rules. Product services emit business events that describe what happened in their own terms. A versioned rule set owned by the ledger team, often with finance co-owning the review, maps each event type to a template that resolves accounts and produces a balanced entry. Rules are pure functions, so they can be tested exhaustively against fixtures, including every refund, partial capture and currency combination. Stamp each entry with the rule version that produced it. When a rule turns out to be wrong, replay the affected events through old and new versions, diff the results, and post the difference as adjusting entries. Replay computes the correction and never rewrites history. Events with no rule are parked in an owned queue, never dropped and never booked to a catch-all "misc" account. A catch-all account is where a ledger's credibility goes to die.
Rules also give you the cheapest high-value invariants beyond zero-sum, and you can check them at write time because the rule knows the intent. A card capture must touch exactly one processor clearing account. A payout must debit a payable and credit a payout-clearing account in the same currency. The capture amount must equal the sum of the payable, fee and tax legs. These shape invariants catch the mis-booking class that zero-sum cannot see. Running them continuously across the whole ledger, alongside trial-balance and balance-chain checks, is chapter 07's subject, Auditability, Compliance & Continuous Correctness.
Design review · questions that find the expensive bugs
Architect's note · decision criteria
Where next