System design prompt: design Stripe payments ledger.
Start with requirements:
1) Immutable, auditable history. No UPDATE in place. Every balance change is an event.
2) Correctness over latency. Strong consistency per account. Idempotent writes.
3) Queries: current balance, balance at time T, list transactions, reconciliation/export.
4) Multi-currency, fees, refunds, disputes, chargebacks, holds.
APIs + data model:
- POST /entries (idempotency_key, account_id, currency, amount, type, external_ref)
- POST /transfers (from_account, to_account, amount, currency, ref)
- GET /balance?account_id=&as_of=
Tables:
- accounts
- journal_entries(id, ts, currency, metadata, external_ref)
- entry_lines(entry_id, account_id, amount, direction, available_vs_pending)
Balance is sum(lines) grouped by account+currency. Keep derived balance snapshots for speed, but treat them as cache.
Architecture:
- Write path: API -> validator -> append-only store (SQL with constraints) -> async projector builds balance snapshots and search indexes.
- Partition by account_id so all mutations for an account serialize on one shard.
- Use unique(idempotency_key, account_id) to make retries safe.
- Every transfer is double-entry: two lines, same entry_id, commit atomically.
Scaling + tradeoffs:
- Hot accounts: shard within account by sub-ledger (available/pending) or by currency, but keep a single ordering key.
- Read performance: periodic snapshots (eg every 1k entries) + replay tail.
- Exactly-once is a trap. Build at-least-once with idempotency + reconciliation jobs.
Failure cases to discuss:
- Partial writes: enforce DB transaction for entry + lines, or nothing.
- Duplicate requests: idempotency keys must survive deploys and cache evictions.
- Clock skew: ordering is DB sequence, not client timestamps.
- Backfills and reversals: never delete. Post compensating entries.
- Projector lag: balance endpoint can serve strongly consistent (compute from source) vs fast (snapshot) with clear staleness bounds.