nemr.app

FinanceEngineering

Double-Entry Ledgers for Developers: Model Money Without Losing Any

· 5 min read · by Elias Nemr

Why money bugs are data-model bugs, and how double-entry ledgers, integer amounts, idempotency keys and reconciliation keep payment systems correct.

If you've ever stored a customer's balance in a column called balance and updated it with balance = balance + 10, you've built the thing every payments engineer eventually regrets. It works until two requests race, a job retries, a refund arrives late, or finance asks "why is this number wrong?" — and you can't answer, because the history was overwritten.

The fix is five hundred years old: double-entry bookkeeping. Here's how to apply it in code, and the handful of related habits that keep money systems correct.

Balances are derived, not stored

The central idea: don't store balances as the source of truth. Store an append-only record of every movement of money and compute balances from it. A balance column can exist as a cache, but if it ever disagrees with the entries, the entries win.

Entries are never edited or deleted. If something was wrong, you post a new entry that reverses it. That gives you a complete audit trail for free, and it makes "what was the balance at 3 pm last Tuesday?" a query instead of an archaeology project.

Every transaction balances to zero

In double-entry, money never appears or disappears; it moves from one account to another. Each transaction consists of two or more entries, and the debits must equal the credits. A customer paying you $100 with a 3% card fee might look like:

AccountDebitCredit
Cash at payment processor97.00
Processing fees (expense)3.00
Customer revenue100.00

That invariant — the entries of every transaction sum to zero — is a gift. It's a check you can enforce in the database and assert in tests, and it catches a whole class of bugs the moment they happen rather than at month-end.

CREATE TABLE accounts (
  id        BIGSERIAL PRIMARY KEY,
  name      TEXT NOT NULL,
  currency  CHAR(3) NOT NULL
);

CREATE TABLE transactions (
  id              BIGSERIAL PRIMARY KEY,
  idempotency_key TEXT NOT NULL UNIQUE,
  description     TEXT,
  posted_at       TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE entries (
  id             BIGSERIAL PRIMARY KEY,
  transaction_id BIGINT NOT NULL REFERENCES transactions(id),
  account_id     BIGINT NOT NULL REFERENCES accounts(id),
  amount         BIGINT NOT NULL  -- signed, in minor units; debits +, credits −
);

-- Invariant: every transaction sums to zero (check on commit or in application code)
SELECT transaction_id FROM entries GROUP BY transaction_id HAVING SUM(amount) <> 0;

Use integers, in minor units

Never store money as a floating-point number. 0.1 + 0.2 is not 0.3 in binary floating point, and the errors compound. Store integer minor units (cents, pence, fils) alongside a currency code. Two gotchas:

  • Currencies have different exponents. USD has 2 decimal places, JPY has 0, and some currencies (like the Kuwaiti dinar) have 3. Look the exponent up from a currency table rather than assuming 100.
  • Never add or compare across currencies without an explicit, recorded exchange rate. Make the type system stop you: a money value is an (amount, currency) pair, not a bare number.

Rounding is a business decision, not a coding accident. When you split $100.00 three ways, someone gets the extra cent — decide who, write it down, and test it.

Make every write idempotent

Networks fail, clients retry, queues redeliver. If "charge the customer" runs twice, the customer pays twice. The standard defence is an idempotency key: the caller sends a unique key with each logical operation, and the server records it with a unique constraint. A retry with the same key returns the original result instead of creating a second transaction (note the UNIQUE column in the schema above).

Wrap each posting in a database transaction

All entries of a transaction must commit together or not at all. Use your database's ACID transaction to insert the transaction row and all its entries atomically, and lock or version the accounts you're checking against. If you enforce "balance must not go below zero", make sure two concurrent debits can't both pass the check — use SELECT … FOR UPDATE on the account row or a serialisable transaction.

Model pending money explicitly

Card payments and bank transfers aren't instant. A card authorisation is a promise, not money. Represent that with distinct states or accounts — for example, funds pending, available and held — and move money between them as events arrive. Collapsing "pending" into "settled" is how you end up showing customers money that later vanishes.

Corrections are new entries

Refunds, chargebacks and mistakes are posted as new transactions that reverse or adjust the originals, linked to them by reference. Keep two timestamps where it matters: when the thing happened in the real world (event time) and when you recorded it (posting time). Reports for a closed month shouldn't silently change because a late correction arrived.

Reconcile against the outside world

Your ledger is your belief about where the money is. Your bank, card processor and payment partners hold their own belief. Reconciliation is the routine job that compares the two, flags differences, and routes them to a human. Run it daily, and treat unexplained breaks as incidents. A ledger that's never reconciled is a story, not a record.

Publish events reliably

Other systems (emails, analytics, notifications) need to know when money moved. Writing to your database and then publishing to a queue as two separate steps will eventually leave them out of sync. The transactional outbox pattern fixes it: write the event to an outbox table in the same database transaction as the ledger entries, and have a separate process publish from that table with at-least-once delivery. Consumers dedupe by event id.

Test the invariants, not just the examples

  • Property-based tests: generate random sequences of operations and assert that every transaction sums to zero and no account violates its rules.
  • Concurrency tests: fire many simultaneous requests at the same account and check the final balance.
  • Replay tests: rebuild all balances from the entries and compare with the cached ones.
  • Idempotency tests: send every write twice and assert nothing changes the second time.

The short version

  • Append-only entries; balances are derived.
  • Every transaction sums to zero.
  • Integer minor units plus an explicit currency; never floats.
  • Idempotency keys on every write; atomic database transactions.
  • Explicit pending/held states; corrections are new entries.
  • Daily reconciliation against the outside world.
  • Outbox for events; invariant-based tests.

Money software is unforgiving precisely because the numbers are easy to check and people do check them. Model it the way accountants have for centuries, and most of the scary bugs become impossible by construction.

Elias Nemr is a software engineer who has built and shipped products across Blockchain, Finance, E-Commerce, AI, Energy and Indie Games. More about him →

Found this useful? Buy me a coffee

Keep reading