Design a Distributed Financial Ledger System
System DesignModel answerLast updated
Build a strongly consistent, double-entry ledger handling concurrent writes, balance queries, and audit trails at scale.
You're building the core ledger for a payments platform that tracks money movements between customer wallets, merchant accounts, platform fees, and external bank accounts.
Design a system that:
- Records financial transactions with multiple legs (for example, a payment that debits a customer, credits a merchant, and credits a fee account)
- Maintains account balances that can be queried in real time
- Guarantees correctness: no duplicate charges, no lost money, balances always reconcile
- Handles concurrency: thousands of transactions per second, including many against the same hot accounts
- Supports auditability: full history, point-in-time balance reconstruction, and compliance reporting
Your design should cover:
- Data modeling and the double-entry accounting model
- API contracts for posting transactions and querying balances
- Consistency guarantees and how you achieve them
- Handling retries and preventing duplicate charges
- Scaling to 10,000 transactions/sec with peaks at 50,000/sec
- Managing hot accounts that receive tens of thousands of operations per second
- Failure modes and recovery
Discuss trade-offs between consistency, latency, and throughput. Explain how you'd validate correctness continuously.
Hints
Hint 1
Every transaction must balance to zero within its currency—this is the core invariant to protect
Hint 2
Idempotency keys let clients safely retry without creating duplicate charges
Hint 3
Hot accounts like a platform fee collector become bottlenecks if modeled as a single row with a lock
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Distributed Financial Ledger
This problem tests your ability to build a system where correctness is non-negotiable. A good answer demonstrates deep understanding of transactions, isolation levels, idempotency, and the trade-offs between strict consistency and performance.
Requirements and Scale
Functional:
- Record multi-leg transactions (a single logical operation touching multiple accounts)
- Query current balance and transaction history per account
- Immutable history; corrections appear as new reversing entries
- Support different account types (customer wallets, merchant payouts, fees, external banks)
Non-functional:
- Strong consistency for balance checks that prevent overdrafts
- Write availability with brief rejections acceptable; silent corruption is not
- Full auditability and the ability to reconstruct any balance at any timestamp
- 10k transactions/sec average, 50k peak; each transaction has ~3 entries, so 150k entry writes/sec at peak
- 100M accounts with some extremely hot accounts (platform fee collector, large merchants)
- 10-year retention: roughly 30B entries/year at ~200 bytes each = 6 TB/year raw data
API Design
POST /v1/transactions
Headers: Idempotency-Key: <uuid>
Body: {
"entries": [
{"account_id": "acct_customer_123", "type": "debit", "amount": 5000, "currency": "USD"},
{"account_id": "acct_merchant_456", "type": "credit", "amount": 4850, "currency": "USD"},
{"account_id": "acct_platform_fees", "type": "credit", "amount": 150, "currency": "USD"}
],
"metadata": {"order_id": "ord_789", "description": "Widget purchase"}
}
Response: 201 {"transaction_id": "txn_...", "status": "posted", "timestamp": "..."}
409 {"error": "insufficient_funds", "account_id": "..."}
422 {"error": "unbalanced_transaction"}
GET /v1/accounts/{account_id}/balance
?as_of=2026-10-31T12:00:00Z (optional)
GET /v1/accounts/{account_id}/ledger
?from=...&to=...&cursor=...&limit=100
POST /v1/transactions/{txn_id}/reverse
Key decisions:
- Amounts are integers in the smallest currency unit (cents, not dollars) to avoid floating-point rounding errors
- Each transaction operates within a single currency; foreign exchange is two transactions through an FX clearing account
- Idempotency keys are mandatory and tied to the request payload hash
Data Model (Double-Entry Accounting)
accounts table:
account_id(PK),currency,account_type(asset/liability/revenue/expense),allow_negative(boolean),version,created_at
transactions table:
transaction_id(PK),idempotency_key(unique index),status(posted/reversed),created_at,metadata(JSON)
entries table (append-only):
entry_id(PK),transaction_id,account_id,entry_type(debit/credit),amount,created_at- Index on
(account_id, created_at)for history queries
balances table (materialized view):
account_id(PK),available_balance,version,last_entry_id,updated_at
idempotency_store table:
idempotency_key(PK),request_hash,response_body,status_code,expires_at
Core invariant: For every transaction, sum(debits) = sum(credits). Validate before committing. Back this up with nightly zero-sum checks per currency across all accounts.
Architecture
Clients
↓
API Gateway (rate limiting, auth)
↓
Ledger Service (stateless, horizontally scaled)
↓
Distributed SQL Database (Postgres with Citus, CockroachDB, or Spanner)
- Sharded by account_id for horizontal scaling
- Synchronous replication within region
↓
Change Data Capture (CDC) → Kafka
↓
[Analytics warehouse, reconciliation service, audit logs, customer notifications]
Deep Dive: Consistency and Atomicity
1. Atomic Transaction Posting
Each transaction must atomically:
- Insert the transaction record
- Insert all entry records
- Update all affected account balances
- Store the idempotency key and response
Use a database transaction at SERIALIZABLE or REPEATABLE READ isolation. Acquire locks on balance rows in sorted account_id order to prevent deadlocks:
BEGIN;
-- Lock balance rows in deterministic order
SELECT * FROM balances
WHERE account_id IN ('acct_123', 'acct_456', 'acct_fees')
ORDER BY account_id
FOR UPDATE;
-- Validate balance constraints (overdraft check)
UPDATE balances
SET available_balance = available_balance - 5000, version = version + 1
WHERE account_id = 'acct_123'
AND (available_balance - 5000 >= 0 OR allow_negative = true);
-- If zero rows updated, rollback and return insufficient_funds
-- Insert transaction and entries
INSERT INTO transactions (transaction_id, idempotency_key, ...) VALUES (...);
INSERT INTO entries (entry_id, transaction_id, account_id, ...) VALUES (...), (...), (...);
-- Update other balances
UPDATE balances SET available_balance = available_balance + 4850 WHERE account_id = 'acct_456';
UPDATE balances SET available_balance = available_balance + 150 WHERE account_id = 'acct_fees';
-- Store idempotency response
INSERT INTO idempotency_store (...) VALUES (...);
COMMIT;
2. Idempotency for Safe Retries
Clients must include an idempotency key (UUID) with every write. On receiving a request:
- Hash the request body
- Check if the key exists:
- Same key + same hash → return stored response (idempotent retry)
- Same key + different hash → return 422 (key reuse violation)
- New key → proceed with transaction
Store the idempotency record in the same database transaction as the ledger write. This prevents the window where a write succeeds but the client never receives confirmation, leading to duplicate charges on retry.
3. Cross-Shard Transactions
Most transactions touch accounts on different shards. Three approaches:
Option A: Distributed SQL (recommended)
Use a database like CockroachDB or Google Spanner that provides native distributed ACID transactions. This is the simplest correct implementation, trading ~10-50ms of latency for strong guarantees.
Option B: Saga with Compensating Transactions
- Write entries in
pendingstate on each shard - Persist saga state in a coordinator table
- Once all legs succeed, flip entries to
posted - On failure, write compensating reversals
- Requires careful state machine design and durable task queue
Option C: Clearing Accounts
Route cross-shard movements through per-shard clearing accounts, making each local write atomic. A separate reconciler ensures clearing accounts net to zero. Adds operational complexity.
Recommendation: Start with distributed SQL for correctness, optimize hot paths later if latency becomes a bottleneck.
Deep Dive: Hot Accounts
A platform fee account receiving 20k credits/sec becomes a single-row bottleneck under locking.
Solution 1: Sub-Account Sharding
Split the logical account into N physical sub-accounts (e.g., 64 buckets). On each credit:
- Hash
transaction_idto select a bucket - Write only to that bucket (no cross-bucket coordination)
- On balance queries, sum all buckets
This parallelizes writes. Trade-off: balance reads become more expensive, but they're infrequent for fee accounts.
Solution 2: Asynchronous Balance Updates
For credit-only accounts that never check overdrafts:
- Append entries without locking the balance row
- Update the balance asynchronously in batches every 100ms
- Accept eventual consistency for balance reads on these accounts
Trade-off: Balance is slightly stale, but throughput increases 100x.
Deep Dive: Point-in-Time Queries and History
Entries are the source of truth. The balances table is a materialized cache.
For as_of queries:
- Store daily balance snapshots per account
- Query:
snapshot_balance + sum(entries WHERE created_at > snapshot_time AND created_at <= as_of_time)
Partition the entries table by month. Archive old partitions to cheaper storage (S3 via Parquet) but keep them queryable for audits.
Reconciliation and Continuous Validation
Runtime checks:
- Before each balance update, assert
new_balance = old_balance ± Δ - Emit metrics on balance version conflicts (indicates contention)
Batch validation (nightly):
- Recompute every account balance from entries; diff against the
balancestable - Assert global zero-sum per currency:
sum(all debits) = sum(all credits) - Reconcile against external bank statements and payment processor reports
Outbox pattern for events:
Use CDC or an outbox table to publish events only after the database transaction commits. This prevents downstream consumers from seeing events for rolled-back writes.
Failure Handling
Client-side:
- On timeout or 5xx, retry with the same idempotency key
- Exponential backoff with jitter
Service-side:
- Synchronous replication (quorum write) within region for RPO = 0
- Cross-region async replication for disaster recovery
- On database partition or coordinator failure, reject writes rather than risk inconsistency
Observability:
- Metrics: transaction throughput, p99 latency, idempotency cache hit rate, hot account contention
- Logs: every rejected transaction (insufficient funds, unbalanced, etc.)
- Alerts: zero-sum violations, reconciliation drift, sustained elevated latency
Trade-Offs Summary
| Decision | Trade-Off |
|---|---|
| Strong consistency | Accept 10-50ms write latency for correctness |
| Distributed SQL | Simpler code, higher infrastructure cost vs. saga complexity |
| Hot account sharding | Parallelizes writes but complicates balance queries |
| Idempotency in DB txn | Increases write latency slightly but guarantees safety |
| Entries append-only | Storage grows unbounded; requires archival strategy |
Common Mistakes
- Using floats for money (introduces rounding errors)
- Storing only balances without entries (loses audit trail and makes reconciliation impossible)
- Implementing idempotency in application memory (lost on restart, causes duplicates)
- Not acquiring locks in deterministic order (causes deadlocks under load)
- Forgetting to validate the zero-sum invariant before commit
A strong answer demonstrates that correctness comes first, and every optimization is validated against the core invariants.