Double-Entry Ledger with Account Consolidation
System DesignModel answerLast updated
Design an ACID, idempotent, sharded banking ledger that supports transfers, paginated history, and merging one account into another under concurrent traffic.
You are asked to design the backend of a corporate banking platform. The platform tracks account balances, moves money between accounts, and lets a customer fold one of their accounts into another.
Functional requirements
- Move money between two accounts held on the platform.
- Consolidate accounts: a customer designates a source account and a destination account. The source account's remaining balance and its visible transaction history become part of the destination, and the source account is permanently retired.
- Statement retrieval: return a paginated list of transactions for a given account.
Non-functional requirements
- Balances must be strictly consistent (ACID); money is never created or destroyed.
- A client retry of the same transfer must not post the transfer twice.
- Every state change must be immutably recorded for auditors.
- The system must sustain roughly 5,000 transactions per second globally.
What to deliver
- The service endpoints (request/response shapes and status codes).
- A schema for accounts and ledger entries, plus the invariant that protects the money.
- How consolidation interacts with transfers that are hitting the source account at the same moment.
- A sharding strategy and how you handle a transfer or merge that crosses shards.
Hints
Hint 1
Decide early whether 'moving history' means physically rewriting old rows or only changing what a reader sees — immutability and rewriting are in direct conflict.
Hint 2
If balances live in the same row as the accounts, closing an account and zeroing it must be one atomic step; think about what lock protects that.
Hint 3
A unique constraint written in the same database transaction as the ledger rows is the only reliable idempotency guard; a cache in front of it is just an optimization.
Hint 4
Pick your shard key so the common case (two accounts of the same customer) stays on one machine.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Frame the numbers first
5,000 TPS average means plan for ~3× peaks, so ~15,000 TPS. Because money moves in double-entry pairs, that is ~10k ledger rows/s average and ~30k/s peak. Daily: 5,000 × 86,400 ≈ 430M transfers, ~860M ledger rows. At ~200 bytes per row with indexes, roughly 170 GB/day and 60 TB/year — partitioning is mandatory from day one, not a later optimization. Reads (balance lookups, statement pages) will outnumber writes maybe 5–10×, so replicas carry most of the read load.
Three questions worth asking before designing:
- Single currency per account, or multi-currency with FX?
- Do merging accounts always share an owner (same corporate customer)? Assume yes.
- Does "move the history" mean auditors must see the same rows, or only that a customer-facing statement shows them together?
The third question is the crux. Auditors require an append-only ledger, so rewriting account_id on historical entries is out. The clean resolution is: history is moved logically (readers are redirected), and the balance is moved with a brand-new ledger transaction.
2. API surface
POST /v1/transfers
Idempotency-Key: <uuid>
{ from_account_id, to_account_id, amount_minor, currency, memo }
-> 201 { transfer_id, status: "POSTED" }
-> 409 account not active / insufficient funds / currency mismatch
GET /v1/accounts/{id}
-> { id, status, balance_minor, version }
POST /v1/accounts/{source_id}/merge
Idempotency-Key: <uuid>
{ destination_account_id }
-> 202 { merge_id, status: "PENDING" }
GET /v1/merges/{merge_id}
-> { status: PENDING | COMPLETED | FAILED }
GET /v1/accounts/{id}/transactions?limit=50&cursor=<opaque>
-> { items: [...], next_cursor }
Amounts are integer minor units — never floats. Merge returns 202 because it may need to wait for in-flight work to drain. Statement pagination is keyset on (posted_at, entry_id); OFFSET on billion-row tables collapses under load.
3. Data model
accounts(
account_id UUID PK,
customer_id UUID, -- shard key
currency CHAR(3),
status ENUM('ACTIVE','PENDING_MERGE','MERGED','CLOSED'),
merged_into UUID NULL,
balance_minor BIGINT, -- cache, derived from ledger
version BIGINT -- optimistic concurrency
)
transfers( -- one row per business event
transfer_id UUID PK,
kind ENUM('TRANSFER','MERGE_SWEEP','REVERSAL'),
idempotency_key VARCHAR UNIQUE,
request_hash CHAR(64), -- detects key reuse with different body
status, created_at
)
ledger_entries( -- append-only: no UPDATE, no DELETE
entry_id BIGINT PK,
transfer_id UUID,
account_id UUID,
direction ENUM('DEBIT','CREDIT'),
amount_minor BIGINT CHECK (amount_minor > 0),
balance_after BIGINT,
posted_at TIMESTAMP,
INDEX (account_id, posted_at, entry_id)
)
merges(merge_id, source_id, dest_id, state, sweep_transfer_id, created_at, completed_at)
The money invariant: for every transfer_id, sum(debits) = sum(credits), and across the whole ledger total debits = total credits. A periodic reconciliation job asserts this; it is the single most valuable alert in the system.
Two design commitments to state explicitly: the ledger is the source of truth and balance_minor is a cache updated in the same DB transaction as the entries; and corrections are compensating reversals, never edits. That is what makes the record auditable.
4. Core flows
Transfer (same shard), one ACID transaction
INSERTthe transfer row with the idempotency key. A unique-violation means a retry: look up and return the original result. Store a hash of the request body and return 422 if the same key arrives with a different body.SELECT ... FOR UPDATEboth account rows, always in sorted account_id order to eliminate deadlocks.- Validate: both ACTIVE, same currency, source balance ≥ amount.
- Insert both ledger entries and
UPDATEboth balances. Commit.
Idempotency nuance: a Redis dedupe cache is a nice fast path but cannot be the authority — a crash between "write cache" and "commit ledger" either loses or duplicates money. Only the unique constraint committed atomically with the entries is safe.
Merge — the hard part
Model it as a state machine: ACTIVE → PENDING_MERGE → MERGED.
- Freeze. In one transaction, lock the source row, verify source and destination are both ACTIVE with the same currency and customer, set source to
PENDING_MERGE, and insert themergesrow. Transfers take the same row lock and check status, so every concurrent transfer is either fully committed before the freeze or seesPENDING_MERGEand gets a retryable 409. That gives linearizability without any global lock. - Drain. Wait for any in-flight cross-shard reservations that hold funds on the source to settle or expire (poll the holds table).
- Sweep. In one transaction, lock both rows, post a
MERGE_SWEEPtransfer that debits the source and credits the destination for the full remaining balance, set sourcestatus=MERGED, merged_into=dest, and mark the mergeCOMPLETED. - History. Never touch old rows. A statement request for account X resolves to the set of accounts whose
merged_intochain ends at X (cache this set), reads entries for all of them, and k-way merges by(posted_at, entry_id). If the read path needs to be faster, build a denormalizedstatement_by_ownerread model asynchronously from CDC — it can be rewritten freely because it is not the record of truth.
Consequences worth calling out: history "moves" instantly and atomically at step 3 with no bulk copy that can half-fail; and for inbound transfers to a retired account you must choose a policy — reject, or resolve merged_into and redirect (friendlier for payees with stale details, and log the redirect in metadata).
5. Sharding and cross-shard work
Shard key: customer_id (hash or directory-based). All of one customer's accounts live together, so intra-company transfers and merges — the dominant case — are single-shard ACID. Sharding by account_id instead would make nearly every transfer and every merge distributed. With ~32 shard primaries plus sync replicas, each takes ~500 TPS at peak, comfortably inside budget; a directory service lets you migrate a hot customer.
Cross-shard transfers use a saga with reservations, not 2PC:
- Orchestrator persists
INITIATED. - Source shard debits and records a reservation, status
DEBITED. - Destination shard credits, status
CREDITED; orchestrator marksPOSTED. - If step 3 fails, a compensating reversal on the source; reservations expire and are swept by a reaper.
The invariant is maintained by doing the two halves in separate ledger transactions whose reversal is guaranteed to eventually run — never by hoping a distributed commit succeeds.
Common mistakes: offset pagination; floats for money; using a cache as the idempotency authority; locking two accounts in arbitrary order (deadlocks); physically rewriting account_id on ledger rows (audit failure); making merge synchronous and blocking on in-flight transfers; and sharding by account so every transfer needs a saga.