Home›Design›Payments and ledgers
Design doc · Payments and ledgers

Payments and ledgers

Where should money movements live, and how do I make sure no cent appears or disappears?

Applications like this: wallets, payment processors, billing systems, loyalty points. This page is written the way I write a database design doc: the workload first, then where each kind of data goes and why, then how it grows, what breaks, and what I rejected.

The short answerA relational database with a double-entry ledger that is append-only, with idempotency keys and synchronous replication. Correctness first, speed second.
1 · The workload

What the application asks of the database

DimensionThis application
WritesSteady. Every movement is a write, never an update in place.
ReadsBalances, statements, reconciliation jobs.
Read to writeClose to 1 to 1 on the ledger.
ConsistencyStrict. A committed movement must survive any single failure, and the books must always balance.
LatencyTens to hundreds of milliseconds is fine. Correctness matters more.
GrowthForever. Ledgers are kept for years, often by law.
Connected

Real failures behind this design

These incidents are why the choices below matter. Each one is written up with its numbers and sources.

2 · What goes where

Each kind of data, its store, and why

ApplicationAccounts and ledger entriesPostgreSQL or MySQL, with synchronous replicationSOURCE OF TRUTHIdempotency keysThe same database, in the same transactionSOURCE OF TRUTHStatements and reconciliationA replica or a column storeCOPYRaw provider callbacksObject storage, plus a table that points to themSOURCE OF TRUTH

Solid arrows: the application writes there. Dashed arrows: a copy fed from the source of truth (change data capture, an outbox, or a cache fill), which can be rebuilt from it.

DataWhere it goesWhy
Accounts and ledger entriesPostgreSQL or MySQL, with synchronous replicationTransactions, constraints, and a commit that waits for a standby, so a failover cannot lose an acknowledged payment. On MySQL, semi-sync waits only up to its timeout and then falls back to async, so watch Rpl_semi_sync_source_status, and use Group Replication when the ledger cannot lose an acknowledged payment. See what a commit waits for.
Idempotency keysThe same database, in the same transactionA retried request must find the key that the first attempt wrote, or the money moves twice.
Statements and reconciliationA replica or a column storeLong scans that must not slow down new payments.
Raw provider callbacksObject storage, plus a table that points to themLarge, rarely read, kept for audit.

How each family of store behaves under traffic: Database families.

3 · Data model

The core tables and the queries they serve

CREATE TABLE idempotency_keys (
  key        text PRIMARY KEY,
  created_at timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE ledger_entries (
  id              bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  idempotency_key text NOT NULL REFERENCES idempotency_keys,
  account         text NOT NULL,
  amount_cents    bigint NOT NULL
);
-- every transfer writes two rows that sum to zero, in one transaction

-- a balance is a sum, or a row updated in the same transaction
SELECT sum(amount_cents) FROM ledger_entries WHERE account = $1;
Try it · real PostgreSQL in your browser

Run it: the charge that runs twice

The client sends a charge, times out, and sends it again. The idempotency key and the ledger entries go in one transaction, so the retry changes nothing.

  1. Charge 49.99, with a key
    BEGIN;
    WITH k AS (
      INSERT INTO idempotency_keys (key) VALUES ('order-981')
      ON CONFLICT (key) DO NOTHING
      RETURNING key
    )
    INSERT INTO ledger_entries (idempotency_key, account, amount_cents)
    SELECT k.key, v.account, v.amount
    FROM k, (VALUES ('customer:42', -4999), ('merchant:7', 4999)) AS v(account, amount)
    RETURNING account, amount_cents;
    COMMIT;
  2. The client retries
    BEGIN;
    WITH k AS (
      INSERT INTO idempotency_keys (key) VALUES ('order-981')
      ON CONFLICT (key) DO NOTHING
      RETURNING key
    )
    INSERT INTO ledger_entries (idempotency_key, account, amount_cents)
    SELECT k.key, v.account, v.amount
    FROM k, (VALUES ('customer:42', -4999), ('merchant:7', 4999)) AS v(account, amount)
    RETURNING account, amount_cents;
    COMMIT;
  3. Balances are a sum
    SELECT account, sum(amount_cents) AS balance_cents
    FROM ledger_entries GROUP BY account ORDER BY account;
    
    SELECT sum(amount_cents) AS must_be_zero FROM ledger_entries;
4 · How it grows

Start simple, change one thing at a time

  1. One primary, one synchronous standbysynchronous_commit with a standby, or semi-synchronous replication in MySQL, which falls back to async after its timeout, so alert on Rpl_semi_sync_source_status. Backups with point-in-time recovery, and a restore tested on a schedule.
  2. Volume growsPartition the ledger by month. Old partitions move to cheaper storage but stay queryable.
  3. Very high volumeShard by account. Transfers between shards need a two-step protocol with a pending state, which is the hardest part of the design and the reason to delay this step.

Scale it: watch this design grow

Pick a stage, then throw something at it. The numbers are a model to show the shape of each change, not a measurement; the measured numbers are in the lab notebooks.

5 · What breaks first

The failures to plan for

What happensWhat you seeWhat I do
A retry without an idempotency keyDuplicate charges in reconciliationMake the key mandatory in the API, and unique in the database.
Async replication and a failoverPayments acknowledged, then missing on the new primaryUse synchronous replication for this database, and accept the latency.
A hot account, such as the platform fee accountLock waits on one balance rowSpread it over several sub-accounts and sum them, or derive the balance from entries.
6 · Alternatives

What I considered and did not pick

Cost. The synchronous standby is not optional here, so budget for it. Save money on the history instead: partition by month and move old partitions to cheaper storage.

How this page was writtenFrom the engines' documentation and common practice. Measured on real servers: a retried payment stopped by its idempotency key, in the notebooks. Before you build: check the anti-patterns, size it with the capacity calculator, and write your own version from the design doc template. Want a second opinion? Submit it for review.
7 · Where to run it

On-prem, managed, EC2 or Kubernetes

StageWhere it runs
Where I would startManaged relational with synchronous standby (RDS Multi-AZ or equivalent)
When it growsThe same, plus cross-region copies. Self-managed only with a team that rehearses failover

For a team without a dedicated database team. Who does which job in each option, and the full-cost comparison: Where to run the database.

8 · Estimate it

The numbers, worked live

The back-of-the-envelope numbers I would want before choosing anything. Move the assumptions to match your application. The link keeps your numbers, so a colleague sees the same ones.

Part 3 of 4 · Design · 24 pagesAll pages

Which database does my application need? What kind of application data goes in which database, and why, as design docs, plus the anti-patterns and the decisions behind them.