In Part 1 we stopped a payment from being applied twice. But we applied it by adding a number to a balance_minor column, and that hides two harder questions. What kind of number should money be? And when a balance looks wrong, how do you prove what it should be?
Chapter 3 covers representing money so the arithmetic never drifts. Chapter 4 builds an immutable ledger, the one record of every movement of money, from which any balance can be rebuilt. Chapter 5 then turns “this should never happen” into rules the system enforces.
Chapter 3
Representing money and financial values
Most money bugs are dull. Nobody hacks anything; a balance is off by a cent, or a fee rounds differently in two services, or a mobile app shows €39.99 when the server charged €40.00. Each one is small, but together they make finance stop trusting your numbers, and after that every report needs a manual check.
Why floating-point numbers are dangerous
Computers usually store decimals as binary floating-point numbers (float in Python, float64 in Go, every number in JavaScript). They are fast and good for measurements like distances or temperatures. But they store numbers in base 2, and most decimal fractions, like 0.1, have no exact base-2 form. It's the same reason 1/3 has no exact decimal form: you get 0.3333… forever and have to stop somewhere.
>>> 0.1 + 0.2
0.30000000000000004
>>> from decimal import Decimal
>>> Decimal("0.1") + Decimal("0.2")
Decimal('0.3')
>>> Decimal(0.1) # built from a float: the float's error comes with it
Decimal('0.1000000000000000055511151231257827021181583404541015625')Python's own documentation makes the point with 0.1 + 0.1 + 0.1 - 0.3, which is exactly zero in decimal arithmetic and 5.5511151231257827e-017 in binary floating point (Python: decimal). The last line above is the trap people fall into after switching to decimals: if you build a decimal from a float, you've already lost. Always build it from a string or an integer.
Three safe ways to store money
| Approach | Example for €40.00 | Good for | Watch out for |
|---|---|---|---|
| Integer minor units | 4000 + "EUR" | Fiat currencies, payment amounts, anything with a fixed number of decimals | You must know each currency's exponent. Overflow with very high-precision assets. |
| Fixed-precision decimal | 40.00 as numeric(38,18) | Ledgers holding many assets, prices, rates, fractional units | Rounding happens when you store into a smaller scale. Choose the scale on purpose. |
| Decimal library in code | Decimal("40.00"), decimal.NewFromString("40.00") | Calculations: fees, FX, interest, allocation | Must never be created from a float. Precision and rounding must be set explicitly. |
| Binary float | 40.0 | Nothing involving money | Everything above. |
Real systems combine them. Payment amounts travel as integer minor units, which is also how providers want them: Stripe “expects currency values using the given denomination's smallest unit represented without decimals” (Stripe: currencies). The ledger stores PostgreSQL numeric, which the docs recommend “for storing monetary amounts and other quantities where exactness is required” (PostgreSQL: numeric types). And calculations in Go or Python use a decimal library.
Every currency has its own precision
“Minor units” means something different per currency. The euro and the US dollar have 2 decimal places. The Japanese yen has 0: you can't charge ¥10.50. The Kuwaiti dinar has 3.
These numbers come from the ISO 4217 currency standard, and they are a property of the currency, not of the amount. So an amount means nothing without its currency, and you never guess the exponent by looking at the number.
// Minor units per currency (ISO 4217). Look it up; never infer it from an amount.
var minorUnits = map[string]int32{
"EUR": 2,
"USD": 2,
"INR": 2,
"JPY": 0,
"KWD": 3,
}Providers add their own quirks on top of this. Stripe, for example, lists a few currencies that are zero-decimal but must still be sent as two-decimal values for backward compatibility (Stripe: currencies). Keep the conversion between your representation and each provider's in one adapter, with tests, rather than scattered through the code.
Assets with more decimals than money
Wallets often hold things that aren't currencies: fund units, fractional shares, loyalty points, crypto tokens. Each has its own precision, and some have a lot of it. Many tokens use 18 decimal places, which breaks integer minor units quickly: a signed 64-bit integer tops out around 9.2 × 1018, so with 18 decimals it can hold only about 9 whole tokens.
For a multi-asset ledger I use numeric(38, 18): 38 digits in total, 18 after the decimal point. That leaves 20 digits before the point, which is plenty for any realistic balance. An assets table records each asset's real scale, and the code rounds to that scale before writing. The column is wide enough for everything; the asset decides how much of that width it uses.
Rounding: choose a rule, apply it once
Rounding is where two correct-looking implementations disagree. 2.5 rounds to 3 under “half up” but to 2 under “half even” (also called banker's rounding, which rounds ties to the nearest even digit to avoid drifting upwards over many operations). Different tools default to different rules:
- PostgreSQL's
numericrounds ties away from zero, while itsdouble precisiontype rounds ties to even on most machines (PostgreSQL: numeric types). - Python's
decimalmodule defaults toROUND_HALF_EVENwith 28 digits of precision (Python: decimal). - Go's
shopspring/decimaloffers bothRoundandRoundBank(shopspring/decimal).
So if your Python service computes a fee and your SQL report recomputes it, they can disagree on ties unless you choose the rule explicitly. My rules of thumb:
- Write the rounding rule down per calculation (“fees: half up to minor units”), and pass the mode explicitly in code. Never rely on a default.
- Round once, at the end, not at every intermediate step.
- Round in your customer's favour only if the business decides that, and then do it consistently.
// FeeMinor returns amountMinor × bps / 10,000, rounded half up.
// bps is basis points: 150 bps = 1.5%. Both inputs are positive.
// amountMinor × bps must fit in an int64: fine for any real payment.
func FeeMinor(amountMinor, bps int64) int64 {
return (amountMinor*bps + 5_000) / 10_000
}
// Convert turns an amount in one currency into minor units of another at rate,
// rounding half-to-even once, at the very end.
func Convert(amountMinor int64, fromExp, toExp int32, rate decimal.Decimal) int64 {
major := decimal.New(amountMinor, -fromExp) // 4000 with exponent 2 → 40.00
converted := major.Mul(rate).RoundBank(toExp) // 40.00 × 0.8571 = 34.284 → 34.28
return converted.Shift(toExp).IntPart() // 34.28 → 3428
}from decimal import Decimal, ROUND_HALF_EVEN
rate = Decimal("0.8571") # from a string, never Decimal(0.8571)
amount = Decimal("40.00")
converted = (amount * rate).quantize(Decimal("0.01"), rounding=ROUND_HALF_EVEN)
# Decimal('34.28')Splitting money without losing cents
A special kind of rounding bug appears when you split an amount: a bill shared between three people, a fee split between partners, a refund spread over instalments. Round each share separately and the shares stop adding up to the total.
The fix is to allocate in integer minor units, then hand out the leftover units by a fixed, deterministic rule. A common one is “largest remainder first, ties by position”:
// Allocate splits totalMinor into parts proportional to weights.
// The parts always add up to totalMinor. Leftover minor units go to the parts
// with the largest remainders, ties broken by position, so the result is deterministic.
func Allocate(totalMinor int64, weights []int64) []int64 {
var sum int64
for _, w := range weights {
sum += w
}
parts := make([]int64, len(weights))
rems := make([]int64, len(weights))
var given int64
for i, w := range weights {
parts[i] = totalMinor * w / sum
rems[i] = totalMinor * w % sum
given += parts[i]
}
order := make([]int, len(weights))
for i := range order {
order[i] = i
}
sort.SliceStable(order, func(a, b int) bool { return rems[order[a]] > rems[order[b]] })
for k := int64(0); k < totalMinor-given; k++ {
parts[order[k]]++
}
return parts
}
// Allocate(10000, []int64{1, 1, 1}) → [3334 3333 3333]Freeze the price you quoted
When a customer converts currency or buys an asset, the price keeps moving, but the customer agreed to one specific price, at one moment, with one specific fee. If you only store the final amounts, you can never answer the question every support team eventually gets: “why did I get 2.4932 units and not 2.5?”
So store the quote: every input to the calculation, as it was used.
CREATE TABLE quotes (
id text PRIMARY KEY,
customer_id text NOT NULL,
pay_asset text NOT NULL, -- what the customer pays in, e.g. 'EUR'
receive_asset text NOT NULL, -- what they get, e.g. 'FUNDX'
rate numeric(38, 18) NOT NULL CHECK (rate > 0),
rate_source text NOT NULL, -- which feed or provider gave us the rate
rate_fetched_at timestamptz NOT NULL,
fee_bps integer NOT NULL CHECK (fee_bps >= 0),
pay_amount numeric(38, 18) NOT NULL,
fee_amount numeric(38, 18) NOT NULL,
receive_amount numeric(38, 18) NOT NULL,
rounding_rule text NOT NULL, -- e.g. 'half_even@4'
calc_version integer NOT NULL, -- which version of the pricing code produced this
expires_at timestamptz NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);The transaction then points at the quote it was executed against. Two of the columns are there for later: calc_version lets you change the pricing code and still explain old transactions, and expires_at stops a customer from executing a quote after the market has moved.
Money at the API boundary
Even if your server is perfect, the number can be damaged on the way in or out. JSON numbers have no fixed precision. RFC 8259 notes that implementations commonly use IEEE 754 double-precision numbers, and only integers within ±(253 − 1) are safe to exchange (RFC 8259, section 6).
In JavaScript that limit is Number.MAX_SAFE_INTEGER, 9,007,199,254,740,991 (MDN). Any client that parses {"amount": 40.10} into a double already has the float problem.
Two conventions are safe:
{ "amount": "40.10", "currency": "EUR" }
{ "amount_minor": 4010, "currency": "EUR" }A decimal string keeps any precision and is unambiguous. Integer minor units are compact and match what providers expect, but only stay safe below 253, so they suit fiat payments better than 18-decimal tokens. Whichever you choose, reject anything else at the edge:
from decimal import Decimal
MINOR_UNITS = {"EUR": 2, "USD": 2, "INR": 2, "JPY": 0, "KWD": 3}
def parse_amount(raw, currency: str) -> Decimal:
if not isinstance(raw, str):
raise ValueError('amount must be a string, like "40.10"') # rejects 40.1 floats
amount = Decimal(raw)
if not amount.is_finite() or amount <= 0:
raise ValueError("amount must be a positive number")
if -amount.as_tuple().exponent > MINOR_UNITS[currency]:
raise ValueError(f"too many decimal places for {currency}")
return amountIf you parse JSON yourself in Python, json.loads(text, parse_float=Decimal) stops the standard library from turning numbers into floats in the first place.
Calculations must be deterministic
A financial calculation should give the same answer every time it runs with the same inputs. Retries depend on that, because a retried job must compute the same fee. So do audits, where you have to show how a number was produced, and reconciliation, where two systems have to agree. To get there you need:
- no floats anywhere in the path;
- every rounding mode and precision set explicitly;
- no hidden inputs: don't read the clock or fetch a live rate in the middle of a calculation. Pass them in, and store them with the result;
- a stable order for anything that depends on order, like allocation tie-breaks.
Checklist
- No binary floats anywhere money is stored, sent or calculated.
- Every amount travels with its currency or asset code.
- Currency exponents come from a lookup table, never from the amount.
- Rounding mode and precision are explicit, documented and applied once.
- Splits use integer allocation, so the parts always add up to the total.
- Quotes store every input: rate, source, time, fee, rounding rule and code version.
- APIs accept amounts as decimal strings or integer minor units, and reject floats.
Chapter 4
Building an immutable financial ledger
If I could keep only one chapter of this handbook, it would be this one. A ledger is what lets you answer “why is this balance what it is?” with a list of facts instead of a guess.
The problem: balances spread across workflow tables
Systems usually start without a ledger. There is a payments table, then withdrawals, then refunds, then a rewards table for a marketing campaign, then manual_adjustments when support needs to fix something. The customer's balance is then whatever this query says:
-- Don't do this: a balance assembled from every workflow table
SELECT
(SELECT coalesce(sum(amount_minor), 0) FROM payments WHERE customer_id = $1 AND status = 'SUCCESS')
- (SELECT coalesce(sum(amount_minor), 0) FROM withdrawals WHERE customer_id = $1 AND status IN ('PENDING', 'PAID'))
+ (SELECT coalesce(sum(amount_minor), 0) FROM refunds WHERE customer_id = $1 AND status = 'COMPLETED')
+ (SELECT coalesce(sum(amount_minor), 0) FROM rewards WHERE customer_id = $1 AND credited)
+ (SELECT coalesce(sum(amount_minor), 0) FROM manual_adjustments WHERE customer_id = $1);This query has to know which statuses count, that withdrawals subtract while they're still pending, and that refunds use COMPLETED while payments use SUCCESS. Every new feature has to update it and every report has to copy it.
If a workflow row is ever updated in place, yesterday's balance changes and nobody notices. Worse, nothing stops a workflow table from being edited, so you can't prove the balance was ever right.
The mental model: an append-only list of money movements
A ledger separates two jobs that the tables above mix together. Workflow records (payments, withdrawals, refunds) track a process: what was asked, what state it's in, which provider is involved. They change as the process moves along. Ledger entries record money that moved (this account went up by this much, because of that), and they never change.
The ledger is append-only: you add entries, and you never update or delete them. A balance is the sum of an account's entries. If something was wrong, you don't edit the past; you add a new entry that corrects it, the way an accountant writes a correction into a paper ledger instead of tearing out the page.
Credits, debits and double entry
Accounting uses the words debit and credit, and they confuse everyone at first because whether a debit increases or decreases an account depends on the account's type. In code it's simpler to use signed amounts: positive means the account goes up, negative means it goes down. I'll use that convention for the rest of the handbook.
Double entry is one rule: money never appears or disappears, it only moves. So every movement is recorded twice: once where it left, once where it arrived. In signed amounts, the entries for one movement always sum to zero. If a customer's wallet goes up by €40, some other account must go down by €40. Usually that's a clearing account representing “money the provider owes us”.
The rule also gives you a check for free: add up every entry in the whole ledger, per currency, and the answer must be zero. If it isn't, something created or destroyed money, and you know straight away.
Asset-movement ledger or full general ledger?
Not every system needs a full accounting general ledger. There are two common levels:
| Asset-movement ledger | Double-entry general ledger | |
|---|---|---|
| What it records | Changes to customer balances only: +40 to a wallet, −80 for a withdrawal. | Every movement on both sides, including platform accounts like clearing, fees and rewards. |
| Sums to zero? | No. Customer balances just add up to “what we owe customers”. | Yes, per journal and across the whole ledger. |
| Good for | Simple wallets and early products where finance keeps the books elsewhere. | Platforms that hold money, earn fees, pay rewards, or need to reconcile with banks and auditors. |
| Cost | Simpler, fewer rows. | More rows and more design up front, but far easier to audit. |
If you're starting a system that holds customer money, I'd go straight to double entry. The extra rows are cheap, and moving to double entry later means migrating years of history. The rest of this chapter builds a double-entry ledger.
Journals: why one transaction produces many entries
One business transaction usually touches several accounts. The running example: a customer buys €100 worth of a fund (“FUNDX”, made up) and, as part of a campaign, receives a €5 reward. That is three separate movements, and six entries:
- Pay: €100 leaves the customer's wallet and goes to a purchase clearing account.
- Deliver units: 2.5 FUNDX units (at an illustrative €40 each) move from the platform's inventory to the customer's holdings.
- Reward: €5 goes to the customer's wallet, paid from the platform's rewards expense account.
All six entries share a journal ID (also called a group or posting ID): j_1001. The journal is the unit that must be all-or-nothing. Either all six entries exist or none do, because five of them alone would create or destroy money. The journal also records why it exists: its source is transaction txn_7Q2.
This journal holds two assets, and each one balances separately: the EUR entries sum to zero on their own, and so do the FUNDX entries. We never add euros to fund units.
The schema
CREATE TABLE assets (
code text PRIMARY KEY, -- 'EUR', 'FUNDX'
scale smallint NOT NULL CHECK (scale BETWEEN 0 AND 18)
);
CREATE TABLE ledger_accounts (
id text PRIMARY KEY, -- e.g. 'cust:c_42:wallet:EUR'
owner_type text NOT NULL CHECK (owner_type IN ('CUSTOMER', 'PLATFORM')),
owner_id text NOT NULL,
purpose text NOT NULL, -- 'wallet', 'holdings', 'clearing', 'rewards_expense' …
asset text NOT NULL REFERENCES assets (code),
allow_negative boolean NOT NULL DEFAULT false,
UNIQUE (owner_type, owner_id, purpose, asset),
UNIQUE (id, asset) -- lets entries check their asset matches
);
CREATE TABLE ledger_journals (
id text PRIMARY KEY, -- the group identifier, e.g. 'j_1001'
kind text NOT NULL CHECK (kind IN ('PAYMENT', 'PURCHASE', 'WITHDRAWAL', 'REWARD',
'REVERSAL', 'ADJUSTMENT', 'OPENING_BALANCE')),
source_type text NOT NULL, -- what caused it: 'transaction', 'ledger_journal', …
source_id text NOT NULL,
reason text,
created_by text NOT NULL, -- a service name or a person
effective_at timestamptz NOT NULL, -- when it counts for the balance
created_at timestamptz NOT NULL DEFAULT now(),-- when we wrote it down
UNIQUE (source_type, source_id, kind) -- one journal of each kind per cause
);
CREATE TABLE ledger_entries (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
journal_id text NOT NULL REFERENCES ledger_journals (id),
line_no smallint NOT NULL,
account_id text NOT NULL,
asset text NOT NULL,
amount numeric(38, 18) NOT NULL CHECK (amount <> 0),
reversal_of_id bigint REFERENCES ledger_entries (id),
created_at timestamptz NOT NULL DEFAULT now(),
FOREIGN KEY (account_id, asset) REFERENCES ledger_accounts (id, asset),
UNIQUE (journal_id, line_no),
UNIQUE (reversal_of_id) -- an entry can be reversed at most once
);
CREATE INDEX ledger_entries_account_time ON ledger_entries (account_id, created_at);Almost every line here is a decision. Going through them in turn:
numeric(38, 18)for amounts, as discussed in Chapter 3. TheCHECK (amount <> 0)rejects pointless zero entries.- The composite foreign key
(account_id, asset)makes it impossible to write a FUNDX entry to a EUR account. It needs the matchingUNIQUE (id, asset)on accounts. UNIQUE (source_type, source_id, kind)on journals is the ledger's idempotency guard: a given transaction can produce at most onePAYMENTjournal, no matter how many times the posting code runs. This is the database enforcing “never move money twice”.UNIQUE (journal_id, line_no)gives each entry a stable position in its journal.UNIQUE (reversal_of_id)means an entry can be cancelled at most once.effective_atvscreated_at. Sometimes money counts from a different time than when you recorded it: a bank credit you learn about at 09:00 that was value-dated yesterday.effective_atis when it counts;created_atis when you knew. Keep both. Statements usually use effective time; audits often ask what you knew and when.
Polymorphic references
source_type plus source_id is a polymorphic reference: the source could be a row in several different tables, so the database can't enforce it with a foreign key. You have three options:
- Keep it polymorphic and check it in code and in reconciliation (every journal's source must exist). Simple and flexible.
- One nullable foreign key per source table (
payment_id,withdrawal_id, …) with aCHECKthat exactly one is set. Fully enforced, but the table grows a column per feature. - A shared parent table, such as
financial_transactions, that every workflow row also has a row in. The journal points there with a real foreign key. This is my usual choice once there are more than two or three sources.
Making the ledger enforce its own rules
Two rules are too important to leave to application code: journals must balance, and entries must never change. PostgreSQL can enforce both.
-- 1. Every journal balances per asset. A constraint trigger can be deferred,
-- so it runs at COMMIT, after all the journal's entries are inserted.
CREATE FUNCTION check_journal_balanced() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF EXISTS (
SELECT 1 FROM ledger_entries
WHERE journal_id = NEW.journal_id
GROUP BY asset
HAVING sum(amount) <> 0
) THEN
RAISE EXCEPTION 'journal % does not balance', NEW.journal_id;
END IF;
RETURN NULL;
END $$;
CREATE CONSTRAINT TRIGGER journal_balanced
AFTER INSERT ON ledger_entries
DEFERRABLE INITIALLY DEFERRED
FOR EACH ROW EXECUTE FUNCTION check_journal_balanced();
-- 2. Entries and journals are append-only.
CREATE FUNCTION forbid_change() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
RAISE EXCEPTION '% is append-only', TG_TABLE_NAME;
END $$;
CREATE TRIGGER ledger_entries_append_only BEFORE UPDATE OR DELETE ON ledger_entries
FOR EACH ROW EXECUTE FUNCTION forbid_change();
CREATE TRIGGER ledger_entries_no_truncate BEFORE TRUNCATE ON ledger_entries
FOR EACH STATEMENT EXECUTE FUNCTION forbid_change();
CREATE TRIGGER ledger_journals_append_only BEFORE UPDATE OR DELETE ON ledger_journals
FOR EACH ROW EXECUTE FUNCTION forbid_change();
CREATE TRIGGER ledger_journals_no_truncate BEFORE TRUNCATE ON ledger_journals
FOR EACH STATEMENT EXECUTE FUNCTION forbid_change();RAISE EXCEPTION raises an error, which aborts the transaction (PostgreSQL: errors and messages). So an unbalanced journal can't commit, and an UPDATE or DELETE on an entry fails. Note the separate TRUNCATE triggers: row-level triggers don't fire on TRUNCATE, which can only have statement-level triggers (PostgreSQL: CREATE TRIGGER).
Triggers stop mistakes, not a determined database superuser. Add a second wall with permissions: the role your application uses gets INSERT and SELECT on the ledger tables and nothing else.
Posting a journal from Go
The posting function checks the journal balances before touching the database (a cheap, early error), then inserts the journal with the idempotency guard, then the entries. It runs inside the caller's transaction, so the journal commits together with the business state change that caused it, like the payment moving to SUCCESS in Part 1.
type Entry struct {
AccountID string
Asset string
Amount decimal.Decimal // signed: positive increases the account, negative decreases it
}
type Journal struct {
ID string
Kind string
SourceType string
SourceID string
Reason string
CreatedBy string
EffectiveAt time.Time
Entries []Entry
}
var (
ErrUnbalanced = errors.New("journal does not balance")
ErrAlreadyPosted = errors.New("journal already posted for this source")
)
// PostJournal writes a journal and its entries inside tx. It is idempotent per
// (source_type, source_id, kind): posting the same cause twice returns
// ErrAlreadyPosted and writes nothing, so callers can retry safely.
func PostJournal(ctx context.Context, tx pgx.Tx, j Journal) error {
totals := map[string]decimal.Decimal{}
for _, e := range j.Entries {
if e.Amount.IsZero() {
return fmt.Errorf("%w: zero amount for %s", ErrUnbalanced, e.AccountID)
}
totals[e.Asset] = totals[e.Asset].Add(e.Amount)
}
for asset, sum := range totals {
if !sum.IsZero() {
return fmt.Errorf("%w: %s is off by %s", ErrUnbalanced, asset, sum)
}
}
tag, err := tx.Exec(ctx, `
INSERT INTO ledger_journals (id, kind, source_type, source_id, reason, created_by, effective_at)
VALUES ($1, $2, $3, $4, $5, $6, $7)
ON CONFLICT (source_type, source_id, kind) DO NOTHING`,
j.ID, j.Kind, j.SourceType, j.SourceID, j.Reason, j.CreatedBy, j.EffectiveAt)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return ErrAlreadyPosted
}
for i, e := range j.Entries {
_, err := tx.Exec(ctx, `
INSERT INTO ledger_entries (journal_id, line_no, account_id, asset, amount)
VALUES ($1, $2, $3, $4, $5::numeric)`,
j.ID, i+1, e.AccountID, e.Asset, e.Amount.String())
if err != nil {
return err
}
}
return nil
}Amounts are sent to PostgreSQL as decimal strings and cast with ::numeric, so no float ever touches them. The caller decides what ErrAlreadyPosted means: for a retried webhook it means “done already, acknowledge it”.
Fixing mistakes: update, reversal or adjustment
Sooner or later a journal will be wrong. Say a bug credited a customer €50 instead of €40. There are three ways to fix it, and only two are acceptable.
- Updating the entry changes 50 to 40 in place. The balance is now right, but the ledger no longer shows that it was ever wrong. Any statement, report or reconciliation that saw the €50 can no longer be explained. The triggers above make this impossible anyway.
- A reversal posts an exact mirror of the wrong journal (every entry negated), which brings everything back to where it was, then a new, correct journal is posted. It's the clearest record: “this happened, it was cancelled, this is what should have happened”.
- An adjustment posts only the difference (−€10), with a reason. It's smaller, and useful when the original journal was partly right or when the correction comes from outside, like a bank fee you only learn about on the statement.
A reversal is itself a new financial transaction: a new journal, written now, pointing back at what it cancels. Each reversing entry references the entry it cancels with reversal_of_id:
// ReverseJournal posts the mirror image of an existing journal. Each new entry
// points at the entry it cancels. Reversing the same journal twice is impossible:
// the second attempt hits UNIQUE (source_type, source_id, kind) and changes nothing.
func ReverseJournal(ctx context.Context, tx pgx.Tx, originalID, newID, reason, by string) error {
tag, err := tx.Exec(ctx, `
INSERT INTO ledger_journals (id, kind, source_type, source_id, reason, created_by, effective_at)
SELECT $1, 'REVERSAL', 'ledger_journal', id, $3, $4, now()
FROM ledger_journals
WHERE id = $2 AND kind <> 'REVERSAL'
ON CONFLICT (source_type, source_id, kind) DO NOTHING`,
newID, originalID, reason, by)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return ErrAlreadyPosted // already reversed, or not a journal we can reverse
}
_, err = tx.Exec(ctx, `
INSERT INTO ledger_entries (journal_id, line_no, account_id, asset, amount, reversal_of_id)
SELECT $1, line_no, account_id, asset, -amount, id
FROM ledger_entries
WHERE journal_id = $2`,
newID, originalID)
return err
}Two guards stop double reversals, at two levels. The journal-level UNIQUE (source_type, source_id, kind) means only one REVERSAL journal can point at a given original. The entry-level UNIQUE (reversal_of_id) means no entry can be cancelled twice, even by a different journal. We also refuse to reverse a reversal: if a reversal was a mistake, post the original again as a new journal.
Adjustments need a different kind of protection, because a person usually starts them. I like to model them as a request that a second person must approve before the journal is posted, with the “four eyes” rule enforced by the database:
CREATE TABLE adjustment_requests (
id text PRIMARY KEY,
account_id text NOT NULL REFERENCES ledger_accounts (id),
amount numeric(38, 18) NOT NULL CHECK (amount <> 0),
reason text NOT NULL,
requested_by text NOT NULL,
approved_by text,
approved_at timestamptz,
CHECK (approved_by IS NULL OR approved_by <> requested_by) -- nobody approves their own
);When it's approved, the posting code creates an ADJUSTMENT journal whose source is the request. The idempotency guard again means one request can only ever be posted once.
Opening balances
If you're migrating from an older system, customers arrive with existing balances. It's tempting to insert one positive entry per customer and move on, but that breaks double entry: money appears from nowhere, and the ledger no longer sums to zero.
Instead, post an OPENING_BALANCE journal per account, balanced against a platform account like opening_balance_equity. Its source is the migration batch. Reconciliation can then check that the sum of opening balances equals the old system's closing total, and the ledger stays balanced from its first entry.
Reading balances: sums, history, projections and snapshots
Because the ledger is the truth, a balance is a query:
-- Current balance of one account, straight from the ledger
SELECT coalesce(sum(amount), 0)
FROM ledger_entries
WHERE account_id = 'cust:c_42:wallet:EUR';
-- The balance as it stood at the end of 31 October, by effective time
SELECT coalesce(sum(e.amount), 0)
FROM ledger_entries e
JOIN ledger_journals j ON j.id = e.journal_id
WHERE e.account_id = 'cust:c_42:wallet:EUR'
AND j.effective_at < '2026-11-01';The second query is historical balance reconstruction, and it comes for free with an append-only ledger: since nothing is ever updated, any past balance can be rebuilt exactly. Keep balances in a mutable column instead and yesterday's value is gone.
Summing every entry works well for a long time with the (account_id, created_at) index, but an active account eventually has years of entries, and reading the balance on every request gets slow. Two tools fix that:
- A balance projection: an
account_balancestable holding the current balance per account, updated in the same transaction as the entries. Reads become a single-row lookup. It's also what lets us block overdrafts, as Chapter 5 shows. - Snapshots: a periodic copy of each account's balance at a point in time. Any historical balance is the latest snapshot before it, plus the entries after that.
CREATE TABLE account_balances (
account_id text PRIMARY KEY REFERENCES ledger_accounts (id),
balance numeric(38, 18) NOT NULL DEFAULT 0,
version bigint NOT NULL DEFAULT 0,
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE balance_snapshots (
account_id text NOT NULL REFERENCES ledger_accounts (id),
as_of timestamptz NOT NULL,
balance numeric(38, 18) NOT NULL,
PRIMARY KEY (account_id, as_of)
);
-- Balance now = latest snapshot + everything recorded since
SELECT s.balance + coalesce((
SELECT sum(e.amount)
FROM ledger_entries e
WHERE e.account_id = s.account_id
AND e.created_at >= s.as_of), 0) AS balance
FROM balance_snapshots s
WHERE s.account_id = 'cust:c_42:wallet:EUR'
ORDER BY s.as_of DESC
LIMIT 1;Checking the ledger
Reconciliation with the outside world gets its own chapter (Chapter 20). But the ledger can also check itself, with a few queries that should always return zero rows. Run them on a schedule and alert on any result.
-- 1. Every journal balances per asset
SELECT journal_id, asset, sum(amount)
FROM ledger_entries
GROUP BY journal_id, asset
HAVING sum(amount) <> 0;
-- 2. The whole ledger nets to zero per asset
SELECT asset, sum(amount)
FROM ledger_entries
GROUP BY asset
HAVING sum(amount) <> 0;
-- 3. Every projection matches the ledger
SELECT b.account_id, b.balance, coalesce(sum(e.amount), 0) AS ledger_balance
FROM account_balances b
LEFT JOIN ledger_entries e ON e.account_id = b.account_id
GROUP BY b.account_id, b.balance
HAVING b.balance <> coalesce(sum(e.amount), 0);Because the projection is updated in the same transaction as the entries, and a single query sees one consistent snapshot of the database, query 3 doesn't report false alarms for transactions that are still in flight.
Indexes and constraints, briefly
A ledger is write-heavy and read in a few predictable ways, so index for those:
(account_id, created_at)for balances and statements, the most common read.(journal_id, line_no), already created by the unique constraint, for “show me this journal”.(source_type, source_id, kind)on journals, from the unique constraint, for “what did this payment post?”.
Resist adding more “just in case”. Every index is extra work on every insert, and the ledger receives a lot of inserts. Chapter 14 covers how to find which indexes your queries actually use.
When to partition, and what it costs
A ledger only grows. Eventually the entries table gets big enough that vacuuming it, backing it up or building an index on it becomes slow. Partitioning splits one logical table into many physical ones, for example one per month, inside the same database. Old months can then be detached and archived cheaply, and queries that filter by time only read the partitions they need.
It has a real cost for a ledger, though. In PostgreSQL, a unique or primary key constraint on a partitioned table must include all the partition key columns, because each partition can only check uniqueness within itself (PostgreSQL: partitioning). If you partition entries by created_at, UNIQUE (journal_id, line_no) must become UNIQUE (journal_id, line_no, created_at), which no longer means “unique per journal”. The same goes for UNIQUE (reversal_of_id).
CREATE SEQUENCE ledger_entry_id_seq;
CREATE TABLE ledger_entries_partitioned (
id bigint NOT NULL DEFAULT nextval('ledger_entry_id_seq'),
journal_id text NOT NULL,
line_no smallint NOT NULL,
account_id text NOT NULL,
asset text NOT NULL,
amount numeric(38, 18) NOT NULL CHECK (amount <> 0),
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (id, created_at), -- must include the partition key
UNIQUE (journal_id, line_no, created_at) -- weaker than before: see text
) PARTITION BY RANGE (created_at);
CREATE TABLE ledger_entries_2026_11 PARTITION OF ledger_entries_partitioned
FOR VALUES FROM ('2026-11-01') TO ('2026-12-01');The way out is to keep the guarantees that matter on a table you don't partition. The journals table is much smaller than the entries table, and its UNIQUE (source_type, source_id, kind) still stops double posting and double reversal at the journal level. So partition entries, keep journals whole, and accept that entry-level uniqueness becomes a reconciliation check instead of a constraint.
Partitioning is not sharding. Partitions live in one database, so a transaction can still write a whole journal atomically. Sharding spreads data across several databases, and a journal that touches a customer account on one shard and a platform account on another can no longer commit in one transaction. Shard a ledger only when you truly must, and design journals so they stay within one shard.
Common mistakes
- Computing balances from workflow tables instead of a ledger.
- Single entries that don't balance, so money appears from nowhere (often during migrations).
- Updating or deleting entries to fix mistakes, instead of reversing or adjusting.
- Mixing assets in one sum, or writing a token amount to a currency account.
- Treating the balance projection as the truth and never checking it against the ledger.
- No idempotency on journals, so a retried job posts the same payment twice.
- Partitioning early and losing uniqueness guarantees without noticing.
Checklist
- Every movement of money is a balanced journal: entries sum to zero per asset.
- Entries and journals are append-only, enforced by triggers and permissions.
- Each journal has a source, and
UNIQUE (source_type, source_id, kind)stops double posting. - Corrections are reversals or approved adjustments, never edits.
- Each entry's asset matches its account's asset, enforced by a composite foreign key.
- Balance projections are updated in the same transaction as entries, and checked against the ledger.
- Snapshots are built with a delay longer than the longest transaction.
- The whole ledger is checked to net to zero per asset, on a schedule.
Chapter 5
Transaction consistency and financial invariants
An invariant is something that must always be true, no matter what order things happen in, how many times a message arrives, or which server crashes. “A journal sums to zero” is one, and you've already met several others. This chapter collects them and asks one practical question of each: what stops it breaking?
The invariants of a payment system
| Invariant | Database constraint | Runtime check | Reconciliation |
|---|---|---|---|
| A transaction is credited at most once | UNIQUE (source_type, source_id, kind) on journals | Conditional status update (Part 1) | Payments with more than one PAYMENT journal |
| A reversal happens at most once | Same unique key with kind REVERSAL; UNIQUE (reversal_of_id) | State machine: SUCCESS → REVERSED only once | Entries reversed more than once |
| The same funds can't be spent twice | Conditional update on the balance projection | Balance and limit checks before starting | Negative balances on accounts that don't allow them |
| A successful transaction has its postings | Status change and journal in one transaction | Posting code called from the transition | SUCCESS payments without a journal, journals without a SUCCESS payment |
| Related entries commit together | One database transaction; deferred balance trigger | Journal balance check in code | Journals that don't sum to zero |
| Every balance is explainable | Append-only triggers on entries | All balance changes go through posting code | Projection equals the sum of entries |
Three ways to enforce an invariant
The last three columns of that table are three different kinds of protection, and each is good at something different.
- Database constraints (
UNIQUE,CHECK, foreign keys, triggers, conditional updates) are absolute. No code path, script or race can get past them. But they can only see what's in the database, and they struggle with rules that span many rows or need outside knowledge. - Runtime validation in your services can express any business rule: limits, frozen accounts, compliance checks, “this customer can't withdraw during a dispute”. But it can be skipped by a script, an old service version or a race between two requests.
- Reconciliation, checking after the fact, sees everything, including the outside world: the provider, the bank. It catches what the other two missed. But it only finds problems after they've happened.
You need all three because each has blind spots the others cover. A rule that can be a constraint should be one. A rule that can't be a constraint must be a runtime check, and a reconciliation query, so that when the runtime check is bypassed you find out the same day, not at the year-end audit.
Double spending: a race you can't see in tests
The most common invariant violation in wallets is spending the same money twice. A customer with €100 starts two €80 withdrawals at the same moment (a double tap, two devices, or a script). The obvious code looks like this:
# Naive version: do not use
def withdraw(conn, account_id, amount):
balance = conn.execute(
"SELECT balance FROM account_balances WHERE account_id = %s", (account_id,)
).fetchone()[0]
if balance < amount:
raise InsufficientFunds()
conn.execute(
"UPDATE account_balances SET balance = balance - %s WHERE account_id = %s",
(amount, account_id),
)UPDATE, so the database evaluates it against the latest committed balance.Both requests read €100, both pass the check, both subtract €80. The account ends at −€60 and €160 has gone out. In tests this almost never happens, because tests rarely run two requests at the same instant. In production, with enough traffic, it happens every week.
The fix is to make the check and the change a single statement:
var ErrInsufficientFunds = errors.New("insufficient funds")
// Debit takes amount from an account's balance projection, but only if it is there.
// The check lives inside the UPDATE, so two concurrent debits can't both pass.
func Debit(ctx context.Context, tx pgx.Tx, accountID string, amount decimal.Decimal) error {
tag, err := tx.Exec(ctx, `
UPDATE account_balances
SET balance = balance - $2::numeric, version = version + 1, updated_at = now()
WHERE account_id = $1 AND balance >= $2::numeric`,
accountID, amount.String())
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return ErrInsufficientFunds // or the account has no projection row
}
return nil
}Why does this work when the Python version didn't? When two transactions try to update the same row, PostgreSQL makes the second one wait until the first commits. Then, at the default Read Committed isolation level, it re-evaluates the second update's WHERE clause against the newly committed row (PostgreSQL: transaction isolation).
So the second withdrawal re-checks 20 >= 80, matches no rows, and is declined. We never wrote any locking code; the row lock PostgreSQL takes for the update was enough.
Keeping projections and the ledger in step
Putting the pieces together, posting a journal should update the projection for every account it touches, in the same transaction, with the overdraft guard for accounts that don't allow negative balances:
// applyToBalances updates the balance projection for each entry, inside tx.
// Accounts that don't allow negative balances can't be taken below zero.
// Entries are applied in account order so that concurrent journals touching
// the same accounts always lock them in the same order and can't deadlock.
func applyToBalances(ctx context.Context, tx pgx.Tx, entries []Entry) error {
sorted := slices.Clone(entries)
slices.SortFunc(sorted, func(a, b Entry) int { return strings.Compare(a.AccountID, b.AccountID) })
for _, e := range sorted {
tag, err := tx.Exec(ctx, `
UPDATE account_balances b
SET balance = b.balance + $2::numeric, version = b.version + 1, updated_at = now()
FROM ledger_accounts a
WHERE b.account_id = $1
AND a.id = b.account_id
AND (a.allow_negative OR b.balance + $2::numeric >= 0)`,
e.AccountID, e.Amount.String())
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return fmt.Errorf("%w: %s", ErrInsufficientFunds, e.AccountID)
}
}
return nil
}
// Post writes a journal and updates balances atomically, inside the caller's tx.
func Post(ctx context.Context, tx pgx.Tx, j Journal) error {
if err := PostJournal(ctx, tx, j); err != nil {
return err // includes ErrAlreadyPosted: nothing was written
}
return applyToBalances(ctx, tx, j.Entries)
}If any account would go negative, Post returns an error, the caller's transaction rolls back, and neither the journal nor any balance change survives. That's “related entries commit atomically” and “the same funds can't be spent twice”, enforced together.
A successful payment must have its postings
Part 1 moved a payment to SUCCESS and credited a balance in the same transaction. With a ledger, the credit becomes a journal, and the rule is the same: the status change and the journal commit together, or not at all. In the ApplyProviderStatus handler from Part 1, creditWallet becomes a call to Post with a PAYMENT journal whose source is the payment.
There's no single constraint that can express “every SUCCESS payment has exactly one PAYMENT journal”, because it spans two tables. So it lives in the code path (one function does both) and in reconciliation:
-- SUCCESS payments with no PAYMENT journal (money taken, nothing recorded)
SELECT p.id
FROM payments p
LEFT JOIN ledger_journals j
ON j.source_type = 'transaction' AND j.source_id = p.id AND j.kind = 'PAYMENT'
WHERE p.status = 'SUCCESS' AND j.id IS NULL;
-- PAYMENT journals whose payment is not SUCCESS (money recorded, not confirmed)
SELECT j.id, p.status
FROM ledger_journals j
JOIN payments p ON p.id = j.source_id
WHERE j.source_type = 'transaction' AND j.kind = 'PAYMENT'
AND p.status NOT IN ('SUCCESS', 'REFUNDED', 'REVERSED');What to monitor
- Rows returned by every invariant query. The target is zero, always. Any row is an incident, even if it's “only a cent”.
ErrUnbalancedattempts. These mean a code bug tried to post a bad journal. The guard stopped it, but the bug is still there.ErrAlreadyPostedrate. Normal at a low level (retries); a spike points to a retry storm or a duplicate-delivery problem upstream.ErrInsufficientFundsrate, split by account type. For customer accounts it's business as usual; for platform accounts it's a bug or a funding problem.- Lock wait time on
account_balances, to spot hot rows before they become an outage.
What to test
- Run two debits for more than half the balance concurrently, a thousand times. Expect exactly one success each time, and never a negative balance.
- Post the same journal twice, sequentially and concurrently. Expect one journal and
ErrAlreadyPostedfor the other. - Reverse the same journal twice. Expect one reversal.
- Try to post an unbalanced journal, bypassing the Go check. Expect the database trigger to reject it at commit.
- Try to
UPDATE,DELETEandTRUNCATEledger rows. Expect all three to fail. - Property-based test: generate thousands of random valid journals, reversals and debits, then assert that the ledger nets to zero per asset and every projection equals the sum of its entries.
Checklist
- Every invariant is written down, with what enforces it at each of the three layers.
- Anything that can be a database constraint is one.
- Balance checks and balance changes are a single conditional statement.
- Status changes and their journals commit in one transaction.
- Locks on balance rows are always taken in the same order.
- Invariant queries run on a schedule, and any result alerts a person.
Further reading
- PostgreSQL: numeric types: exact decimals, precision and rounding.
- Python: decimal: decimal arithmetic, contexts and rounding modes.
- shopspring/decimal: arbitrary-precision decimals for Go.
- Stripe: currencies: minor units and zero-decimal currencies from a provider's side.
- RFC 8259, section 6: why JSON numbers aren't safe for money.
- PostgreSQL: CREATE TRIGGER and errors and messages: constraint triggers and raising errors.
- PostgreSQL: partitioning: including the limits on unique constraints.
- PostgreSQL: transaction isolation: how concurrent updates are re-checked.
What's next
We now have money that doesn't drift, a ledger that can't be edited, and invariants enforced at three layers.
Twice in this part, a UNIQUE constraint or a conditional UPDATE did the real work of stopping duplicates and races. Part III, Idempotency and Concurrency, makes those tools the main topic: how to choose idempotency keys, how to make deduplication atomic, when to lock and when to compare-and-swap, and why a Redis lock alone can't protect your money.
If this was useful
Pass it on to someone who's building or fixing a payment system, or share it with your network. The handbook is free, and people passing it on is how it reaches the engineers it was written for.