Build a Fault-Tolerant Money Transfer Ledger at Scale
System DesignModel answerLast updated
Design a distributed ledger for account-to-account transfers that stays strictly consistent, avoids overdrafts and duplicate charges, and survives crashes at any point.
Scenario
You are designing the core of a payments platform in which customers move money between accounts. The platform handles millions of transfers a day across several regions. Losing a committed transfer is unacceptable, and so is letting the same funds be spent twice.
What the system must do
- Show a customer the current balance of an account.
- Move money from one account to another.
- Return a paginated history of an account's transactions.
Qualities it must have
- Correctness: Transfers are atomic and consistent. Money is never created or destroyed, and an account can never be overdrawn by racing requests.
- Throughput: Many transfers run at the same time without corrupting state.
- Durability: Once a transfer is confirmed, it survives machine, rack, and zone failures.
- Availability: Balance lookups and transfers stay responsive under normal failures.
What your answer should cover
- Capacity estimate: Turn the volume into transactions per second, read/write ratio, and storage growth.
- API: Endpoints for transfers, balance, and history, including how clients can safely retry.
- Data model: Pick a storage technology and a schema, and justify it (relational vs. NoSQL, how atomicity across two accounts is achieved).
- Architecture: Service boundaries, replication, messaging, and any consensus or coordination you rely on.
- Concurrency control: How you stop two simultaneous debits from driving a balance below zero, and how you deal with extremely busy accounts.
- Cross-shard transfers: What happens when the two accounts live on different database shards.
- Failure handling: What state is the system in, and how does it recover, if a process dies halfway through a transfer?
Hints
Hint 1
Begin by writing down the invariants (total money is conserved, balances never go negative, a retried request is applied once) and check every design choice against them.
Hint 2
Treat an append-only set of debit/credit entries as the source of truth and the stored balance as a derived value updated in the same transaction. Think about a conditional update that fails when funds are insufficient.
Hint 3
For transfers spanning shards, compare a distributed transaction (2PC or distributed SQL) with a multi-step workflow using an in-flight holding account, an outbox, idempotent consumers, and a recovery job.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Put correctness ahead of raw throughput, then scale by partitioning. State the invariants up front and justify every decision against them:
- Total money is conserved (every transfer has equal debits and credits).
- No balance goes below zero.
- A request retried by the client takes effect at most once.
- A confirmed transfer is never lost.
1. Sizing
- 100M transfers/day is about 1,200 TPS on average. Plan for 10x peaks, so about 12k TPS.
- Reads (balance, history) are roughly 10x writes, so about 100k QPS at peak.
- Each transfer writes one transfer row and two ledger entries, about 600 B. That is about 60 GB/day and 22 TB/year, retained 7+ years.
- Assume a single currency for now. Target p99 under 500 ms for a domestic transfer.
- Writes favor consistency over availability (CP per shard). Balance reads may be slightly stale if they carry an
as_oftimestamp.
2. API
POST /v1/transfers
Header: Idempotency-Key: <uuid>
Body: { from_account_id, to_account_id, amount_minor, currency }
-> { transfer_id, status: PENDING | COMPLETED | FAILED }
GET /v1/transfers/{id}
GET /v1/accounts/{id}/balance -> { available, pending, as_of }
GET /v1/accounts/{id}/transactions?cursor=&limit=
- The idempotency key is stored under a unique constraint, so a retry after a timeout returns the original result instead of charging twice.
- Amounts are integers in minor units. Never use floating point for money.
- History uses cursor pagination, not offsets.
3. Data model
Use a relational store (sharded Postgres/MySQL, or Spanner/CockroachDB). You need multi-row ACID transactions, unique constraints, and conditional updates, all of which are awkward in most NoSQL systems.
accounts(account_id, currency, balance, version, status, CHECK balance >= 0)transfers(transfer_id, idempotency_key UNIQUE, from, to, amount, state, timestamps)ledger_entries(entry_id, transfer_id, account_id, direction, amount, balance_after, created_at, UNIQUE(transfer_id, account_id, direction)), append-onlyoutbox(id, event_type, payload, published)
This is double-entry bookkeeping: each transfer writes a debit and a credit. The entries are the immutable truth, and balance is a cached projection updated in the same transaction. A nightly job checks that each balance equals the sum of its entries. Errors are fixed with new reversing entries, never edits.
Shard by account_id, with an index on (account_id, created_at) so history reads hit one shard.
4. Architecture
Client -> API gateway (auth, rate limiting) -> stateless transfer service -> fraud/risk check -> ledger shards. Each shard has a leader plus synchronous replicas in other availability zones (Raft or semi-synchronous replication). An outbox relay publishes events to Kafka for downstream credit workers, notifications, and CDC into a warehouse. A recovery sweeper re-drives stuck transfers.
Durability: acknowledge a commit only after a quorum in different zones has persisted the log. Add point-in-time backups and an immutable event archive.
5. Concurrency
For a same-shard transfer, run one local transaction:
BEGIN;
UPDATE accounts SET balance = balance - :amt, version = version + 1
WHERE account_id = :from AND balance >= :amt; -- 0 rows => insufficient funds, rollback
UPDATE accounts SET balance = balance + :amt WHERE account_id = :to;
INSERT INTO ledger_entries (...) -- debit and credit
UPDATE transfers SET state = 'COMPLETED' WHERE transfer_id = :id;
COMMIT;
The conditional update is atomic under row locking, so two concurrent withdrawals cannot both pass the balance check.
Pessimistic (FOR UPDATE) | Optimistic (version check) | |
|---|---|---|
| Good for | Contended accounts | Low-contention retail accounts |
| Risk | Lower throughput, deadlocks | Retry storms on hot rows |
With pessimistic locks, always lock accounts in ascending ID order to avoid deadlocks.
Hot accounts (merchants, payroll) break both schemes. Split the balance into N buckets, or accept credits as an append-only stream that is aggregated asynchronously. Credits may lag, but debits stay strict.
6. Cross-shard transfers and crashes
Option A: distributed SQL or 2PC. Simple to reason about and serializable, but with higher latency, and 2PC can block if the coordinator dies holding locks.
Option B: saga with transactional outbox (common at scale):
- On the source shard, in one transaction: debit the source, credit a suspense account, mark the transfer
DEBITED, and write an outbox row. Money is never "nowhere". - The relay publishes the event to Kafka (at-least-once).
- On the destination shard, in one transaction: debit suspense, credit the destination, mark
COMPLETED. The unique constraint on ledger entries makes redelivery a no-op. - If the credit fails permanently (closed or frozen account), a compensating transaction returns funds to the source and the state becomes
REVERSED.
Crash mid-transfer: each step is a local atomic transaction, so a crash lands before or after a step, never inside one. The outbox removes the "DB committed but message lost" problem. The sweeper scans non-terminal transfers older than N seconds and replays them, which is safe because every step is idempotent.
7. Trade-offs
- Saga vs 2PC: the saga gives better availability at the cost of the recipient seeing funds a little later. The sender's balance is correct immediately and suspense keeps the books balanced.
- CP writes: if a shard loses quorum, transfers touching it fail fast rather than diverge.
- Strong reads cost more, so serve available balance from the leader and history from replicas.
Common mistakes
- Using floats for money.
- Read-then-write balance checks without a conditional update or lock.
- Writing to the DB and publishing to a broker as two separate steps (dual write).
- No idempotency key, so retries double-charge.
- Overwriting balances without an append-only ledger and reconciliation.
- Ignoring hot accounts and lock ordering.