Building a High-Throughput Payment Processing Platform
System DesignModel answerLast updated
Design a payment platform supporting wallet transfers, card transactions, refunds, and chargebacks with strong consistency, exactly-once semantics, and audit compliance.
You're tasked with designing a payment processing platform that handles multiple payment flows at scale. The platform must support:
- Wallet-to-wallet transfers between users
- Card and digital wallet payments (Apple Pay, Google Pay) for merchants
- Full lifecycle management: authorization, capture, void, refund
- Dispute and chargeback processing
- Complete transaction audit trails for users and merchants
- Integration with external payment processors, card networks, and banking systems
Your design should address:
-
Product requirements and scale assumptions: Define the core capabilities, expected throughput (transactions per second), latency targets, and data volume projections.
-
API contracts: Design the key endpoints for creating, authorizing, capturing, voiding, and refunding payments. Explain how you prevent duplicate charges and ensure exactly-once semantics.
-
Ledger architecture: Describe how money moves through the system. How do you model accounts, balances, and transactions? How do authorization holds differ from captured funds?
-
Payment flow and compliance boundaries: Walk through a card payment from end to end, including the roles of gateways, acquirers, card networks, and issuers. Where do you tokenize sensitive data, and how do you minimize your compliance scope?
-
Fraud prevention: What controls do you implement for risk assessment, velocity checking, and regulatory compliance (KYC/AML)?
-
Data model: Design schemas for transactions, ledger entries, settlements, and the structures needed for idempotency and auditing.
-
Failure handling and consistency: How do you handle failures in multi-step workflows? What consistency guarantees do you provide for balances versus transaction history? How do you manage retries?
-
Settlement and reconciliation: Explain how you match your internal records against external settlement reports, handle currency conversion, deduct fees, and schedule merchant payouts.
-
Scale and reliability: Describe your approach to horizontal scaling, request queueing, multi-region deployment, and disaster recovery.
-
Security and observability: Cover authentication, encryption, key management, privacy requirements, distributed tracing, and how you test integrations with external partners.
Present a high-level architecture and discuss the key trade-offs in your design.
Hints
Hint 1
Start with correctness: no money can be lost, created, or charged twice. Scale is secondary to getting the ledger right.
Hint 2
Use a double-entry accounting model where every transaction creates balanced debits and credits across accounts.
Hint 3
Idempotency keys and transactional outbox patterns are essential for exactly-once semantics in distributed payment flows.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: High-Throughput Payment Processing Platform
A well-structured answer prioritizes correctness over throughput—payments must never lose money, double-charge, or produce unbalanced ledgers. Spend the first few minutes establishing scope, then focus on the ledger model and failure handling before addressing scale.
1. Requirements and Scale Estimates
Core capabilities:
- Wallet transfers between users
- Card and digital wallet payments for merchants
- Multi-step payment lifecycle: authorize (reserve funds), capture (finalize), void (cancel), refund (reverse)
- Dispute and chargeback workflows
- Real-time status updates via webhooks
- Paginated transaction history
- Scheduled payouts to merchant bank accounts
Non-functional goals:
- Exactly-once money movement (no duplicate charges or lost funds)
- Strong consistency for account balances
- 99.99% availability for payment authorization
- Sub-200ms p99 latency for internal operations (external network calls to issuers may add 300ms–2s)
- Full audit trail for regulatory compliance
- PCI DSS compliance for card data, GDPR for user data, AML/KYC integration
Scale targets:
- 50 million users, 1 million merchants
- 1,000 TPS average, 10,000 TPS peak
- Each payment generates 4–8 ledger entries, so peak ledger write rate is 40k–80k entries/second
- ~100 million payments/day at ~2KB each = 200GB/day hot data
- 7+ year retention means cold storage strategy for historical ledger data
2. API Design
Key endpoints:
POST /payments— Create payment intent. Parameters:amount(integer minor units),currency,payer_id,payee_id,payment_method_token,capture_mode(auto/manual),metadataPOST /payments/{id}/authorize— Reserve funds (wallet hold or issuer authorization)POST /payments/{id}/capture— Finalize full or partial amount up to authorized totalPOST /payments/{id}/void— Cancel uncaptured authorizationPOST /payments/{id}/refunds— Reverse full or partial captured amountPOST /transfers— Direct wallet-to-wallet transferGET /payments/{id},GET /accounts/{id}/transactions— Status and paginated history
Responses include id, status, amounts (authorized/captured/refunded), next_action (e.g., 3DS redirect URL), error_code, timestamps.
Exactly-once semantics:
Every mutating request requires an Idempotency-Key header. The system:
- Stores
(merchant_id, idempotency_key) → request_hash, status, responseatomically with the payment record - Returns the cached response for retries with matching key and hash
- Returns 422 if the hash differs (different request body)
- Returns 409 if the original request is still processing
- Retains keys for 24–72 hours
Outbound calls to processors include our own reference ID so their systems can deduplicate retries.
State machine: created → requires_action → authorized → captured → refunded, with branches to voided, failed, disputed. Transitions use optimistic locking: UPDATE payments SET status=?, version=version+1 WHERE id=? AND version=?.
3. Double-Entry Ledger Model
Account types:
- User wallet
- Merchant receivable / payable
- Authorization holds
- Processor clearing (funds in flight)
- Fee revenue
- Currency conversion
- Chargeback reserve
- External bank accounts
Each account has a specific currency. A journal_transaction contains 2+ ledger_entries (account_id, amount, debit/credit). Entries within each currency must sum to zero. Entries are immutable; corrections post reversals.
Sample flows:
Wallet transfer: Debit Alice's wallet, credit Bob's wallet—atomic in one transaction.
Card authorization: No ledger movement yet (issuer holds funds). Record as memo/pending state.
Capture: Debit processor clearing (receivable from acquirer), credit merchant payable (net amount), credit fee revenue.
Settlement: When acquirer pays out, debit bank account and credit processor clearing.
Payout: Debit merchant payable, credit external bank account.
Refund/chargeback: Reverse postings. Chargebacks also debit merchant balance, potentially drawing from reserve.
Balance materialization: Store balance and version on each account row, updated atomically with ledger entries. This enables overdraft checks (available_balance >= amount) in a single transaction.
4. Architecture Overview
Components:
- API Gateway: Authentication, rate limiting, idempotency cache lookup
- Payment Orchestrator: Owns state machine, coordinates multi-step workflows (sagas)
- Risk Service: Synchronous fraud scoring (~50ms budget)
- Ledger Service: Sole writer of money. Uses sharded, strongly consistent SQL (Postgres/CockroachDB/Spanner), sharded by account_id
- Tokenization Vault: Isolated PCI zone storing card PANs
- Processor Adapters: Per-acquirer integration with intelligent routing
- Event Bus (Kafka): Feeds webhooks, notifications, read projections (Elasticsearch for search, Cassandra for history), reconciliation jobs, payout scheduler, analytics warehouse
Card payment flow:
- Client SDK sends card directly to vault; receives token (PAN never touches merchant or core services)
- Orchestrator calls risk service, then processor adapter
- Adapter calls acquirer
- Acquirer routes through card network (Visa/Mastercard) to issuer
- Issuer approves/declines and places hold
- Capture batched to acquirer in clearing files
- Settlement occurs T+1 or T+2, net of interchange and network fees
PCI scope: Limited to vault and processor adapters (which detokenize only at the moment of outbound call). All other services stay out of scope.
Digital wallets (Apple/Google Pay): Generate network tokens + per-transaction cryptogram. Vault decrypts payload, sends DPAN and cryptogram to processor. These payments have built-in SCA, reducing 3DS friction and fraud risk.
5. Consistency and Failure Handling
Ledger writes: Strongly consistent, ACID transactions. All downstream consumers (webhooks, search, analytics) are eventually consistent.
Transactional outbox pattern: State update, ledger entries, and outbox event committed atomically. A separate relay process (CDC or poller) publishes events to Kafka. This decouples the write path from message delivery and survives crashes.
Saga orchestration: Multi-step workflows (authorize → risk check → capture → notify) coordinated by the orchestrator. Each step is idempotent. On failure, compensating transactions are triggered (e.g., void authorization if capture fails).
Retries: Exponential backoff with jitter for transient failures. Circuit breakers for degraded external services. Dead-letter queues for persistent failures requiring manual review.
Duplicate prevention: Unique constraints on (merchant_id, idempotency_key) and payment_reference_id. Database enforces at-most-once ledger entry creation even if application logic retries.
6. Data Model
Payments table: id, merchant_id, payer_id, payee_id, amount, currency, status, version, idempotency_key, request_hash, authorized_amount, captured_amount, refunded_amount, created_at, updated_at
Ledger entries: id, journal_transaction_id, account_id, amount, type (debit/credit), created_at (immutable, append-only)
Accounts: id, owner_id, owner_type, currency, balance, version
Idempotency log: merchant_id, idempotency_key, request_hash, response, created_at, expires_at
Settlement records: id, processor_id, settlement_date, file_reference, total_amount, reconciled_at
7. Settlement and Reconciliation
Daily batch job fetches settlement files from acquirers. Each file lists transactions, fees, chargebacks. Reconciliation engine matches file entries to internal journal transactions by reference ID. Discrepancies trigger alerts. Currency conversion applied at spot rate captured at transaction time. Merchant payouts scheduled (daily/weekly) once settlement clears and reserve requirements met.
8. Scalability and Resilience
Horizontal scaling: Ledger service sharded by account_id. Orchestrator and API gateway are stateless and scale horizontally. Read replicas for history queries.
Queueing and backpressure: Kafka buffers async work. Rate limits and circuit breakers protect downstream systems.
Multi-region: Active-passive for writes (ledger requires strong consistency). Active-active for reads. RPO ~5 minutes (asynchronous replication), RTO ~15 minutes (failover automation).
Disaster recovery: Daily snapshots, continuous WAL archival, cross-region replication for compliance and DR.
9. Security, Privacy, Observability
Auth: OAuth 2.0 for merchants, internal JWT for service-to-service. Fine-grained permissions (authorize vs capture vs refund).
Encryption: TLS 1.3 in transit. AES-256 at rest for PII and vault data. Key rotation via HSM or cloud KMS.
Privacy: PII encrypted, access logged. GDPR right-to-erasure handled by tombstoning (preserve ledger integrity, redact personal identifiers).
Observability: Distributed tracing (Jaeger/Tempo) with correlation IDs. Metrics for authorization success rate, p99 latency, ledger balance drift. Structured logs for audit trail.
Testing: Sandbox environment with processor simulators. Chaos engineering (random failures, latency injection) in staging. Synthetic transaction monitoring in production.
Key Trade-offs
- Strong consistency for balances vs eventual consistency for history: Prevents overdrafts but means search/analytics lag slightly.
- Synchronous risk scoring vs asynchronous: Adds latency but catches fraud before authorization.
- Sharded ledger vs single global database: Enables scale but complicates cross-account transactions (require distributed transaction or saga).
- PCI scope minimization vs operational complexity: Tokenization vault adds a hop but drastically reduces compliance burden.
- Multi-region active-active vs active-passive: Active-passive simpler for strong consistency; active-active requires conflict resolution (CRDTs or consensus).
This design prioritizes correctness, auditability, and regulatory compliance while scaling to thousands of transactions per second through sharding, async processing, and careful failure handling.