Accounting for DevelopersModule 1: Concepts for engineersIntermediate3 min read
Building a Double-Entry Accounting Engine in Code
How to implement double-entry accounting in software: modelling postings, enforcing balanced entries, handling money safely, idempotency, and deriving balances.
Course outline (16 lessons)
Before this lesson:Why Software Developers Need Accounting KnowledgeDouble-Entry Accounting
In this lesson · 9 sections
This lesson builds the core of a small double-entry engine. The code is TypeScript, but the ideas apply in any language. It is the same logic the Accounting Playground runs in your browser.
4 invariants every double-entry ledger engine must enforce
- 1
Zero-sum per currency
Every journal entry's postings must sum to exactly 0 within each ISO 4217 currency—never net USD against EUR.
- 2
Exact integer minor units
Store amounts as signed integer minor units (bigint cents or pence) paired with a currency, never binary floats.
- 3
Atomic & idempotent writes
Insert the entry header and all postings inside one database transaction guarded by a unique idempotency key.
- 4
Immutable append-only history
Never UPDATE or DELETE posted entries; correct mistakes by posting a new linked reversing entry.
1. Represent money safely
Never use binary floating-point for money: 0.1 + 0.2 !== 0.3. Store integer minor units (cents, pence) with an explicit currency.
type Currency = "USD" | "EUR" | "GBP";
interface Money {
amountMinor: bigint; // 1050n = $10.50
currency: Currency;
}
Note that minor units vary: most currencies use 2 decimal places, some use 0 (such as JPY) and a few use 3. Look the exponent up from a currency table (ISO 4217) rather than assuming 100.
2. Model postings with a sign convention
A common convention: debits are positive, credits are negative. Then an entry balances when its postings sum to zero, and an account’s raw balance is just the sum of its postings.
interface Posting {
accountId: string;
amountMinor: bigint; // debit > 0, credit < 0
currency: Currency;
}
interface JournalEntry {
id: string;
idempotencyKey: string;
effectiveDate: string; // accounting date, e.g. "2026-03-31"
description: string;
postings: Posting[];
}
An alternative is two non-negative columns, debit and credit. Both work; pick one and use it everywhere.
3. Enforce the invariant at the boundary
Validate every entry before it is stored. Reject anything that does not balance.
class LedgerError extends Error {}
function validateEntry(entry: JournalEntry, accounts: Map<string, Account>): void {
if (entry.postings.length < 2) throw new LedgerError("An entry needs at least two postings");
const totals = new Map<Currency, bigint>();
for (const p of entry.postings) {
const account = accounts.get(p.accountId);
if (!account) throw new LedgerError(`Unknown account ${p.accountId}`);
if (!account.active) throw new LedgerError(`Account ${account.code} is closed`);
if (account.currency !== p.currency) throw new LedgerError("Currency mismatch");
if (p.amountMinor === 0n) throw new LedgerError("Zero-amount posting");
totals.set(p.currency, (totals.get(p.currency) ?? 0n) + p.amountMinor);
}
// Balance per currency: never net USD against EUR.
for (const [currency, sum] of totals) {
if (sum !== 0n) throw new LedgerError(`Entry does not balance in ${currency}: ${sum}`);
}
}
Enforce it in the database too. A deferred constraint or a check in the same transaction that inserts postings prevents another code path from bypassing the rule.
4. Post atomically and idempotently
Insert the entry and all its postings in one database transaction. Either all lines exist or none do.
External events, such as payment webhooks, are often delivered more than once. Store an idempotency key with a unique constraint and treat a duplicate as success without posting again.
async function post(entry: JournalEntry): Promise<void> {
validateEntry(entry, await loadAccounts(entry));
await db.transaction(async (tx) => {
const inserted = await tx.insertEntryIfNew(entry); // ON CONFLICT (idempotency_key) DO NOTHING
if (!inserted) return; // already posted
await tx.insertPostings(entry.id, entry.postings);
});
}
5. Derive balances
A balance is the sum of postings for an account, optionally up to a date:
SELECT account_id, SUM(amount_minor) AS balance_minor
FROM postings
JOIN journal_entries e ON e.id = postings.entry_id
WHERE e.effective_date <= :as_of
GROUP BY account_id;
For display, flip the sign for credit-normal accounts (liabilities, equity, revenue) so they show as positive.
At scale, maintain cached balances updated in the same transaction as the postings, and periodically verify them against the sum of postings. The postings remain the source of truth.
6. Never edit, always reverse
Posted entries are immutable. Corrections are new entries. This is covered in reversals and audit trails.
A worked example: a marketplace sale
Customer pays $100; the platform keeps a 10% fee
| Account | Amount (minor units) |
|---|---|
| Cash at payment provider (asset) | +10000 |
| Payable to seller (liability) | −9000 |
| Platform fee revenue (revenue) | −1000 |
| Sum | 0 |
When the seller is paid out, a second entry debits Payable to seller +9000 and credits Cash −9000.
Testing the engine
- Property test: for any generated valid entry, postings sum to zero and the trial balance stays balanced.
- Reject unbalanced, empty, zero-amount, wrong-currency and closed-account entries.
- Replaying the same idempotency key posts once.
- Cached balances equal summed postings.
Recap
- Use integer minor units and per-currency balancing.
- Validate every entry: at least two postings, valid accounts, sum to zero.
- Post atomically and idempotently.
- Derive balances from postings; cache only with verification.
- Never edit posted entries.
Try it yourself
Active recall
Quick check · Test yourself
Work out each answer in your head first, then reveal the explanation and mark whether you got it right.
1Why use signed integer minor units (for example, cents) rather than floating-point numbers?
Show worked answer
Floating-point cannot represent most decimal fractions exactly, so sums drift. Integers in minor units add exactly.
2A payment webhook is delivered twice. How should the engine avoid posting it twice?
Show worked answer
Use an idempotency key, such as the payment provider's event ID, with a unique constraint, so the second attempt is detected and ignored.
Frequently asked questions
Why store signed integer minor units instead of FLOAT or DOUBLE for ledger amounts?
Binary floating-point types cannot represent base-10 fractions like 0.10 or 0.20 exactly, causing penny rounding drift that breaks zero-sum checks. Signed integers in minor units (such as bigint cents) guarantee exact arithmetic and clean equality checks.
Why shouldn't an accounting system just update a mutable balance column on each account?
Updating a balance in place destroys the audit trail, makes point-in-time historical reporting impossible, and lets bugs silently corrupt money without any balancing counterpart. Storing immutable postings and deriving (or verifying) balances guarantees every cent has an explainable origin.
How does a double-entry engine handle multi-currency transactions if every currency must sum to zero?
Route currency conversions through dedicated FX clearing (or trading) accounts—one in each currency. In USD, cash goes out and the USD FX clearing account balances it to zero; in EUR, the EUR FX clearing account goes out and EUR cash balances it to zero, keeping each currency independently balanced.
Key terms in this lesson
Lesson 2 of 16 · Accounting for Developers
Finished this lesson?
Mark it complete to track your progress through the course. Progress is saved in this browser only.
Previous lesson: Why Software Developers Need Accounting Knowledge
Connected lessons
Sources & authoritative references
- IFRS Accounting Standards — IFRS Foundation
- FASB Accounting Standards Codification — Financial Accounting Standards Board
Educational content only—not accounting, tax, legal or investment advice. See our editorial policy or report an error via our corrections policy.