Double-Entry Ledger Design
Last Updated: 2026-12-01 Status: Complete
A double-entry ledger design records every movement of money as a journal entry whose lines sum to zero, so money can never appear or vanish without a visible counterpart. After this page you can define a PayFac chart of accounts, write the journal entries for a sale, refund, chargeback, payout and reserve, and build the PostgreSQL schema and NestJS posting service that enforce the rules. The ideas come from double-entry bookkeeping and are decades old; the engineering work is making them hold under concurrency, retries and corrections.
Quick Reference
| Rule | Why |
|---|---|
| Every entry nets to zero per currency | Money is conserved; a bug cannot create money silently |
| Entries and lines are immutable | The ledger is the audit trail |
| Corrections are new reversing entries | History stays intact; both the error and the fix are visible |
| Balances are derived from lines | A stored mutable balance drifts and has no history |
| One external reference per entry, unique | Retries and duplicate events post once |
effective_at is separate from posted_at | Backdated effects stay explainable |
| One account per owner per currency | Never sum across currencies |
Account Types and Normal Balances
A ledger is a set of accounts. Each account has a type, and each type has a normal balance: the side (debit or credit) on which the account usually grows.
| Type | Meaning for a PayFac | Normal balance | Increases with | Decreases with |
|---|---|---|---|---|
| Asset | Things the platform owns or is owed: bank cash, processor receivable | Debit | Debit | Credit |
| Liability | Things the platform owes: money owed to sub-merchants, reserves | Credit | Credit | Debit |
| Equity | Owners' stake, retained earnings | Credit | Credit | Debit |
| Revenue | Fees earned | Credit | Credit | Debit |
| Expense | Costs incurred: interchange, processing, losses | Debit | Debit | Credit |
Debit and credit are only the left and right side of an entry; they do not mean increase or decrease. The identity that always holds is assets = liabilities + equity (revenue and expense roll into equity at period end).
When a processor funds the platform for a sub-merchant's sale, the cash sits in the platform's bank account, but it is not the platform's money. The platform owes it to the sub-merchant, so the ledger records cash as an asset and a matching payable as a liability. Only the fee is revenue. This is also why the sponsor bank agreement controls where the cash is held, often in an FBO or settlement account; see Sponsor Delegation and Financial Requirements.
A PayFac Chart of Accounts
Start small and add accounts only when a question needs them answered. The names below are illustrative; code is the stable identifier your posting rules use.
| Code | Type | Granularity | Purpose |
|---|---|---|---|
cash_fbo | Asset | Per bank account and currency | Cash at the settlement or FBO bank; reconciled to bank statements |
receivable_processor | Asset | Per processor and currency | Funds the processor or acquirer owes the platform; a clearing account |
receivable_merchant | Asset | Per sub-merchant and currency | Negative balances and chargebacks the platform expects to recover |
merchant_payable_pending | Liability | Per sub-merchant and currency | Captured, not yet payable |
merchant_payable_available | Liability | Per sub-merchant and currency | Payable now (see Pending vs Available Balance) |
reserve_payable | Liability | Per sub-merchant and currency | Funds held under a reserve; the merchant's money, restricted |
payout_in_transit | Liability | Per payout rail and currency | Clearing account between payout initiation and bank confirmation |
fee_revenue | Revenue | Per fee type | Platform fees; sub-ledger by fee type for reporting |
processing_cost | Expense | Per cost type | Interchange, network and processor fees |
chargeback_loss | Expense | Per currency | Unrecoverable chargebacks written off |
fx_clearing | Asset | Per currency | Holds the two legs of a currency conversion (see balances) |
fx_spread_revenue | Revenue | Per currency | Spread earned on conversions |
fx_gain_loss | Expense | Per currency | Difference between booked and realized conversion; a credit balance is a net gain |
suspense | Liability | Per source and currency | Unidentified cash awaiting classification |
rounding | Expense | Per currency | Sub-minor-unit differences; a credit balance is a net gain |
Every account gets one of the five types in the schema, which fixes its normal side. Clearing, suspense, rounding and FX accounts can legitimately carry the opposite side (a suspense debit is an unidentified payment); the type is a convention for reporting, not a restriction on the sign.
The sub-merchant payable is one account per sub-merchant per currency. A merchant's balance is then a query on its own accounts, and a sub-ledger total (the sum over all merchants) can be checked against a control total. Platform and customer ownership belong in owner_id; the entity model is in Entity Model.
How Do You Record a $100 Card Sale With a $3 Fee?
Assumptions for this worked example: the platform charges the sub-merchant a $3 fee on a $100 sale, the processor funds net of its own costs, and the processor's cost for this transaction is $2.20 (illustrative: $1.65 interchange, $0.15 network, $0.40 processor). Amounts are in USD. Funding terms vary by contract; see Merchant Funding.
There are four postings, each triggered by a different event, not by the same moment.
Entry 1: capture succeeds. Posts when the processor confirms the capture. Revenue is recognized now because the platform has earned the fee and the merchant is owed the rest.
| Account | Debit | Credit |
|---|---|---|
receivable_processor | 100.00 | |
merchant_payable_pending | 97.00 | |
fee_revenue | 3.00 |
Entry 2: settlement and fee file ingested. Posts when the processor's settlement and fee records arrive (Settlement Files). The processor's costs are known only now, so the expense posts now, against the receivable the processor is netting.
| Account | Debit | Credit |
|---|---|---|
processing_cost | 2.20 | |
receivable_processor | 2.20 |
Entry 3: the platform decides the money is payable. Posts when settlement is confirmed and any hold window ends. This moves the merchant's balance from pending to available; it is a platform decision and need not coincide with cash arrival.
| Account | Debit | Credit |
|---|---|---|
merchant_payable_pending | 97.00 | |
merchant_payable_available | 97.00 |
Entry 4: funding arrives. Posts when the bank credit appears (from the bank statement, matched to the processor's funding record). The receivable now returns to zero: 100.00 − 2.20 = 97.80.
| Account | Debit | Credit |
|---|---|---|
cash_fbo | 97.80 | |
receivable_processor | 97.80 |
A real funding credit covers a whole batch, so post it as one receivable_processor credit line per settled item, each tagged with that item's object_id (or allocate the batch through an allocation table). Otherwise per-payment receivable items can never reach zero and aging cannot work.
Check the result: cash 97.80 covers the 97.00 owed to the merchant and leaves 0.80, which equals fee revenue 3.00 minus processing cost 2.20. If receivable_processor is not zero after Entry 4, something is missing, late or wrong; that is the signal described in Ledger Reconciliation.
The same capture as a JSON entry (signed integer minor units; positive = debit, negative = credit):
{
"external_ref": "capture:pay_01H8X",
"entry_type": "capture",
"effective_at": "2026-12-01T14:03:11Z",
"lines": [
{ "account": "receivable_processor:proc_a:USD", "amount_minor": 10000 },
{ "account": "merchant_payable_pending:mrc_42:USD", "amount_minor": -9700 },
{ "account": "fee_revenue:processing:USD", "amount_minor": -300 }
]
}
Each posting is triggered by a durable event (capture confirmed, file ingested, bank credit seen). If you post cash on capture, the ledger claims money the bank does not have, and reconciliation can no longer tell you when funding is late.
How Do You Record a Refund?
Assume a full $100 refund of a settled sale, with a platform policy of also returning the $3 fee (a policy choice; some platforms keep it). The processor deducts the refund from a future funding. If the receivable has no other open items, it goes negative, and a negative receivable_processor now represents an amount the platform owes the processor, until that funding nets it.
| Account | Debit | Credit |
|---|---|---|
merchant_payable_available | 97.00 | |
fee_revenue | 3.00 | |
receivable_processor | 100.00 |
If the sale had not yet settled, the debit would hit merchant_payable_pending instead. A refund that exceeds the merchant's balance is still posted: the platform owes the cardholder regardless, and the shortfall becomes a negative balance (see Reserves and Negative Balances). Whether processing costs are returned on refunds depends on your processor contract; post the adjustment when the fee file shows it, not when you assume it. Refund mechanics are in Void vs Reversal vs Refund vs OCT.
How Do You Record a Chargeback in a Ledger?
Take a $100 chargeback on a sale whose proceeds were already paid out, so the merchant's available balance is zero. The network and issuer process the dispute through the processor; the platform sees a debit in its funding. Dispute lifecycle and representment are in Chargeback Lifecycle and Representment.
Step 1: chargeback received. The processor will take $100 out of funding, and the merchant is charged.
| Account | Debit | Credit |
|---|---|---|
merchant_payable_available | 100.00 | |
receivable_processor | 100.00 |
The merchant's payable is now −100.00, a negative balance. An optional dispute fee follows the same pattern: debit the payable, credit fee_revenue.
Step 2a: recovery. The platform recovers funds by debiting the merchant's bank account; cash arrives and the payable is restored.
| Account | Debit | Credit |
|---|---|---|
cash_fbo | 100.00 | |
merchant_payable_available | 100.00 |
Recovery from the merchant's own reserve involves no cash: debit reserve_payable, credit merchant_payable_available. Offsetting against future sales needs no separate entry; those sales simply credit the negative payable.
Step 2b: write-off. If recovery is abandoned, move the loss to expense, in a separate entry approved under your policy.
| Account | Debit | Credit |
|---|---|---|
chargeback_loss | 100.00 | |
merchant_payable_available | 100.00 |
If the platform instead pursues collection, reclassify the negative payable to receivable_merchant rather than writing it off, so the asset and its aging are visible.
Step 3: representment win. The issuer reverses the chargeback and the processor re-credits $100. Post a new entry; never edit Step 1.
| Account | Debit | Credit |
|---|---|---|
receivable_processor | 100.00 | |
merchant_payable_available | 100.00 |
If recovery (2a) had already restored the merchant, the win re-credits the merchant as above and the recovered cash is returned per your agreement. If only the write-off (2b) happened, credit chargeback_loss instead of the merchant.
{
"external_ref": "chargeback:dsp_77:received",
"entry_type": "chargeback_debit",
"effective_at": "2026-12-14T00:00:00Z",
"lines": [
{ "account": "merchant_payable_available:mrc_42:USD", "amount_minor": 10000 },
{ "account": "receivable_processor:proc_a:USD", "amount_minor": -10000 }
],
"metadata": { "dispute_id": "dsp_77", "reason_code": "[from dispute record]" }
}
How Do You Record a Payout, a Reserve Hold and a Release?
Payout. Two entries, because the platform's bank confirms later than the platform decides.
| Event | Debit | Credit | Amount |
|---|---|---|---|
Payout created (scheduled) | merchant_payable_available | payout_in_transit | 97.00 |
Payout paid (bank debit confirmed) | payout_in_transit | cash_fbo | 97.00 |
Posting at creation takes the money out of the available balance immediately, so it cannot be paid twice; submitting to the rail later changes no balances. A payout canceled or failed before release is undone with reversing entries. If the bank returns a paid payout (for example an ACH return), post entries that re-credit the merchant's available (or held) balance against cash_fbo and the payout clearing account. A returned payout is not a negative balance; negative balances come from refunds, chargebacks, fees or a returned recovery debit. Payout mechanics are in Payouts.
Reserve. Holding $10.00 moves liability between two of the merchant's accounts; no cash moves.
| Event | Debit | Credit | Amount |
|---|---|---|---|
| Reserve hold | merchant_payable_available | reserve_payable | 10.00 |
| Reserve release | reserve_payable | merchant_payable_available | 10.00 |
Rolling, fixed and capped schedules, release jobs and policy percentages are covered in Reserves and Negative Balances and Reserve Management.
Invariants Your Ledger Must Enforce
- Balanced per currency. The sum of
amount_minorfor each currency in an entry is zero. An entry may span currencies (an FX conversion) only if each currency balances on its own throughfx_clearing. - Immutable. No
UPDATEorDELETEon entries or lines; revoke those privileges (andTRUNCATE, which row triggers do not block) and add a trigger as defense in depth. - Corrections are reversals. To correct posted entry E, post E' with every line negated and
reverses_entry_id = E, then post the correct entry. Both the error and the fix remain visible. If later entries depend on E (a release to available, a payout), do not blindly reverse E's lines: reverse the dependent entries too, in reverse dependency order, or post a delta against the account that holds the money now. See Ledger Reconciliation. - Idempotent by external reference. One entry per unique
external_ref. A repeat with the same content returns the original; a repeat with different content is a client error. See Idempotency. effective_atvsposted_at.effective_atis when the economic event happened (the processor's settlement date);posted_atis when the row was written. Backdated effects (a settlement file arriving two days late) keep their trueeffective_at, so period reports are right and the lateness is itself visible.- Trial balance. The sum of all lines is zero for each currency. A trial balance lists every account's balance and checks that debits equal credits; run it continuously, not only at month end.
Why Are Balances Derived, Not Stored?
A balance column that code updates in place has three problems:
- It drifts. Any code path that updates the entry but not the balance, or the reverse, leaves them inconsistent forever, and nothing says which is right.
- It races. Two concurrent read-modify-write updates lose one of them unless every writer locks correctly.
- It has no history. You cannot answer "what was the balance last Tuesday at noon" or "which entry caused this".
Make the lines the source of truth: balance = sum of lines for the account. For speed, keep a cache: a snapshot row of (account_id, as_of_line_id, balance_minor) or a per-account running version, updated in the same transaction as the lines or built by a background job. Read as snapshot balance plus lines after as_of_line_id. Because the cache can always be rebuilt by summing lines, a cache bug is a performance incident, not a financial one. Hot-account scaling is in Scaling.
PostgreSQL Schema
Signed amounts or debit/credit columns? This schema uses one signed amount_minor bigint per line (positive = debit, negative = credit). Balanced-entry checking is a plain SUM(...) = 0, there is no way to write a line with both sides, and a balance is a SUM. The cost is readability: accountants think in two columns, so expose a view that shows debit_minor and credit_minor for reports. Choose one convention for the entire system and document it; mixing conventions is a source of real bugs.
CREATE TABLE ledger_account (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
code text NOT NULL, -- e.g. merchant_payable_available
owner_id uuid, -- sub-merchant, bank account, etc.
currency char(3) NOT NULL, -- ISO 4217
type text NOT NULL CHECK (type IN
('asset','liability','equity','revenue','expense')),
normal_side text NOT NULL CHECK (normal_side IN ('debit','credit')),
version bigint NOT NULL DEFAULT 0, -- bumped on guarded writes
created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE NULLS NOT DISTINCT (code, owner_id, currency), -- PostgreSQL 15+
UNIQUE (id, currency)
);
CREATE TABLE journal_entry (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
external_ref text NOT NULL UNIQUE, -- idempotent posting key
request_hash text NOT NULL, -- detects reuse with other content
entry_type text NOT NULL,
effective_at timestamptz NOT NULL,
posted_at timestamptz NOT NULL DEFAULT now(),
reverses_entry_id uuid UNIQUE REFERENCES journal_entry(id),
reason text,
ticket_ref text,
metadata jsonb NOT NULL DEFAULT '{}'
);
CREATE TABLE ledger_line (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
entry_id uuid NOT NULL REFERENCES journal_entry(id),
line_no int NOT NULL,
account_id uuid NOT NULL,
currency char(3) NOT NULL,
amount_minor bigint NOT NULL CHECK (amount_minor <> 0),
object_type text, -- business object this line belongs to
object_id text, -- e.g. payment id, payout id, batch item id
FOREIGN KEY (account_id, currency) REFERENCES ledger_account (id, currency),
UNIQUE (entry_id, line_no)
);
CREATE INDEX ON ledger_line (account_id, id);
CREATE INDEX ON ledger_line (account_id, object_id);
-- Reject unbalanced entries at commit time, after all lines are inserted.
CREATE FUNCTION assert_entry_balanced() RETURNS trigger AS $$
BEGIN
IF EXISTS (SELECT 1 FROM ledger_line WHERE entry_id = NEW.entry_id
GROUP BY currency HAVING SUM(amount_minor) <> 0) THEN
RAISE EXCEPTION 'journal entry % is not balanced', NEW.entry_id;
END IF;
RETURN NULL;
END $$ LANGUAGE plpgsql;
CREATE CONSTRAINT TRIGGER ledger_line_balanced
AFTER INSERT ON ledger_line DEFERRABLE INITIALLY DEFERRED
FOR EACH ROW EXECUTE FUNCTION assert_entry_balanced();
-- Immutability as defense in depth (also REVOKE UPDATE, DELETE from the app role).
CREATE FUNCTION forbid_mutation() RETURNS trigger AS $$
BEGIN RAISE EXCEPTION 'ledger rows are immutable'; END $$ LANGUAGE plpgsql;
CREATE TRIGGER journal_entry_immutable BEFORE UPDATE OR DELETE ON journal_entry
FOR EACH ROW EXECUTE FUNCTION forbid_mutation();
CREATE TRIGGER ledger_line_immutable BEFORE UPDATE OR DELETE ON ledger_line
FOR EACH ROW EXECUTE FUNCTION forbid_mutation();
The composite foreign key forces each line's currency to match its account, so a line can never post USD into a EUR account. Two limits of the schema: the deferred trigger fires per inserted line, so an entry with zero lines never triggers it (reject empty entries in the posting service, or add an entry-level check), and row-level triggers do not block TRUNCATE, so REVOKE TRUNCATE from the application role as well. object_type and object_id tag each line with the business object it settles; reconciliation groups on them. Money fields in the payment-side records are in Entity Model.
Concurrency and Overdraft Guards
Two concurrent payouts that each see a 100.00 balance and each take 80.00 overdraw the account. Fix it by making the check and the write atomic:
- Row lock on the guarded account.
SELECT ... FOR UPDATEon the account row, in a stable order (by id) to avoid deadlocks, then compute the balance, check and insert. - Optimistic locking. Read the account
version, compute, and write only if the version is unchanged, otherwise retry. See optimistic locking. - Guard per write, not per account. A processor-initiated chargeback must post even when it drives a balance negative (the money is already gone), while a payout must not. So the guard belongs to the posting rule: pass the list of accounts that must stay non-negative for this entry.
Vendor examples (labeled as vendor behavior): Modern Treasury's ledger lets an entry carry a balance filter that fails the write with a 422 if the resulting balance leaves a range, or a lock_version that rolls back if the account version changed. TigerBeetle offers account flags such as debits_must_not_exceed_credits, which apply to every transfer on that account; with account-level flags, model a separate account for flows that may go negative.
@Injectable()
export class LedgerService {
constructor(private readonly dataSource: DataSource) {}
async post(dto: PostEntryDto): Promise<{ entryId: string; replayed: boolean }> {
if (dto.lines.length < 2) throw new UnprocessableEntityException('entry needs at least two lines');
for (const l of dto.lines) { // @IsInt() allows unsafe integers
if (!Number.isSafeInteger(l.amountMinor) || l.amountMinor === 0) {
throw new UnprocessableEntityException('amountMinor must be a nonzero safe integer');
}
}
// Canonical form: fixed key order, lines sorted by lineNo, so equal content hashes equally.
const canonical = JSON.stringify([
dto.entryType, dto.effectiveAt.toISOString(), dto.reason ?? null, dto.ticketRef ?? null,
[...dto.lines].sort((a, b) => a.lineNo - b.lineNo)
.map((l) => [l.lineNo, l.accountId, l.amountMinor]),
]);
const hash = createHash('sha256').update(canonical).digest('hex');
return this.dataSource.transaction(async (m) => { // assumes default READ COMMITTED
const ins = await m.query(
`INSERT INTO journal_entry (external_ref, request_hash, entry_type, effective_at, reason, ticket_ref)
VALUES ($1,$2,$3,$4,$5,$6) ON CONFLICT (external_ref) DO NOTHING RETURNING id`,
[dto.externalRef, hash, dto.entryType, dto.effectiveAt, dto.reason, dto.ticketRef]);
if (ins.length === 0) { // replay of an earlier post
const [prev] = await m.query(
`SELECT id, request_hash FROM journal_entry WHERE external_ref = $1`, [dto.externalRef]);
if (prev.request_hash !== hash) {
throw new UnprocessableEntityException('external_ref reused with different content');
}
return { entryId: prev.id, replayed: true };
}
const ids = dto.lines.map((l) => l.accountId);
const accounts: Array<{ id: string; currency: string; normal_side: string }> =
await m.query(`SELECT id, currency, normal_side FROM ledger_account WHERE id = ANY($1)`, [ids]);
if (accounts.length !== new Set(ids).size) throw new NotFoundException('unknown account');
const net = new Map<string, bigint>(); // per-currency balance check
for (const l of dto.lines) {
const cur = accounts.find((a) => a.id === l.accountId)!.currency;
net.set(cur, (net.get(cur) ?? 0n) + BigInt(l.amountMinor));
}
if ([...net.values()].some((v) => v !== 0n)) throw new UnprocessableEntityException('unbalanced');
const guarded = [...new Set(dto.mustStayNonNegative ?? [])].sort();
if (guarded.length) { // lock in id order, then check
await m.query(`SELECT id FROM ledger_account WHERE id = ANY($1) ORDER BY id FOR UPDATE`, [guarded]);
for (const id of guarded) {
const acct = accounts.find((a) => a.id === id)!;
const [{ sum }] = await m.query(
`SELECT COALESCE(SUM(amount_minor),0)::text AS sum FROM ledger_line WHERE account_id = $1`, [id]);
const delta = dto.lines.filter((l) => l.accountId === id)
.reduce((s, l) => s + BigInt(l.amountMinor), 0n);
const sign = acct.normal_side === 'credit' ? -1n : 1n;
if (sign * (BigInt(sum) + delta) < 0n) throw new UnprocessableEntityException('insufficient balance');
}
await m.query(`UPDATE ledger_account SET version = version + 1 WHERE id = ANY($1)`, [guarded]);
}
await m.query(
`INSERT INTO ledger_line (entry_id, line_no, account_id, currency, amount_minor)
SELECT $1::uuid, t.n, t.a, acc.currency, t.v
FROM unnest($2::uuid[], $3::bigint[]) WITH ORDINALITY AS t(a, v, n)
JOIN ledger_account acc ON acc.id = t.a`,
[ins[0].id, ids, dto.lines.map((l) => String(l.amountMinor))]);
return { entryId: ins[0].id, replayed: false }; // deferred trigger re-checks balance at commit
});
}
}
PostEntryDto carries externalRef, entryType, effectiveAt, lines (each lineNo, accountId and a signed integer amountMinor, validated with @IsInt() and @ValidateNested, plus the safe-integer check shown, because @IsInt() accepts integers beyond Number.MAX_SAFE_INTEGER; alternatively accept amounts as decimal strings), optional reason, ticketRef and mustStayNonNegative. The line insert in the example omits object_type and object_id; carry them on each line in production.
The lock-then-sum guard and the ON CONFLICT DO NOTHING then SELECT replay branch assume PostgreSQL's default READ COMMITTED. Under REPEATABLE READ or SERIALIZABLE, re-read after the lock in a new statement or retry on serialization failure (SQLSTATE 40001).
Two points to note. The sum in the guard is O(lines); in production read a snapshot plus the lines after it. And a concurrent first post with the same external_ref blocks on the unique index until the other transaction commits, so exactly one wins; the loser then sees the committed row.
Vendor ledger behaviors (Modern Treasury balance guards, TigerBeetle flags) are taken from their current documentation and can change. Check the linked docs before depending on them. Values that change over time are tracked in Key Numbers.
Is a Ledger an Event Log?
Yes: an append-only list of immutable facts from which current state is derived is event sourcing, applied to money. The ledger is the one place where you accept the cost of that model completely, because the balance must be provable. Other domain events (a payout was approved) can be published from the same transaction through an outbox, so consumers learn of postings exactly as they were committed; see Event-Driven Architecture.
Stripe's engineering blog describes its ledger as an immutable, append-only double-entry log with data-quality checks on fund flows, and notes that clearing accounts should be zero at steady state, so a nonzero balance signals a missing, late or incorrect event. Treat that as a design pattern you can copy: route every uncertain flow through a clearing account, and alert on the ones that do not return to zero. That is the subject of Ledger Reconciliation.
Why Is the Complexity Worth It?
- Conservation. A bug that credits one account must debit another, so errors surface as imbalances instead of silently leaking money.
- Explainability. Any balance is the sum of named, dated lines; support, finance and auditors can all trace it.
- Reconciliation. Clearing accounts turn "is anything missing?" into "is this balance zero?".
- Correction without erasure. Reversing entries preserve audit trails.
- Extension. New products (reserves, FX, revenue share) become new accounts and entry types, not new tables.
The cost is real: more writes per business event, discipline about posting rules, and a team that learns accounting vocabulary. Have your finance and accounting leads review the chart of accounts and revenue-recognition choices; this page describes engineering patterns, not accounting advice.
Self-Assessment
- An entry has lines for 100.00 USD debit and 99.00 USD credit. What should the system do? Reject it at write time and, as defense in depth, at commit via the deferred trigger.
- Why is
payout_in_transita separate account? It is a clearing account: it should return to zero when the bank confirms, and an aging balance means a payout was created but never marked paid or reversed.
More scenarios are in the Ledger Quiz.
Related Topics
- Pending vs Available Balance: balance types, holds and multi-currency
- Ledger Reconciliation: clearing accounts, suspense and corrections
- Entity Model: the records that trigger postings
- Idempotency: safe retries for posting
- Reserves and Negative Balances: reserve mechanics and recovery
- Check your understanding: Ledger Quiz
References
- Ledger: Stripe's system for tracking and validating money movement — Stripe engineering blog, Ilya Ganelin, 2024
- Ledger accounts overview — Modern Treasury documentation (vendor)
- Lock on account balance or version — Modern Treasury documentation (vendor)
- Account reference — TigerBeetle documentation (vendor)
- Event Sourcing — Martin Fowler, 2005
- CREATE TRIGGER — PostgreSQL documentation (constraint triggers, deferrable)