Design a Digital Wallet: 2PC vs TCC vs Saga, Event Sourcing & Raft Consensus
Scaling Peer-to-Peer Wallet Transfers to 1 Million TPS
BEGIN; UPDATE ... COMMIT; cannot span two distinct servers atomically without distributed coordination!Digital Wallet Event Sourcing & Raft Architecture
1. Distributed Transactions Compared: 2PC vs. TCC vs. Saga
| Pattern | How It Works | Lock Contention | Best Use Case |
|---|---|---|---|
| Two-Phase Commit (2PC) | Coordinator runs Prepare (acquires X-locks on all shards) → Commit | ❌ Holds locks across network RPCs; stalls on coordinator crash | Low-TPS legacy cross-DB monoliths |
| TCC (Try-Confirm-Cancel) | Phase 1: Try reserves balance (frozen += $100); Phase 2: Confirm transfers or Cancel releases | Short business-level reservation; no long DB row locks | Cross-shard wallet transfers requiring strict invariants |
| Saga Pattern | Sequential local transactions + Compensating Undo actions on failure | Zero cross-shard locks (eventual consistency) | Long-lived multi-service workflows (Checkout → Shipping) |
Why TCC Shines for Wallets
Try, Shard A atomically deducts available funds into a pending hold (available -= 100, pending += 100) while validating Bob's account exists on Shard B. Only after both Try phases persist an outbox/transaction log does Confirm finalize balances—ensuring Alice can never double-spend!2. Reproducibility & Auditability: Event Sourcing + CQRS
- Source of Truth = Immutable Command/Event Log: Never overwrite balances blindly. Record every immutable transaction event (
WalletCredited,WalletDebited) sequentially in an append-only log (e.g., Kafka / RocksDB). - Deterministic State Machine: Replaying events from offset
0through the state machine deterministically reproduces the exact balance at any timestamp. - CQRS Read Views & Snapshots: Take periodic balance Snapshots (
offset_100000 -> $420) so recovery replays only recent delta events in milliseconds rather than scanning years of history!
3. Pushing to 1 Million TPS: In-Memory State Machines + Sharded Raft
- Partition wallets across $N$ Sharded Raft Groups (
Node Leader + 2 Followersper shard). - The Shard Leader runs Event Sourcing entirely in memory / embedded RocksDB (
1M+ ops/sec), replicating every ordered event via Raft Consensus before acknowledging! - If the Leader dies, Followers hold a strictly identical replicated command log and elect a new Leader in milliseconds with zero lost cents.