Most products start tracking money with a balance column and an UPDATE. It works until a provider redelivers a webhook, a refund lands before its payment, or someone fixes a figure by hand at month end. Then the number is wrong, and nothing records how it became wrong.
A double-entry ledger replaces that column with invariants: every journal balances, nothing is edited, every write happens once per source event, and every balance can be recomputed from its postings. We enforce them in the database, because it is the one layer every writer passes through: the API, the import job, the outbox relay and the engineer with a SQL console. Application checks still matter, but their job is good error messages, not the last line of defence.
Below: the schema, a deferred constraint trigger that checks balance at commit, an idempotent posting function, concurrency choices, webhooks into the ledger, and reconciliation that names every difference. It is grounded in Ledger & Reconciliation, our prototype for merchants paid through QRIS, bank virtual accounts and e-wallets. It runs on synthetic data and has not met a real bank or provider file, so we flag what is still untested.
The model: accounts, journals and postings
An account is a pot of money with a type: asset, liability, equity, revenue or expense. A journal is one business event, such as a capture or a settlement. A posting is one line of a journal: an account and a signed amount. With debits positive and credits negative, the oldest rule in bookkeeping becomes arithmetic: a journal balances when its postings sum to zero.
Our prototype has an 18-account chart in whole rupiah, with a clearing account per provider and a fee account per channel. A capture debits the provider's clearing account and credits sales. A settlement batch empties clearing, as in this illustrative QRIS batch where the provider deducted Rp 500 above the contracted fee (made-up values):
| Account | Posting (Rp) | Why |
|---|---|---|
| 1110 Cash in transit | 1,489,000 | Net payout the bank will credit |
| 5101 QRIS fee | 10,500 | Fee at the contracted rate |
| 1160 Fee variance | 500 | Charged above contract, waiting for a decision |
| 1121 QRIS clearing | -1,500,000 | Gross of the captured payments |
The sum is zero, and the variance is a balance someone must explain, not a rounding error hidden in the fee line.
Five invariants worth refusing writes for
- Each journal balances, per currency. At least two postings, summing to zero in every currency they touch. A journal that nets IDR against USD is not balanced; conversion needs its own postings
- Postings are immutable. No update, delete or truncate. A mistake is corrected by a reversal journal that mirrors the original, and a journal can be reversed once
- Amounts are integers in a declared scale. No floats, ever, and an explicit decision about how many decimals each currency carries
- Each source event writes once. The idempotency key comes from the event (a provider transaction, an exception resolution), not from a random value generated at write time
- Balances are derived. A balance is the sum of postings. If you cache it, the cache is checked against that sum
The Rupiah decision deserves its own sentence. The ISO 4217 list gives IDR two minor units; our prototype decides on zero. It stores whole rupiah in bigint columns, and its statement parser accepts 1.250.000,00 but refuses 1.250,50 as a fractional rupiah instead of rounding it. Writing the scale down per currency means a provider that starts sending sen fails loudly at import, not quietly at month end. A check constraint also bounds every amount to Number.MAX_SAFE_INTEGER (9,007,199,254,740,991), because the TypeScript layer reads amounts as JavaScript numbers.
Enforcing them in PostgreSQL
The schema below follows the prototype's migrations, with one addition: the prototype is Rupiah only, so we added a currency per account and posting to show the general case. The composite foreign key stops a posting from using a currency its account does not hold.
create table currencies (
code char(3) primary key check (code ~ '^[A-Z]{3}$'),
scale smallint not null check (scale between 0 and 3) -- decimals we store, our decision
);
create table accounts (
code text primary key,
name text not null,
type text not null check (type in ('asset', 'liability', 'equity', 'revenue', 'expense')),
currency char(3) not null references currencies (code),
unique (code, currency)
);
create table journals (
id bigint generated always as identity primary key,
kind text not null,
idempotency_key text not null,
request_hash text not null,
effective_at timestamptz not null,
recorded_at timestamptz not null default now(),
reverses_journal_id bigint references journals (id),
source_type text,
source_id text,
constraint journals_idempotency_key_unique unique (idempotency_key),
constraint journals_reversed_once unique (reverses_journal_id)
);
create table postings (
id bigint generated always as identity primary key,
journal_id bigint not null references journals (id),
line_no integer not null check (line_no > 0),
account_code text not null,
currency char(3) not null,
amount bigint not null check (amount <> 0), -- debit positive, credit negative
unique (journal_id, line_no),
foreign key (account_code, currency) references accounts (code, currency)
);
A CHECK constraint sees one row, so it cannot express "the postings of this journal sum to zero". A per-statement check fails too, because the journal row is inserted before its postings. PostgreSQL's answer is a constraint trigger declared DEFERRABLE INITIALLY DEFERRED: it is queued as rows arrive and fires when the transaction commits. Constraint triggers must be AFTER ROW triggers, so we attach one to each table.
create function check_journal(target bigint) returns void language plpgsql as $$
declare
line_count integer;
off_currency char(3);
begin
select count(*) into line_count from postings where journal_id = target;
if line_count < 2 then
raise exception 'journal % has % postings', target, line_count using errcode = 'LR001';
end if;
select currency into off_currency from postings where journal_id = target
group by currency having sum(amount) <> 0 limit 1;
if found then
raise exception 'journal % does not balance in %', target, off_currency using errcode = 'LR001';
end if;
end $$;
create function journal_inserted() returns trigger language plpgsql as $$
begin perform check_journal(NEW.id); return null; end $$;
create function posting_inserted() returns trigger language plpgsql as $$
begin perform check_journal(NEW.journal_id); return null; end $$;
create constraint trigger journals_balanced after insert on journals
deferrable initially deferred for each row execute function journal_inserted();
create constraint trigger postings_balanced after insert on postings
deferrable initially deferred for each row execute function posting_inserted();
create function refuse_change() returns trigger language plpgsql as $$
begin
raise exception '% on % refused: the ledger is append-only', TG_OP, TG_TABLE_NAME
using errcode = 'LR002';
end $$;
create trigger journals_append_only before update or delete on journals
for each row execute function refuse_change();
create trigger postings_append_only before update or delete on postings
for each row execute function refuse_change();
create trigger journals_no_truncate before truncate on journals
for each statement execute function refuse_change();
create trigger postings_no_truncate before truncate on postings
for each statement execute function refuse_change();
The journal trigger catches a journal with no postings; the posting trigger catches a later insert that would unbalance an existing journal. The prototype also checks reversals: one must mirror its original line for line (compared with EXCEPT ALL), a reversal of a reversal is refused, and each failure has its own SQLSTATE so the application can map it to a precise error.
On PGlite (PostgreSQL 18.6 compiled to WebAssembly, the prototype's engine) this schema refused an unbalanced journal, a single-line journal, IDR netted against USD, a posting in the wrong currency, an unbalanced posting added to a committed journal, and every update, delete and truncate.
Three failure modes to know before relying on it:
- Cost grows with journal size. Each posting queues a check that reads the whole journal, so N lines cost roughly N squared row reads at commit: nothing for 2 to 6 lines, about a million for a 1,000-line batch. Split large batches into several journals
- Triggers are not a security boundary. A table owner can disable them, and
session_replication_role = replicaskips ordinary triggers and foreign key checks. Run the application as a role that owns nothing, revokeUPDATE,DELETEandTRUNCATE, and treat the triggers as the second wall SET CONSTRAINTS ALL IMMEDIATEfails closed. It only moves the check earlier, so a multi-statement posting fails at the journal insert
Posting with an idempotency key
The posting function hashes the request, returns the stored journal if the key exists with the same hash, refuses the key if the hash differs, and otherwise inserts. Stripe's API applies the same comparison to its idempotency keys, and the difference matters: a retry must replay, but a bug that reuses a key for a different payment must fail.
import { createHash } from "node:crypto";
type Line = { account: string; currency: string; amount: number };
export type Draft = {
idempotencyKey: string; kind: string; effectiveAt: string;
source: { type: string; id: string }; lines: Line[];
};
type Db = { query<R>(text: string, params?: unknown[]): Promise<{ rows: R[] }> };
type Posted = { journalId: number; replayed: boolean };
async function replay(db: Db, key: string, hash: string): Promise<Posted | null> {
const { rows: [row] } = await db.query<{ id: number; request_hash: string }>(
"select id, request_hash from journals where idempotency_key = $1", [key]);
if (!row) return null;
if (row.request_hash !== hash) throw new Error(`idempotency conflict: ${key}`);
return { journalId: Number(row.id), replayed: true };
}
export async function postJournal(db: Db, d: Draft): Promise<Posted> {
if (d.lines.some((l) => !Number.isSafeInteger(l.amount) || l.amount === 0)) {
throw new Error("amounts must be non-zero safe integers in minor units");
}
const hash = createHash("sha256").update(JSON.stringify([d.kind, d.effectiveAt, d.source.type,
d.source.id, d.lines.map((l) => [l.account, l.currency, l.amount])])).digest("hex");
const earlier = await replay(db, d.idempotencyKey, hash);
if (earlier) return earlier;
try {
// One statement is one transaction: the deferred balance triggers run as it commits
const { rows: [row] } = await db.query<{ journal_id: number }>(
`with j as (
insert into journals (kind, idempotency_key, request_hash, effective_at, source_type, source_id)
values ($1, $2, $3, $4, $5, $6) returning id)
insert into postings (journal_id, line_no, account_code, currency, amount)
select j.id, l.n, l.a, l.c, l.m from j,
unnest($7::text[], $8::text[], $9::bigint[]) with ordinality as l(a, c, m, n)
returning journal_id`,
[d.kind, d.idempotencyKey, hash, d.effectiveAt, d.source.type, d.source.id,
d.lines.map((l) => l.account), d.lines.map((l) => l.currency), d.lines.map((l) => l.amount)]);
return { journalId: Number(row?.journal_id), replayed: false };
} catch (err) {
const e = err as { code?: string; constraint?: string };
const lostRace = e.code === "23505" && e.constraint === "journals_idempotency_key_unique";
const winner = lostRace ? await replay(db, d.idempotencyKey, hash) : null;
if (winner) return winner;
throw err;
}
}
The lookup before the insert is only an optimisation. The unique constraint arbitrates: when two callers race past the lookup, the second insert waits for the first transaction, fails with 23505 on the named constraint, and replays the winner. We tested this against PostgreSQL 17 with node-postgres: 20 concurrent calls with one key produced one journal; with the lookup forced to miss for all 20, one insert won and 19 replayed; three concurrent calls sharing a key with different bodies produced one journal and two conflicts.
Writing the journal and its postings as one statement lets it run on a pooled connection in autocommit mode. Inside a larger transaction, wrap it in a savepoint, because a unique violation aborts the surrounding transaction and the replay query would fail. The prototype does the same in TypeScript with Drizzle inside an explicit transaction, and derives keys from the source: capture:<provider>:<transaction> for captures, exception:<id>:resolve for resolutions. Unlike an API idempotency cache, these keys are never pruned: they link a journal back to its cause.
Concurrency: what actually contends
Appending journals barely contends. Each transaction inserts its own rows, and the balance check is safe under the default Read Committed level: a committing transaction sees committed postings plus its own, so it can only pass if what it added nets to zero.
Contention starts when a rule reads a balance before writing, such as a customer wallet that must not go negative, or a cached balance row updated on every posting. The options:
| Approach | Guarantees | Cost |
|---|---|---|
| Derive balances on read | Nothing to keep in sync | Reads grow with history; add snapshots later |
| Cached row updated in the posting transaction | Cache matches postings at every commit | Every writer to that account queues on one row lock |
SELECT ... FOR UPDATE on account rows, in sorted order |
Balance checks see no concurrent writer | Blocking; unsorted locking deadlocks |
SERIALIZABLE |
No anomaly from any interleaving | Retry every transaction that fails with 40001 |
Clearing accounts are the trap: every QRIS capture touches the same one. As simple arithmetic, a cached row locked for 2 ms per posting caps that account near 500 postings per second, whatever the hardware. Our prototype derives every balance and runs a single PGlite connection, so it has not met this problem and has had no load or concurrency testing. Where one account needs a strict single writer, routing its writes through one owner also works, as in single-writer bookings on Durable Objects.
Verified webhooks feeding the ledger
Payments enter the prototype through signed webhooks from three simulated providers, each with its own HMAC scheme. The raw body is verified before parsing, in constant time, within a 300-second timestamp tolerance by default. A rejected delivery is logged by the SHA-256 hash of its body, never the body. Accepted events land in an inbox unique per provider and event id, so a redelivery only increments a counter.
A state machine reaches the same end state in any delivery order: a refund that arrives before its payment is parked, and money for an already paid order goes to customer deposits as an exception. The payment change, its event and an outbox message commit together, and the relay posts the journal with a key derived from the provider transaction. A relay that crashes after posting but before acknowledging still yields one journal; the prototype's outbox test checks exactly that.
Reconciliation: every difference gets a name
A merchant sees each rupiah three times: as a webhook, a settlement report line and a bank credit, often batched, net of fees and a day later. Reconciliation is done not when the match rate is high, but when every remaining difference has a cause and a journal.
Imports are checked first: opening balance plus lines must equal closing, statements must continue from the previous closing, and a repeated file is refused by its SHA-256. The matching engine works in tiers (reference, provider cut-off window, fuzzy amount and date, bounded subset-sum), and every proposal carries reasons and a confidence. Only proposals at 950 per mille or above confirm themselves; the rest wait for a person. A partial unique index keeps a statement line in at most one active match. Whatever remains becomes an exception whose resolution posts an adjusting journal:
| Difference | How it shows up | What the prototype posts |
|---|---|---|
| Timing | Batch follows the provider's cut-off, or the credit is late beyond grace days | Matched by window, or a late exception claimed from the provider (1150) |
| Fees | Payout net of the fee; a charge above contract | Fee at contract plus fee variance (1160); a short payout accepted as fee |
| Partial payment | A virtual account paid in parts | Intent stays partially paid; each capture posts its own journal |
| Duplicate | Same bank credit twice, or an order paid twice | Duplicate exception; excess held in customer deposits (2101), refunded via 2102 |
| Unknown credit | Nothing explains a bank line | Unidentified receipts suspense (2190) until someone does |
The same rule works for totals. A control bridge walks from one side's total to the other through named causes (missing items, duplicates, fees, rounding) and must end at zero unexplained; a residue that cannot be named is itself the finding.
Audit trail: two clocks and no erasers
Every journal carries two times: effective_at, when it counts, and recorded_at, when the system learned it. That answers the auditor's real question, "what did the ledger say on the 5th, as you knew it on the 5th?" These are the queries we would schedule alongside it:
-- 1. The whole ledger nets to zero in every currency (expect no rows)
select currency, sum(amount) as residue
from postings group by currency having sum(amount) <> 0;
-- 2. Balances at an instant, as the ledger knew them at another instant
select p.account_code, p.currency, sum(p.amount) as balance
from postings p join journals j on j.id = p.journal_id
where j.effective_at <= $1 and j.recorded_at <= $2
group by p.account_code, p.currency;
-- 3. A cached balance that drifted from its postings (expect no rows)
select b.account_code, b.balance as cached, coalesce(d.total, 0) as derived
from account_balances b
left join (select account_code, sum(amount) as total from postings group by account_code) d
using (account_code)
where b.balance <> coalesce(d.total, 0);
The third query only means something if the cache is written in the same transaction as its postings, so one snapshot sees both. Never drive an incremental cache from a "last journal id" watermark: identity values are assigned at insert, not commit, so a lower id can commit later.
The rest of the trail comes from refusing to forget. A reversal records its reason and points at its original; journals point at their source (a payment capture, an import, an exception) and keep the hash of the request that created them. Migrations are checksummed, and the prototype refuses to start if an applied migration's text has changed. Its property tests check that reversing any subset of journals restores every balance and that posting the same request twice changes nothing. One honest limit: reversals from the journal explorer post at the current time, so back-dated corrections are not offered yet.
FAQ
Why not store amounts as NUMERIC?
numeric is exact, so it is a valid choice, especially for unit prices with more decimals than the currency. We prefer bigint in declared minor units because the scale becomes an explicit decision per currency, and no layer can carry a fraction the business never agreed to.
Can the ledger share a database with the rest of the app?
Yes, and for a product team it usually should: the outbox, the payment state and the journal then commit together. Separate the database roles instead of the servers, so only the ledger's code path holds write grants on its tables.
Checklist
- Store debits positive and credits negative, and check each journal sums to zero per currency at commit
- Make postings append-only with triggers and revoked grants; correct by reversal only
- Declare a scale per currency, use
bigint, and refuse fractions at import rather than rounding them - Derive idempotency keys from the source event and compare a request hash on replay
- Let the unique constraint settle races, and test the losing path under real concurrency
- Derive balances; if you cache them, update the cache in the posting transaction and check it for drift
- Give every reconciliation difference a cause, an owner and an adjusting journal
- Keep effective and recorded time on every journal so past reports can be reproduced
Primary references
- Patterns for Accounting: accounts, entries and transactions, and reversal versus replacement adjustments
- PostgreSQL: CREATE TRIGGER: constraint triggers, deferral and the
AFTER ROWrestriction - PostgreSQL: Transaction Isolation: Read Committed behaviour, serialisation failures and retries
- Stripe: Idempotent requests: replaying a key and refusing changed parameters
- ISO 4217 currency list, published by SIX as maintenance agency: minor units per currency, including IDR
Related reading
- API Webhook Reliability: Handle Retries Without Duplicates
- ERP vs Custom System: What Growing Companies Should Know
See how these invariants run end to end in our Ledger & Reconciliation case study, or explore our business systems work.
