Double-Entry Ledger Design
- Apply the debit/credit rules for asset, liability, equity, revenue and expense accounts to real transactions.
- Design a ledger schema (accounts, journal entries, postings) with enforceable invariants.
- Choose between computed, materialized and running balances, and between row locking and append-plus-async for concurrency.
- Make posting idempotent and safe under retries, and model reversals without deleting anything.
- Handle multi-currency entries and FX through position accounts.
TL;DR
- Every money movement is a journal entry made of two or more postings. Postings in an entry sum to zero per currency. This is the invariant that makes money impossible to create or destroy by accident.
- The ledger is append-only. You never
UPDATEorDELETEa posting. Mistakes are fixed by a reversal entry plus a new correct entry. - A balance is a derived value: the sum of an account's postings. You may materialize it (a balance column updated in the same transaction) for fast overdraft checks, and you can always recompute it to verify.
- Idempotency is enforced by a unique key on the journal entry, written in the same DB transaction as the postings.
- Concurrency: lock the balance rows in a consistent order when you must check funds, and use append + async aggregation (or sub-account sharding) for hot accounts that don't need checks.
- Multi-currency: an entry balances per currency. FX goes through FX position accounts, never through a single posting that changes currency.
- Auditability comes from the design itself: who, when, why, which request, and what it reverses are all stored with each entry.
Why it matters
A ledger is the most correctness-critical component in a bank, a wallet, a payment service provider, or an e-commerce platform that holds seller balances. Interviewers use "design a ledger" or "design a wallet" to see whether you think about money as movements between accounts rather than as a mutable number. Their follow-ups go after concurrency (two transfers from the same account), retries (the client times out and resubmits), corrections (a fee was charged twice), and audit (show the balance as of last Tuesday). A double-entry, append-only design answers all of these structurally instead of with ad-hoc code.
For e-commerce marketplaces the same design tracks what the platform owes sellers: order captured, commission deducted, shipping fee subsidized, refund clawed back, payout sent. If you skip double-entry here, you end up with a "seller balance" that nobody can explain at month-end.
Core concepts
Double-entry rules
Each account has a type, and the type decides which side increases it (its normal balance):
| Account type | Increases with | Decreases with | Bank example | Marketplace example |
|---|---|---|---|---|
| Asset | Debit | Credit | Loans to customers, cash at central bank, nostro | Cash at bank, receivable from PSP |
| Liability | Credit | Debit | Customer deposits | Payable to sellers, customer wallet balances |
| Equity | Credit | Debit | Share capital, retained earnings | Retained earnings |
| Revenue | Credit | Debit | Fee income, interest income | Commission income |
| Expense | Debit | Credit | Interest expense | Payment processing fees, shipping subsidies |
The accounting equation Assets = Liabilities + Equity (+ Revenue − Expenses) always holds if every entry has equal debits and credits.
Example: transfer with fee. An sends 500,000 VND to Binh at the same bank and pays a 5,000 VND fee.
| Account | Type | Debit | Credit |
|---|---|---|---|
| An — CASA | Liability | 505,000 | |
| Binh — CASA | Liability | 500,000 | |
| Fee income — transfers | Revenue | 5,000 | |
| Total | 505,000 | 505,000 |
The bank owes An less (debit to a liability), owes Binh more (credit to a liability), and earned 5,000 (credit to revenue).
Example: marketplace order. A buyer pays 1,000,000 VND by card. The platform takes 10% commission, and the PSP charges 2% (20,000).
| Account | Debit | Credit |
|---|---|---|
| Receivable from PSP (asset) | 980,000 | |
| PSP fees (expense) | 20,000 | |
| Payable to seller (liability) | 900,000 | |
| Commission income (revenue) | 100,000 |
When the PSP settles, debit Cash at bank, credit Receivable from PSP. When the platform pays the seller, debit Payable to seller, credit Cash at bank. Each step stays balanced, and anyone can trace the flow.
Data model
Three core tables plus optional balance snapshots:
Sign convention. Store each posting as a signed integer in minor units: debit = positive, credit = negative. An entry is balanced when SUM(amount) = 0 per currency. For display, a liability or revenue account shows -balance so that a customer with a positive deposit sees a positive number. Some teams instead store amount unsigned plus a direction column. Either works, as long as the convention is enforced in one place.
CREATE TABLE accounts (
id BIGINT PRIMARY KEY,
code TEXT NOT NULL UNIQUE, -- e.g. 'cust:1001:casa:VND'
type TEXT NOT NULL CHECK (type IN ('asset','liability','equity','revenue','expense')),
currency CHAR(3) NOT NULL,
allow_negative BOOLEAN NOT NULL DEFAULT false, -- in normal-balance terms
balance BIGINT NOT NULL DEFAULT 0, -- materialized, debit-positive
version BIGINT NOT NULL DEFAULT 0,
status TEXT NOT NULL DEFAULT 'active',
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE journal_entries (
id BIGINT PRIMARY KEY,
idempotency_key TEXT NOT NULL UNIQUE,
kind TEXT NOT NULL, -- transfer, fee, refund, reversal...
reverses_id BIGINT UNIQUE REFERENCES journal_entries(id),
value_date DATE NOT NULL,
posted_at TIMESTAMPTZ NOT NULL DEFAULT now(),
created_by TEXT NOT NULL, -- service or user id
request_id TEXT, -- trace / correlation id
description TEXT,
metadata JSONB NOT NULL DEFAULT '{}'
);
CREATE TABLE postings (
id BIGINT PRIMARY KEY,
entry_id BIGINT NOT NULL REFERENCES journal_entries(id),
account_id BIGINT NOT NULL REFERENCES accounts(id),
amount BIGINT NOT NULL CHECK (amount <> 0), -- debit +, credit -
currency CHAR(3) NOT NULL,
balance_after BIGINT, -- running balance (optional)
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX postings_account_idx ON postings (account_id, id);
CREATE INDEX postings_entry_idx ON postings (entry_id);
Notes on the schema:
reverses_idisUNIQUE, so an entry can be reversed at most once.BIGINTminor units avoid floating-point errors. For currencies with 2 or 3 decimals, store cents or mills, and keep anexponentper currency. See Schema Patterns: Money, Audit, Multi-tenancy.- Large ledgers partition
postingsby time or by account hash (see Partitioning & Sharding in Practice). An entry's postings should live in the same database so the entry commits atomically.
Enforcing the invariants in the database
Don't rely only on application code. Postgres can check the zero-sum rule at commit with a deferred constraint trigger:
CREATE FUNCTION check_entry_balanced() RETURNS trigger AS $$
BEGIN
IF EXISTS (
SELECT 1 FROM postings
WHERE entry_id = NEW.entry_id
GROUP BY currency
HAVING SUM(amount) <> 0
) THEN
RAISE EXCEPTION 'journal entry % is unbalanced', NEW.entry_id;
END IF;
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
CREATE CONSTRAINT TRIGGER postings_balanced
AFTER INSERT ON postings
DEFERRABLE INITIALLY DEFERRED
FOR EACH ROW EXECUTE FUNCTION check_entry_balanced();
-- Append-only: the application role can only insert.
REVOKE UPDATE, DELETE ON postings, journal_entries FROM ledger_app;
Other invariants worth checking continuously, for example with a nightly job and alerts:
- For every account:
accounts.balance = SUM(postings.amount). - For every currency:
SUM(accounts.balance) = 0across the whole ledger (the trial balance). - No posting to a closed account. Posting currency equals account currency.
balance_afterforms an unbroken sequence per account.
Balances: computed, materialized, running
| Approach | How | Good for | Cost |
|---|---|---|---|
| Computed | SUM(amount) over postings at read time | Small ledgers, audit queries, verification | Slow for accounts with millions of postings |
| Materialized | accounts.balance updated in the same transaction as the posting | Overdraft checks, fast reads | Write contention on that row |
| Running balance | postings.balance_after stored on each posting | Statements, point-in-time balance, chain verification | Requires serialized writes per account |
| Snapshots + delta | Daily balance_snapshots plus sum of postings since | Historical "as of" queries at scale | Snapshot job, careful with back-valued entries |
A common production combination: a materialized balance for checks, balance_after for statements, daily snapshots for reporting, and a nightly recomputation that proves they all agree.
Idempotent posting
Clients retry. Networks drop responses. Message consumers redeliver. The posting API therefore takes a caller-supplied idempotency key (for example the transfer id from the payment service), and the ledger:
- Opens a transaction.
- Inserts the journal entry. The
UNIQUE (idempotency_key)constraint rejects duplicates. - On a unique violation it rolls back, loads the existing entry and returns it, after checking that the request payload matches (same accounts and amounts). A mismatch means a client bug, so it returns an error instead of the old result.
- Otherwise it inserts the postings, updates balances and commits.
Because the key and the postings commit together, there is no window where the money has moved but the key wasn't recorded. See Idempotency & Exactly-Once.
Concurrency
Two transfers out of the same account at the same moment must not both pass an overdraft check against the same old balance.
Option 1: pessimistic row lock (SELECT … FOR UPDATE). Simple and correct under READ COMMITTED. Lock all accounts in an entry in ascending id order to avoid deadlocks when A→B and B→A run concurrently. Throughput on a single account is limited by lock hold time: with roughly 1–5 ms per transaction, that's a few hundred to about a thousand postings per second per account (rough, depends heavily on hardware and transaction size).
Option 2: conditional update. For a credit-normal customer account (stored negative under the debit-positive convention), debit it with UPDATE accounts SET balance = balance + $1 WHERE id = $2 AND balance + $1 <= 0. The check and the write happen in one statement under the row lock the UPDATE takes, so you skip a separate read round-trip. RowsAffected = 0 means insufficient funds.
Option 3: append + async aggregation for hot accounts. Some accounts receive huge volumes but never need a funds check: the bank's fee income account, a big merchant's settlement account, the platform's "receivable from PSP". For these:
- Insert postings without touching the account's balance row.
- A background aggregator (or a materialized view) folds postings into the balance every few seconds.
- Or shard the hot account into N sub-accounts (
fee_income#0..#15), pick one by hash, and report the sum.
The debit side of a customer transfer still needs a synchronous check. Only the credit-only or internal side goes async.
Option 4: single-writer per account. Partition accounts across workers (for example by Kafka partition key = account id). One goroutine owns each account's balance in memory and applies commands sequentially, persisting postings in batches. You get very high throughput at the cost of more complex recovery and rebalancing. This is the approach of some high-volume wallets and exchanges. See Digital Wallet and Stock Exchange.
Reversals, not deletes
A posted entry is a fact. To undo it:
- Post a reversal entry with the same accounts and opposite signs,
reverses_idpointing at the original, and a reason. - If the original was simply wrong (wrong amount), reverse it and post a new correct entry. Statements then show three lines, which is what auditors expect.
- A partial refund is not a reversal. It is a new entry for the refunded amount, linked to the original order or payment in metadata.
Value dating: a reversal usually carries the original entry's value date so interest is corrected. Its posting date is today.
Multi-currency
An entry balances per currency. Converting money needs an FX position account in each currency. Example: a customer converts 100 USD to VND at 25,000 VND/USD (illustrative rate):
| Account | Currency | Amount (debit +) |
|---|---|---|
| Customer USD account | USD | +10,000 (cents) |
| FX position USD | USD | −10,000 |
| FX position VND | VND | +2,500,000 |
| Customer VND account | VND | −2,500,000 |
USD postings sum to 0, and so do VND postings. The FX position accounts now show the bank long USD and short VND. Treasury manages that exposure and revalues it to report FX gains and losses. Store the rate used, its source and its timestamp in the entry's metadata.
Auditability
A ledger is easy to audit if every entry answers these questions:
- Who created it: service identity and, for manual entries, the maker and checker user ids.
- Why: kind, description, and the business object it belongs to (transfer id, order id).
- When: posting timestamp, value date, business date.
- From which request: trace id, so you can jump to logs and traces.
- What it reverses or corrects.
Optional extras: hash-chaining entries (each stores a hash of the previous entry plus its own content) to make tampering detectable, and shipping entries to WORM (write-once) storage for retention.
Trade-offs
| Option | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| Row lock + materialized balance | Simple, strongly consistent checks, easy to reason about | Throughput ceiling per hot account, deadlock risk if lock order is wrong | Customer accounts with modest per-account rates (most banks and wallets) |
| Append-only + async aggregation | Very high write throughput, no hot rows | Balance lags, so it can't be used for funds checks | Credit-only or internal accounts (fee income, settlement, PSP receivable) |
| Sharded sub-accounts | Spreads contention, still synchronous | Reads must sum shards, and debit checks get complex | Hot account that still needs near-real-time balance |
| Single-writer in-memory per account | Very high throughput, deterministic ordering | Complex recovery, rebalancing, and snapshotting | Exchange or wallet at massive scale with an expert team |
| Event-sourced ledger (postings are the events) | Full history, replay, temporal queries | Projections to maintain, schema evolution of events | You already treat postings as the source of truth (you should) |
| Off-the-shelf ledger DB (e.g. TigerBeetle) or ledger SaaS | Purpose-built invariants and performance | New operational dependency, less flexibility in data model | Throughput or correctness needs exceed what the team wants to build |
In practice
A Go posting function using row locks in a deterministic order. The interfaces are database/sql with Postgres placeholders.
package ledger
import (
"context"
"database/sql"
"errors"
"fmt"
"sort"
)
type Posting struct {
AccountID int64
Amount int64 // debit +, credit -
Currency string
}
type Entry struct {
IdempotencyKey string
Kind string
ValueDate string // YYYY-MM-DD business date
CreatedBy string
Postings []Posting
}
var (
ErrUnbalanced = errors.New("entry does not balance")
ErrInsufficientFunds = errors.New("insufficient funds")
ErrDuplicate = errors.New("duplicate idempotency key")
)
func validate(e Entry) error {
sums := map[string]int64{}
for _, p := range e.Postings {
if p.Amount == 0 {
return fmt.Errorf("zero posting on account %d", p.AccountID)
}
sums[p.Currency] += p.Amount
}
for cur, s := range sums {
if s != 0 {
return fmt.Errorf("%w: %s off by %d", ErrUnbalanced, cur, s)
}
}
if len(e.Postings) < 2 {
return ErrUnbalanced
}
return nil
}
// Post writes the entry atomically. newID generates ids (e.g. Snowflake-style).
func Post(ctx context.Context, db *sql.DB, e Entry, newID func() int64) (int64, error) {
if err := validate(e); err != nil {
return 0, err
}
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return 0, err
}
defer tx.Rollback() // no-op after Commit
entryID := newID()
res, err := tx.ExecContext(ctx, `
INSERT INTO journal_entries (id, idempotency_key, kind, value_date, created_by)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (idempotency_key) DO NOTHING`,
entryID, e.IdempotencyKey, e.Kind, e.ValueDate, e.CreatedBy)
if err != nil {
return 0, err
}
if n, _ := res.RowsAffected(); n == 0 {
return 0, ErrDuplicate // caller loads and returns the existing entry
}
// Lock accounts in ascending id order to avoid deadlocks.
ps := append([]Posting(nil), e.Postings...)
sort.Slice(ps, func(i, j int) bool { return ps[i].AccountID < ps[j].AccountID })
for _, p := range ps {
var balance int64
var allowNegative bool
var typ, currency string
err := tx.QueryRowContext(ctx, `
SELECT balance, allow_negative, type, currency
FROM accounts WHERE id = $1 AND status = 'active'
FOR UPDATE`, p.AccountID).Scan(&balance, &allowNegative, &typ, ¤cy)
if err != nil {
return 0, fmt.Errorf("lock account %d: %w", p.AccountID, err)
}
if currency != p.Currency {
return 0, fmt.Errorf("currency mismatch on account %d", p.AccountID)
}
next := balance + p.Amount
if !allowNegative && goesNegative(typ, next) {
return 0, ErrInsufficientFunds
}
if _, err := tx.ExecContext(ctx, `
UPDATE accounts SET balance = $1, version = version + 1 WHERE id = $2`,
next, p.AccountID); err != nil {
return 0, err
}
if _, err := tx.ExecContext(ctx, `
INSERT INTO postings (id, entry_id, account_id, amount, currency, balance_after)
VALUES ($1, $2, $3, $4, $5, $6)`,
newID(), entryID, p.AccountID, p.Amount, p.Currency, next); err != nil {
return 0, err
}
}
return entryID, tx.Commit()
}
// Debit-normal accounts (asset, expense) go negative below zero.
// Credit-normal accounts (liability, equity, revenue) go "negative" above zero.
func goesNegative(accountType string, balance int64) bool {
switch accountType {
case "asset", "expense":
return balance < 0
default:
return balance > 0
}
}
Practical knobs and observations:
- Isolation:
READ COMMITTEDplus explicitFOR UPDATEis enough here.SERIALIZABLEalso works but turns contention into retryable serialization failures. See Transactions & Isolation Levels. - Publishing events: write an outbox row in the same transaction ("entry posted") so downstream services (notifications, read models, reconciliation) get every entry exactly once in effect. See Transactional Outbox & CDC.
- IDs: time-ordered ids (Snowflake, ULID, UUIDv7) keep
postingsinserts index-friendly. See Unique ID Generation. - Holds usually live in a separate table, and available balance = ledger balance minus active holds (see Core Banking Concepts).
Common pitfalls
- Single-entry "balance += amount" designs. Symptom: money appears or disappears with no counter-entry, and nobody can explain the difference at month-end.
- Floats for money. Symptom:
0.1 + 0.2errors accumulate into rounding breaks in reconciliation. - Updating or deleting postings to fix mistakes. Symptom: statements change after the customer already saw them, and auditors find history that can't be explained.
- Idempotency key stored in a different transaction (or in Redis only). Symptom: rare double postings after crashes or timeouts.
- Locking accounts in request order. Symptom: deadlocks under load whenever A→B and B→A transfers overlap.
- Synchronous balance update on a hot internal account. Symptom: p99 latency climbs on every payment because they all queue on the fee-income row lock.
- One posting changing currency. Symptom: the trial balance per currency stops summing to zero, and FX exposure is invisible.
- No continuous invariant checks. Symptom: a bug that skipped a posting is found weeks later by finance instead of minutes later by an alert.
Interview angle
- Typical prompts: "Design a ledger for a digital wallet", "How do you guarantee a transfer never creates money?", "Two requests debit the same account at the same time — what happens?", "How do you fix a wrong entry?"
- A strong answer includes double-entry with a zero-sum invariant, an append-only journal, a materialized balance plus verification, an idempotency key in the same transaction, deterministic lock ordering, a hot-account strategy, reversal entries, per-currency balancing with FX accounts, and an outbox for downstream events.
- Follow-ups: How do you show the balance as of a past date? How do you scale beyond one database (shard by account, and how to handle cross-shard transfers with a saga plus a clearing/suspense account; see Distributed Transactions: 2PC, TCC, Saga)? How do you migrate an existing single-entry system?
- Red flags: storing balance only, using floats, deleting rows, "we'll use a distributed lock in Redis" as the only guard on a balance, or not knowing which side increases a liability.
Self-check
1. Write the postings (signed, debit positive) for a 2,000,000 VND card refund to a customer on a marketplace where the seller had been credited 1,800,000 and the platform kept 200,000 commission.
Assuming the platform claws back from the seller and returns its commission:
- Payable to seller (liability): +1,800,000 (debit, the platform owes the seller less)
- Commission income (revenue): +200,000 (debit, reverses income)
- Receivable from/payable to PSP or cash: −2,000,000 (credit, money flows out to the buyer through the PSP)
Sum = 0. Whether commission is refunded is a business rule. If it isn't, the seller absorbs the full 2,000,000 or the platform records an expense.
2. Why should the idempotency key be in the same database transaction as the postings?
If the key is stored separately, a crash between the two writes leaves either postings without a key, so a retry posts again, or a key without postings, so a retry is wrongly treated as done. Writing both in one ACID transaction makes "money moved" and "request recorded" a single atomic fact.
3. Your fee-income account is a hot spot: every transfer credits it. How do you fix this without weakening correctness?
Fee income never needs a funds check, so stop updating its balance row synchronously. Either append postings only and aggregate the balance asynchronously, or shard it into N sub-accounts chosen by hash and sum them for reporting. The customer debit side keeps its synchronous lock. The zero-sum invariant still holds because postings are still written atomically within each entry.
4. How do you answer "what was account X's balance at 2026-03-31 23:59:59"?
Take the latest balance snapshot at or before that time and add postings after the snapshot up to the timestamp, or read balance_after of the last posting before the timestamp. Decide whether the question means posting time or value date, because back-valued entries make those differ. Banks often need both.
5. Why must a multi-currency entry balance per currency rather than in total?
You can't add VND and USD without picking a rate, and the rate changes. Balancing per currency means each currency's ledger is closed on its own, and FX conversions show up explicitly in FX position accounts. That makes exposure visible and lets treasury revalue it.
6. Scenario: a support agent wants a button to "fix" a wrongly charged fee. What do you build?
A correction workflow, not an edit. The agent (maker) requests a reversal of the fee entry with a reason. A second person (checker) approves it, required above some threshold or always for manual entries. The system posts a reversal entry with reverses_id set and both user ids recorded, notifies the customer, and the original entry stays visible in the history.
7. What continuous checks would you run against a production ledger?
- Every journal entry sums to zero per currency.
- Materialized balance equals the sum of postings, per account.
- Trial balance sums to zero per currency across the ledger.
balance_aftersequences are unbroken.- No postings on closed accounts.
- Ledger totals match external sources through reconciliation.
Exercise
Build a minimal ledger in Go + Postgres:
- Create the schema above, including the deferred zero-sum trigger and
REVOKE UPDATE, DELETE. - Implement
Post(as above),Reverse(entryID, reason)andBalanceAt(accountID, ts). - Write a test that fires 1,000 concurrent 1,000 VND transfers from an account holding 500,000 VND to random accounts. Assert exactly 500 succeed, the final balance is 0, and the trial balance is 0.
- Write a test that sends the same idempotency key 10 times concurrently and asserts exactly one entry exists.
- Run
EXPLAIN ANALYZEonBalanceAtfor an account with 1 million postings, then add a snapshot table and compare.
Done when: all tests pass under go test -race, an unbalanced insert fails at commit, and you can explain the timing difference in step 5.
Further reading
- Martin Fowler, Analysis Patterns, chapters on accounting (Account, Entry, Posting Rules).
- Martin Kleppmann, "Accounting for Computer Scientists" (blog post).
- Modern Treasury, "Accounting for Developers" series.
- Alex Xu & Sahn Lam, System Design Interview Vol. 2, chapters on payment system and digital wallet.
- TigerBeetle documentation — a purpose-built double-entry database, useful for its explanations of debit/credit and invariants.
- Martin Kleppmann, Designing Data-Intensive Applications, chapters on transactions and stream processing.
Related
- Core Banking Concepts — balances, holds and value dating that sit on top of the ledger.
- Reconciliation & Settlement — proving the ledger matches the outside world.
- Locking & Concurrency Control — row locks, optimistic concurrency and deadlocks in detail.
- Idempotency & Exactly-Once — patterns for safe retries.
- Digital Wallet — a high-throughput ledger case study.
- Event-Driven Architecture, CQRS & Event Sourcing — the ledger as an event log.
- Blockchain & Distributed Ledgers for Architects — when a ledger shared across organisations makes sense, and when it does not.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).