System Design · Concept Library · Free article
Double-Entry Ledgers: Money as an Append-Only, Always-Balancing Record
Never store money as a column you overwrite. Record every movement as an immutable entry whose debits equal its credits, and derive balances from that history, so a charge that crashed halfway can always be recovered and every cent can be audited.
A double-entry ledger records money as an append-only sequence of immutable entries instead of a single balance you overwrite. Every movement is written as balanced debits and credits — the amount leaves one account and arrives in another, so each entry sums to zero and the books always balance. You never edit or delete a row; to fix a mistake you append a reversing entry, so the full history of every dollar survives. The current balance is not a stored number you trust — it is derived by summing the entries (with periodic snapshots so a read does not re-sum from the beginning of time). The payoff is memory: a charge that crashed halfway is still on the books and always recoverable, every cent is auditable, and money is represented exactly as integer minor units rather than a float that drifts. It is the append-only log the saga treated as its source of truth, and the record a reconcile job later checks against the provider.
The $8 that vanished — a column can’t tell you a story
A Hatch customer upgraded to Pro. The card was charged $8, and then, in the worst possible instant, the server crashed before the account flipped to Pro. Support gets the email two days later: "I paid and I still don’t have Pro." You open the database to see what happened, and here is the problem — the account row just says plan = free. There is no charged_at, no amount, no trace. The one column you have was built to hold the current state, and the current state is "free." It has no idea a charge ever happened. You cannot refund what you cannot see, and you cannot even confirm the customer’s story.
This is what a mutable value costs you. A column you overwrite only ever remembers its latest value; every previous truth is gone the instant you write the next one. For a display name or a theme colour, that is exactly right — nobody needs the history of your avatar. For money it is a catastrophe, because with money the history is the point: what moved, when, in which direction, and whether it is still owed. A charge that died mid-flight is not an edge case you can ignore; it is a customer’s money sitting in a state your data model literally cannot represent.
Watch the same two operations — a charge, then a refund — land in a mutable column versus an append-only ledger, and then ask each one a question support actually asks:
The interactive version of this example is available when JavaScript loads.
The column answers "the balance is $0" and nothing else. The ledger answers "$8 was charged at 12:04, refunded at 12:06, here are both rows" — the same final balance, but with the entire story intact. That difference is the whole page. The rest is how you build the second thing well.
Append the movement, don’t overwrite the total
A ledger flips how you store money. Instead of one row that holds the current balance and gets rewritten, you keep an append-only list where every money movement is a new, permanent row — a charge, a refund, a payout, a fee. Nothing is ever updated in place; you only ever add. The current balance is not stored at all in the naive version — it is whatever you get by adding up every entry from the beginning. The list is the truth; the balance is just a reading of it.
If that feels familiar, it should: it is the same append-only discipline the saga relied on to survive a crash. The saga wrote PENDING, CHARGED, GRANTED as it went so a restarted orchestrator could see exactly where it was. That log and this ledger are the same object viewed two ways — the saga cares that the sequence lets it recover; the ledger cares that the sequence is the authoritative record of the money. One append-only log, two jobs.
Every movement has two sides that must balance
Now the "double-entry" part, which sounds like accounting jargon but is really a correctness check that has survived six hundred years because it works. The rule is simple: money never appears or disappears — it only moves from one place to another. So every entry records both ends of the movement. When a customer pays Hatch $8, that $8 leaves the customer’s cash and arrives in Hatch’s revenue. You write both: a credit to one account and a debit to another, for the same amount. The two sides sum to zero, because nothing was created — it just moved.
The debit-and-credit vocabulary is old and a little confusing, so hold the plain idea underneath it: every entry touches at least two accounts, and the total that leaves must equal the total that arrives. Add up the debits and add up the credits across the entry and they have to match. If they do not, the entry is malformed and the ledger rejects it. Compose a movement and try to make it not balance:
The interactive version of this example is available when JavaScript loads.
For the upgrade, the entry is small but complete: debit the customer’s cash account $8, credit Hatch’s revenue account $8, one balanced entry that records the whole movement. Later, when you need to know how much revenue Pro has brought in, you do not trust a counter someone incremented — you sum the revenue account’s entries. The number is always defensible because it is built from the movements themselves.
To fix a mistake, append its reversal — never edit the past
The hardest habit to give up is editing. Something is wrong — a charge posted twice, an amount was off — and every instinct says open the row and fix it. In a ledger you must not. A posted entry is permanent; correcting it means appending a new entry that reverses its effect, then appending the right one. The mistake stays visible in the history, cancelled by its reversal, rather than erased. This is exactly the compensation idea from the saga, now as a storage rule: you do not un-happen a fact, you record an opposing fact.
It feels wasteful to keep a wrong entry around, but that permanence is the entire value. An auditor — or a very angry customer, or a regulator — can be shown the complete, untouched story: here is the double charge, here is the reversal that cancelled it, here is the correct charge. Nothing was quietly rewritten, so nothing can be quietly wrong. A ledger you can edit is not a ledger; it is a spreadsheet with extra steps, and it carries none of the trust that makes the append-only version worth building.
The balance is a reading of history, plus a shortcut
If the ledger is just entries, where does a balance come from? You compute it: sum every entry for the account and that sum is the balance. This is the purest form of the model — there is one source of truth, the entries, and the balance is always derived from it, so the two can never disagree. Append a reversal and the balance updates for free the next time you sum, without ever touching a stored number. Step through a few entries and watch the running balance follow the history:
The interactive version of this example is available when JavaScript loads.
There is an obvious catch, and it is a good example of a system-design trade you will make constantly. Summing from the beginning of time is fine when an account has a hundred entries and absurd when it has fifty million — every balance read would re-add years of history. The fix is a snapshot (a checkpoint): periodically store the balance as of a certain entry, then to read the current balance you take the latest snapshot and sum only the entries since. You keep the derive-from-history correctness and buy back the read speed. The snapshot is a cache of a computation, not a second source of truth — if you ever doubt it, you can always re-derive from the immutable entries and check.
Never store money as a floating-point number
Here is a mistake that looks harmless and corrupts a ledger from the inside: storing an amount as a decimal like 8.10 in a floating-point number — a float or a double. It seems fine, and it quietly is not, so it is worth understanding exactly why, because the reason is the whole rule.
A float stores a number in binary — base 2 — in a fixed number of bits (32 for a float, 64 for a double). The catch is that binary can only write a fraction exactly when its denominator is a power of two: a half, a quarter, an eighth, a sixteenth. A tenth is not one of those. So a value like 0.1 has no exact binary form at all — it becomes an infinitely repeating binary fraction that the computer chops off to fit the bits it has, storing a number a hair away from a true tenth.
One rounded value is invisible. The damage is that the errors compound: add these slightly-off numbers together, or multiply them, and the gaps stack up until the total is visibly wrong — the famous case is 0.1 + 0.2 coming out as 0.30000000000000004. A ledger does money arithmetic millions of times, so this is not a hypothetical: it is a matter of when, not if, a balance ends up off by a cent, then a dollar, and the books no longer sum to zero. In a record built to be exact, an inexact number type is a contradiction. Watch a tenth of a dollar added up in a float versus in whole cents, and see the drift appear:
The interactive version of this example is available when JavaScript loads.
That raises a fair question: an integer has a ceiling too — how much money can it hold? For almost everything, far more than you will ever need. A 64-bit signed integer (a long, or bigint in Postgres) counts to about 9.2 quintillion, which in cents is on the order of ninety trillion dollars in a single value. So integer minor units in a 64-bit column is the correct default, exact and fast, and it covers essentially every normal account and transaction. You only outgrow it at the extremes — and there is a clean answer for each:
How to size the money type
- Normal amounts (up to ~90 trillion dollars in one value): a 64-bit integer of minor units — a
long/bigint. Exact, fast, and the default for virtually every app. - Very large or very high-precision values (a company-wide aggregate that sums past 64 bits, high-denomination currencies, or crypto tokens with 18 decimal places): an arbitrary-precision type that grows as needed —
BigInteger/BigDecimalin Java or .NET,BigIntin JavaScript, Python’s built-in ints (already unbounded). You trade a little speed for unlimited exact range. - Crossing a language or JSON boundary: send the amount as a decimal string (
"8.10", or the minor-units"810"as text) and parse it into your exact type at the edges. This is the one representation that is portable to every language — and it dodges a subtle trap: JSON numbers are decoded as doubles by many parsers, so a money value sent as a bare JSON number can be silently corrupted in transit. A string never is.
A posting must be safe to retry
A ledger lives in the same messy world as everything else: the request that writes an entry can time out, get retried, or arrive twice. If a retried "charge $8" appends a second entry, you have not just double-charged the customer — you have poisoned the source of truth, and every balance derived from it is now wrong. So a posting has to be idempotent: writing the same movement twice must record it once.
The ledger is the source of truth — so nothing is ever lost
Put the pieces together and you have a record with a specific, powerful role: the ledger is the single source of truth for money, and everything else — a balance, a plan flag, a dashboard — is a view derived from it. That reframing is what pays off when things go wrong. A charge that crashed halfway through the upgrade is not a mystery anymore; it is an entry sitting in the ledger, marked pending, that a recovery job can find and either complete or reverse. The money is never lost, because the fact that it moved was written down before anything else happened.
It also makes the system honest to the outside world. Because every entry is immutable and every balance is provable from history, you can hand an auditor, a regulator, or a furious customer the complete, untouched story of any dollar — charged here, refunded there, reconciled on this date. Nothing was overwritten, so nothing can be hidden or accidentally wrong. Auditability stops being a feature you bolt on and becomes a property the data model has for free.
What a ledger costs, and when a column is fine
A ledger is not free, and the discipline is knowing when its guarantees are worth the price. You store every movement forever, so the data only grows — and reads get slower as history piles up, which is why you need snapshots and read models, which are themselves more moving parts. Modelling everything as balanced double-entry movements is more work than setting a column, and it is genuinely harder to reason about at first. You pay all of that to buy memory, auditability, and exact recovery. When those are not the point, do not pay for them:
Signs you don’t need a full double-entry ledger
- The value has no history worth keeping. A user’s theme, a display name, a last-seen timestamp — overwrite them in a column; nobody will ever audit your avatar.
- It is a count, not money, and an approximate one. A view counter or a like count wants a fast atomic counter, not a balanced ledger — losing the exact history of likes is not a financial event.
- There is no second party and nothing to reconcile. Double-entry earns its keep when money moves between accounts you must keep balanced; a purely internal, single-sided number may not need both sides.
- The stakes are low enough that a mistake is a shrug, not a lawsuit. The ledger’s cost is justified by the cost of being wrong — where being wrong is cheap, so is a simpler design.
Who builds on ledgers, and how
The pattern is everywhere money is taken seriously. Every bank and accounting system in the world runs on double-entry — it is the six-hundred-year-old general ledger, digitised. Stripe, Square, and PayPal keep internal ledgers of every charge, refund, fee, and payout so their books are provable and reconcilable. A wave of infrastructure now offers the ledger as a product: TigerBeetle is a database built from scratch for double-entry financial transactions at extreme throughput; Formance, Modern Treasury, and Fragment provide ledger-as-a-service so a fintech does not rebuild this from zero. And outside of money, the same append-only, derive-the-state-from-events shape is exactly event sourcing, used for order lifecycles, inventory, and audit trails. Different names, one idea: record the movements, never the mutable total.
A ledger table and a balanced posting
The whole model is a narrow append-only table and one rule enforced on writes:
The shape
- The table, append-only.
ledger_entries(id, txn_id, account_id, amount_minor, direction, idempotency_key UNIQUE, created_at)—amount_minoris an integer (cents),directionis debit or credit, and rows are only ever inserted, never updated. - A movement is a balanced transaction. One
txn_idgroups the two sides: insert a debit torevenuefor810and a credit tocustomer_cashfor810— the app asserts the debits and credits under atxn_idsum to zero before it commits. - Exactly-once. The
idempotency_keyuniqueness constraint makes a retried posting a no-op, so the same movement can never be recorded twice. - Correct with a reversal, never an update. To undo a bad entry, insert an opposing entry (
amount_minorswapped direction) referencing the original — the mistake and its fix are both in the history. - Read the balance.
balance = latest_snapshot + sum(amount_minor · sign(direction)) since the snapshot— derived from the entries, sped up by the checkpoint, never stored as a trusted mutable number.
Pitfalls
- Storing money as a float. Binary can’t hold most decimal fractions exactly, so amounts drift and the books stop balancing. Store integer minor units end to end.
- Editing or deleting a posted entry. The instant you mutate history, you lose the audit trail and the recovery guarantee. Correct only by appending a reversal.
- Trusting a stored balance as the source of truth. A cached balance that drifts from the entries is a silent bug. The entries are truth; a stored balance is a derived read model you can always re-derive and check.
- Non-idempotent postings. A retried write that appends a second entry poisons every balance derived from it. Every posting carries a unique idempotency key.
- Single-entry shortcuts. Recording only one side of a movement throws away the balance invariant that catches lost or created money. Keep both sides.
- Never snapshotting. Summing all of history on every read works in a demo and dies in production. Checkpoint balances and sum only what came after.
Best practices
- Append, never overwrite — every money movement is a new immutable entry; the past is set in stone.
- Balance every entry — debits equal credits, so the whole ledger sums to zero and a lost cent is detectable.
- Store integer minor units — exact money arithmetic, no floating-point drift; format to decimals only for display.
- Make every posting idempotent — a unique key so a retried write records the movement exactly once.
- Derive the balance, snapshot for speed — the entries are truth; checkpoints keep reads fast without a second source of truth.
- Correct with reversals — fix a mistake by appending its opposite, keeping the error and its fix both auditable.
- Reconcile against the outside — diff the ledger against the provider on a schedule to catch drift the ledger alone can’t see.
Rapid-fire cheat-sheet (intern → principal)
- "Why not just keep a balance column and update it?"
- A column you overwrite only remembers its latest value, so the moment anything goes half-finished — a crash, a dispute — you have a number with no explanation and no way to recover. Money needs its history, so you append immutable entries instead and derive the balance from them.
- "What does double-entry mean, and why?"
- Money only moves, it never appears or vanishes — so every entry records both ends: a debit to one account and a credit to another, equal amounts summing to zero. The payoff is an invariant: the whole ledger must always balance, so a bug that created or lost money is detectable, not silent.
- "How do you fix a wrong entry?"
- You never edit or delete it. You append a reversing entry that cancels its effect, then post the correct one. The mistake stays visible, cancelled — which is exactly what makes the ledger auditable and trustworthy.
- "Where does the balance come from?"
- It is derived: sum the account’s entries. To keep reads fast as history grows, you periodically snapshot the balance and sum only the entries since the last snapshot. The snapshot is a cache of a computation, not a second source of truth.
- "How do you represent money, and why does it matter?"
- As an integer count of the smallest unit — cents, not a float. Floating-point can’t hold most decimal fractions exactly, so amounts drift over millions of operations and the books stop balancing. Integers are exact; divide by 100 only when displaying.
- "How does this fit the saga and reconciliation?" (the principal one)
- The ledger IS the saga’s durable log and the money’s source of truth: the saga appends PENDING/CHARGED/GRANTED/REFUNDED so a crash is recoverable and the books are provable. Postings are idempotent (the Chapter 2 key) so a retry records once. And because your ledger is only your view, a scheduled reconciliation diffs it against the provider’s to catch drift — the ledger is what makes that diff possible.
The takeaway
By GOAT Engineer. Back to Concept Library. Privacy Policy · Contact.