Design a Payment System: Double-Entry Ledgers, Idempotency Keys & Reconciliation
The Golden Rule of FinTech Architecture: Zero Silent Money Loss
Scalable Payment System Architecture
1. Pay-In Flow vs. Pay-Out Flow
- Pay-In (Buyer → Platform):
- User clicks Pay → API creates a
PaymentEvent(NOT_STARTED) → Payment Executor calls PSP (Stripe/Adyen) using a Hosted Card Token → PSP confirms → Executor records completion in Ledger + Wallet asynchronously via Kafka!
- User clicks Pay → API creates a
- Pay-Out (Platform → Seller):
- Triggered on scheduled settlement windows or payouts, routing funds via bank transfer / PSP payout APIs after passing fraud/risk checks.
2. Double-Entry Ledger: Accounting That Always Balances
balance = balance - 50 column in place! Store an immutable append-only Double-Entry Ledger where every transaction writes balanced opposing rows whose sum must equal zero:| Account | Debit | Credit | Entry Meaning |
|---|---|---|---|
| Buyer Clearing Account | $50.00 | — | Buyer owes/pays $50 |
| Seller Merchant Account | — | $48.50 | Seller receives $48.50 |
| Platform Fee Revenue | — | $1.50 | Platform takes $1.50 fee |
3. Exactly-Once Execution: Idempotency Keys & Retries
- Idempotency Header: Client generates a unique
UUIDv4key per checkout session (Idempotency-Key: 9f8a-...) and sends it to the Payment Service. - Atomic Lock + Cached Result: Server stores
idempotency_keyin aUNIQUEindexed SQL/Redis table:- First call inserts
IN_PROGRESS(returns409 Conflictif another thread races concurrently!), completes PSP charge, saves response (200 OK), and forwards the exact sameidempotency_keyto the PSP! - Retries immediately return the saved response without hitting the card twice.
- First call inserts
- Transient Network Failures: Retry failed internal steps via Kafka + Dead-Letter Queues (DLQ) with exponential backoff.
4. The Last Line of Defense: Automated Reconciliation
- Every night, each PSP generates an immutable Settlement File listing every cleared charge and refund.
- The Reconciliation Service compares the PSP Settlement File line-by-line against your internal Double-Entry Ledger—automatically flagging discrepancies (PSP captured money, internal DB missed webhook → auto-heal or route to Finance Ops!).