Skip to content

Double-Entry Ledger System Design for Payments and Wallets

Design a ledger for a wallet or payments product: debit and credit rules, journal entries, a Postgres schema, idempotent posting, holds, hot accounts and reconciliation.

· Founder & developer

Published

Architecture diagram: a wallet API, a top-up service, a settlement job reading PSP and bank files, and a payout service post to one ledger service on Postgres, which feeds an event queue.

The first version of most wallets is a balance column and a statement like UPDATE wallets SET balance = balance - 2550. It works until a retry runs the update twice, two transfers both pass the balance check before either one writes, or support asks why a customer has $74.50 and nobody can answer, because every update overwrote the history.

The ledger design in this post fixes all three. Every movement of money is a transaction whose entries sum to zero, entries are never edited, and balances are derived from them. This post designs one for a payments or wallet product: accounting rules, journal entries, a Postgres schema, idempotent posting, holds, hot accounts and reconciliation, with a diagram you can copy.

Why a balance column is not enough

Balance column Double-entry ledger
History Overwritten on every update Every change is an immutable entry
A retried request Can apply twice Collapses onto one idempotency key
Where the money went Only one side is recorded Every debit has a matching credit
Fixing a mistake Edit the number Post a reversing transaction
System-wide check None All entries sum to zero per currency

Stripe describes its internal Ledger as an immutable, auditable log built on double-entry bookkeeping that processes five billion events per day. Square built Books, an append-only double-entry database, when its original settlement service stopped scaling and could not keep payouts consistent.

Double-entry rules for engineers

  1. Every transaction has at least two entries, and they balance: total debits equal total credits, in each currency.
  2. Entries are append-only. A mistake is fixed by a new transaction that reverses it, never by an update.
  3. Balances are derived from entries. A cached balance is fine if it changes in the same database transaction.
  4. Amounts are integers in minor units: cents for USD, whole yen for JPY, fils (three decimals) for KWD. Never floats. TigerBeetle calls the number of decimal places (2 for USD, 0 for JPY, 3 for KWD) the asset scale.
  5. Each account holds one currency. An exchange is two balanced legs through an FX account.

Debit and credit are directions, and which one increases an account depends on its type. The examples use a wallet platform that takes card payments through a payment service provider (PSP):

Account type Normal balance Wallet platform example
Asset Debit Cash at bank, PSP receivable
Liability Credit Wallet: Alice, Payouts in transit
Revenue Credit Fee revenue
Expense Debit Card processing fees

A customer's balance is a liability of the platform, money it owes the customer, so a top-up credits the wallet and a withdrawal debits it. Many engineering ledgers, Square's Books among them, store one signed amount per entry, debits positive and credits negative, so the rule becomes "the entries of a transaction sum to zero".

Four money movements as journal entries

Alice tops up, the PSP settles, Alice pays Bob, and Bob withdraws. Amounts are in cents; the $3.00 processing fee is illustrative.

# Event Debit Credit Cents
1 Alice tops up $100 by card PSP receivable Wallet: Alice 10,000
2 The PSP settles the next day, minus a fee Cash at bank 9,700 and Card processing fees 300 PSP receivable 10,000
3 Alice sends Bob $25, with a $0.50 fee Wallet: Alice Wallet: Bob 2,500 and Fee revenue 50 2,550
4a The bank accepts Bob's $20 payout Wallet: Bob Payouts in transit 2,000
4b The payout appears on the bank statement Payouts in transit Cash at bank 2,000

Afterwards Alice has 7,450, Bob has 500, and the bank holds 7,700: the 7,950 owed to customers minus the 250 by which fees paid exceed fees earned. PSP receivable and Payouts in transit are clearing accounts: money passes through them, so a non-zero balance at steady state means something is stuck. The fee in row 3 is part of the transfer's transaction, so Alice can never pay it without Bob receiving the money.

The ledger data model

Three tables are enough to start: accounts, transactions that carry the idempotency key and a request fingerprint, and append-only entries.

CREATE TABLE accounts (
  id             bigint  PRIMARY KEY,
  code           text    NOT NULL UNIQUE,   -- 'wallet:alice', 'cash:bank-1'
  currency       char(3) NOT NULL,          -- ISO 4217
  normal_side    text    NOT NULL CHECK (normal_side IN ('debit', 'credit')),
  balance        bigint  NOT NULL DEFAULT 0 -- cached sum of entries
);

CREATE TABLE transactions (
  id              bigint      PRIMARY KEY,
  idempotency_key text        NOT NULL UNIQUE,
  request_hash    bytea       NOT NULL,     -- fingerprint of the request
  kind            text        NOT NULL,     -- 'topup', 'p2p', 'payout', 'reversal'
  reverses_id     bigint      REFERENCES transactions (id),
  effective_at    timestamptz NOT NULL
);

CREATE TABLE entries (
  id             bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  transaction_id bigint NOT NULL REFERENCES transactions (id),
  account_id     bigint NOT NULL REFERENCES accounts (id),
  amount         bigint NOT NULL CHECK (amount <> 0)  -- debit > 0, credit < 0
);

A CHECK constraint cannot span rows, but a Postgres constraint trigger declared DEFERRABLE INITIALLY DEFERRED runs at commit and can raise an exception when the entries do not sum to zero per currency. Revoke UPDATE and DELETE on entries from the application role. The cached balance is debit-positive: a wallet holding 7,450 stores -7,450, and the API flips the sign for display.

Posting a transaction: idempotent and atomic

One ledger service owns this path. A P2P transfer with a fee:

BEGIN;

INSERT INTO transactions (id, idempotency_key, request_hash, kind, effective_at)
VALUES ($1, 'p2p:7f3c9a', $hash, 'p2p', now())
ON CONFLICT (idempotency_key) DO NOTHING;
-- 0 rows: a retry. Compare request_hash; return the stored transaction or reject.

SELECT id, balance FROM accounts
WHERE id IN ($alice, $bob, $fees)
ORDER BY id
FOR UPDATE;
-- Reject if Alice's balance + 2550 > 0: her wallet would go below zero.

INSERT INTO entries (transaction_id, account_id, amount) VALUES
  ($1, $alice,  2550),
  ($1, $bob,   -2500),
  ($1, $fees,    -50);

UPDATE accounts SET balance = balance + 2550 WHERE id = $alice;
UPDATE accounts SET balance = balance - 2500 WHERE id = $bob;
UPDATE accounts SET balance = balance - 50   WHERE id = $fees;

COMMIT;  -- the deferred trigger checks the sum here

Idempotency makes retries safe:

  • API callers send a key. Stripe's idempotency keys are up to 255 characters, and an IETF Idempotency-Key header draft proposes a standard header for them. The idempotency key diagram walks through the full request flow.
  • Events reuse an upstream ID: the PSP's payment ID for a top-up, the payout ID, the statement line ID. Webhooks and files arrive more than once; webhook delivery is at least once by design.
  • Same key, different payload is an error. Stripe compares the parameters and fails the request; the IETF draft suggests 422.
  • Keep ledger keys forever. An API may forget keys after a day; a ledger must never post twice, however late the duplicate.

Tell other services through an outbox row written in the same transaction, as in the transactional outbox pattern. A process that spans the ledger and other services is a saga with compensating transactions, not two-phase commit.

Holds: pending, posted and available balances

Payouts and card authorizations reserve money before it moves. Two common designs:

  • Pending amounts on the account. TigerBeetle accounts keep debits_pending, debits_posted, credits_pending and credits_posted. A two-phase transfer reserves the amount, then is posted (fully or partly), voided, or expires after a timeout. Pending amounts count toward balance limits, and a transfer resolves only once.
  • A hold account. Debit Wallet: Bob and credit Holds: Bob to reserve, and reverse it to release. This is plain double entry, with more entries.
Balance Credit-normal wallet Used for
Posted credits_posted − debits_posted Statements and accounting
Pending debits_pending Payouts and card holds in flight
Available posted − pending What the user can spend

With holds, the posting check uses the available balance, not the posted one. When Bob withdraws $20 of his $25, a pending transfer to Payouts in transit reserves 2,000 and his available balance drops to 500. If the bank accepts, the transfer is posted (row 4a); if not, it is voided and 2,500 is available again. Give every hold an expiry.

Hot accounts and concurrency

Every transfer credits Fee revenue and every top-up debits PSP receivable. If posting locks every account, they all wait on one row.

  • Lock only accounts with a limit. Wallets need the lock and the check. Fee revenue has no lower bound, so at volume, append its entries without locking a cached balance and roll it up later.
  • Split hot accounts into sub-accounts such as fee_revenue:00 to fee_revenue:15, pick one by hashing the transaction ID, and sum them for reports.
  • Lock in a consistent order. The Postgres documentation names this the best defense against deadlocks; ORDER BY id FOR UPDATE does it.
  • Or use SERIALIZABLE. At the serializable level, Postgres aborts a transaction that could not run in any serial order, so the service retries on serialization failures.
  • Keep a posting on one shard, for example by sharding on tenant; see the database sharding diagram.

Reconciliation, corrections and audits

  • Trial balance: all entries sum to zero per currency. A nightly non-zero result means something wrote around the posting path.
  • Cache check: each cached balance equals the sum of its entries.
  • Clearing accounts return to zero. Stripe's Ledger tracks how much of it is zeroed out at steady state; a stuck clearing balance points to a missing, late or wrong event.
  • External matching: match PSP reports and bank statement lines to transactions by reference.
  • Corrections are reversals: mirror the wrong transaction with reverses_id set, then post the right one. Square's Books works the same way, leaving a permanent audit trail.
  • Closed periods: after month end, post late adjustments into the next period instead of back-dating effective_at.

A ledger is close to event sourcing: entries are the events and balances a projection, as in the CQRS and event sourcing diagram.

The double-entry ledger diagram

Architecture diagram: a wallet API, a top-up service, a settlement job reading PSP and bank files, and a payout service post to one ledger service on Postgres, which feeds an event queue.

15 components · 13 connections

Open in Archboard
Diagram contents
  • Wallet users
  • Payment provider (PSP)
  • Partner bank
  • Wallet API
  • Top-up service
  • Settlement and recon, daily
  • Payout service
  • Ledger service
  • Ledger DB: accounts, transactions, entries, outbox
  • ledger.posted events
  • Statements and notifications
  • Finance reporting
  • send money
  • post P2P + fee, Idempotency-Key
  • webhook
  • post top-up, key = payment ID
  • settlement report
  • statement
  • post settlement, key = statement line ID
  • payout
  • pending, then post or void; key = payout ID
  • append entries
  • outbox relay
  • consume
  • load
One ledger service: transfers, top-ups, payouts and daily settlement post balanced transactions through it into Postgres, and an outbox feeds statements and reporting.

How to read it:

  • Left column: wallet users, the payment provider and the partner bank.
  • Second column: the four writers. Purple is a P2P transfer, green a card top-up, blue a payout (pending, then post or void), and amber the daily settlement and reconciliation job.
  • Ledger service and DB: the only writer of entries; one posting is one database transaction, keyed by an idempotency key or upstream ID.
  • Bottom right: an outbox relay publishes ledger.posted events for statements, notifications and finance reporting.
  • Note on the right: the journal entries from this post and the checks that must hold.

Drawing ledger diagrams clearly

  • Show a single writer. If two services write entries, make that visible as a risk.
  • Color by money flow, not by team: top-up, transfer, payout, settlement.
  • Label the keys on each posting edge.
  • Separate online and batch: solid for API calls, dashed for files, jobs and events.
  • Put the journal entries on the diagram in a note.

Common mistakes are a balance field on the user service; flows with no credit side; services that approve payments from a stale copy of the balance, such as a read replica or a cache outside the ledger database; and no path for bank statements. For the card side, see the payment gateway integration diagram; for refund and settlement flows that finance and support can read, see payment flow diagrams.

Build it in Archboard

  1. Sign in with Google or GitHub and create a diagram.
  2. Add a Person from the C4 Model pack for wallet users, and two C4 Model External System nodes for the payment provider and the partner bank.
  3. From the Cloud pack, add an API Gateway for the wallet API, two Compute nodes for the top-up and payout services, and a Function for the settlement and reconciliation job.
  4. Add another Compute node for the ledger service and a Postgres node from the Data pack for the ledger database.
  5. Add a Cloud Queue for ledger.posted events, a Compute node for statements and notifications, and a Data Warehouse from the Data pack for finance reporting.
  6. Connect the outside parties to the writers, the four writers to the ledger service, the ledger service to the database, and the database through the queue to the consumers; label the edges and dash the file, batch and event edges.
  7. Add a Markdown block from the Core pack with the journal entries, and two Core Text notes for the posting rule and the legend.

If you sketch flows in Mermaid first, the Mermaid converter turns a flowchart into an editable first draft. The example uses 13 diagram nodes; the Free plan allows 15 per diagram.

FAQ

What is a double-entry ledger in software? A database of accounts and transactions in which the entries of every transaction sum to zero, so each debit has a matching credit. Entries are immutable, and balances are derived from them.

Should I store balances or compute them from entries? Either works. Computing is always correct but slows as history grows; a cached balance must change in the same database transaction as the entries.

How do I handle refunds and mistakes? Never edit entries. A refund is a new transaction; a mistake gets a reversal that mirrors the original, followed by the correct transaction.

Do I need a specialized ledger database? Not to start: Postgres with the schema above serves many products. Purpose-built ledgers such as TigerBeetle help when hot accounts make row locks the bottleneck.

Start free — one seat, no credit card.

Related posts

← Back to blog

Open a canvas in a minute

Sign in with Google or GitHub. Free for a single seat. Upgrade when the team joins.