Build a Multi-Provider Payment Routing and Ledger Platform
System DesignModel answerLast updated
Design a merchant payment platform that routes charges across several processors, survives timeouts without double-charging, and keeps refunds, captures and authorizations consistent.
Problem
A large global online merchant sells subscriptions and one-time items. Its checkout services should not talk to card processors directly. Design an internal payment orchestration platform that sits between checkout and several external payment service providers (PSPs), for example a card acquirer, a regional processor and a wallet provider.
The platform must handle the full payment lifecycle (authorize, capture, void, refund), choose among providers dynamically, tolerate flaky networks, and guarantee that a customer is never charged twice or refunded more than was collected.
Functional requirements
- Expose operations to authorize, capture (full or partial), void and refund (full or partial).
- Select a provider using configurable rules, and fail over when the preferred provider is unhealthy or timing out.
- Provide exactly-once effect for client requests, even with concurrent retries.
- Consume PSP callbacks (webhooks) that can be late, duplicated or out of order.
- Keep an immutable audit trail and a double-entry ledger so that
refunded <= captured <= authorizedalways holds.
Non-functional requirements
- Strong consistency for payment state and money totals.
- 99.999% availability for accepting new authorization requests.
- p99 latency under 500 ms for the platform's own work (excluding provider time).
- Never store raw card numbers; use a tokenization service to keep PCI scope small.
Scale
- About 50 million transactions per day (roughly 600/s average, 3,500/s at peak).
- Up to 10,000 webhook events per second at peak.
- Financial records and audit data kept for 7 years.
What to deliver
- A high-level architecture from checkout to provider call.
- The payment state machine and a data model that enforces the money invariants.
- How you handle provider timeouts and failover without duplicate authorizations.
- How webhooks are ingested and reconciled with current payment state when they arrive out of order.
Hints
Hint 1
A timeout is not a failure. Think about what the platform knows after a timeout, and what must happen before a second provider is tried.
Hint 2
Separate the client's idempotency key (one logical request) from an attempt (one call to one provider), and give each attempt its own deterministic provider-side idempotency key.
Hint 3
Put the state change, ledger rows, audit/outbox event and idempotent response in a single database transaction, and add CHECK constraints so the invariants hold even if application code is wrong.
Hint 4
For webhooks, acknowledge fast, deduplicate by provider event id, partition by provider reference, and push events through the same state-machine code as synchronous responses, treating them as facts that may be stale.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify and size
- API load: 3,500 TPS peak. Each payment touches roughly 3-6 rows (payment, attempt, ledger entries, outbox, idempotency record), so plan for about 20k writes/s at peak.
- Webhooks: 10k/s bursts. Acknowledge quickly, or providers retry and amplify the load.
- Storage: 50M payments/day at about 2 KB each is roughly 100 GB/day, about 36 TB/year, about 250 TB over 7 years before replication. Keep about 90 days hot, then tier to immutable (WORM) object storage.
- Consistency vs availability: ingestion must stay up, but money state must be strongly consistent. Resolve this by durably accepting the intent in any healthy region while serializing each payment's transitions on one home shard chosen by
payment_id.
2. API
POST /payments(authorize, optional auto-capture),POST /payments/{id}/capture,/void,/refunds,GET /payments/{id}.- Every mutating call requires an
Idempotency-Key. - Clients send only a payment token from the vault, never a PAN.
POST /webhooks/{psp}is signature-verified.
3. Architecture
- API gateway (authn, rate limiting) leads to a stateless orchestrator.
- The orchestrator uses a strongly consistent store sharded by
payment_id(Spanner/CockroachDB, or sharded Postgres with synchronous replicas) holding payments, attempts, idempotency keys and ledger. - A router combines rules (currency, card network, BIN country, cost, merchant preference) with per-PSP health scores and circuit breakers.
- PSP adapters call the vault to detokenize, then call the provider.
- A transactional outbox feeds Kafka for orders, notifications and analytics.
- Separate components: a webhook ingest tier, a webhook processor, a recovery worker for unknown outcomes, and a nightly reconciler against settlement files.
4. Data model and state machine
payments(id, state, version, authorized_amt, captured_amt, refunded_amt, refund_pending_amt)withCHECK (captured_amt <= authorized_amt)andCHECK (refunded_amt + refund_pending_amt <= captured_amt).idempotency_keys(merchant_id, key, request_hash, payment_id, status, response)with a primary key on(merchant_id, key).payment_attempts(attempt_id, payment_id, op, psp, psp_idem_key UNIQUE, psp_reference UNIQUE, status)where status is PENDING, SUCCEEDED, FAILED or UNKNOWN.ledger_entries(txn_group_id, account, direction, amount): append-only, each group nets to zero.webhook_inbox(psp, event_id)with a primary key on both columns, for deduplication.
Forward-only states:
CREATED -> AUTH_PENDING -> AUTHORIZED | AUTH_FAILED | AUTH_UNKNOWN
AUTH_UNKNOWN -> AUTHORIZED | AUTH_FAILED
AUTHORIZED -> CAPTURED | VOIDED | EXPIRED
CAPTURED -> PARTIALLY_REFUNDED -> REFUNDED
Each transition is a compare-and-set on (state, version) and commits one transaction with: the state update, balanced ledger rows (a capture debits clearing and credits customer liability), the audit/outbox event, and the stored idempotent response. The CHECK constraints are the last line of defense against buggy code or races.
5. Idempotency, timeouts and failover
- Claim the key by inserting it as IN_PROGRESS. Same hash and DONE returns the stored response. Same hash and IN_PROGRESS returns a pending or 409 result. A different hash returns 422.
- Create an attempt with
psp_idem_key = hash(payment_id, op, attempt_no)and pass it to the provider's own idempotency feature, so an internal retry of the same attempt is deduplicated by the provider. - Call the provider with a tight timeout (2-5 s).
A timeout means UNKNOWN, not FAILED. Mark the attempt UNKNOWN and the payment AUTH_UNKNOWN. Do not immediately route to another provider, since the first may have placed a hold and a second authorization would double-hold the customer's funds. A recovery worker queries the provider by idempotency key or reference with backoff. If the provider confirms success, move to AUTHORIZED. If it confirms failure, create attempt 2 on the secondary. If it cannot confirm in a bounded time, issue a void/reversal first, then retry elsewhere.
Immediate failover is safe only when the request provably never left us (connection refused, circuit already open) or the provider returned an explicit pre-processing error or soft decline. Hard declines (insufficient funds, stolen card) are never retried on another provider.
Latency: our own work is about two database round trips plus routing, roughly 20-50 ms, which fits comfortably in the 500 ms p99 budget.
Capture and refund races: serialize on the payment row. A refund first reserves refund_pending_amt in the same transaction, calls the provider, then converts pending to refunded on success or releases it on failure. Concurrent refunds therefore cannot exceed the captured amount.
6. Webhooks and out-of-order events
- Ingest tier (stateless, autoscaled): verify the signature, write the raw event to Kafka keyed by provider reference (so one payment's events stay ordered per partition), return 200 in under 50 ms.
- Processor: insert into
webhook_inbox; a conflict means a duplicate, so stop. Find the attempt by provider reference and apply the event through the same state-machine code as synchronous responses. - Treat events as facts, not commands. If an event is older than the current state (for example "authorized" after "captured"), record it and make no transition. If it arrives before its prerequisite (a capture event before we have seen the authorization), park it and retry with backoff, or fetch the provider's current status and reconcile.
- Webhooks resolve UNKNOWN attempts as well, giving a second path to the same outcome as the recovery worker.
7. Reconciliation, retention, security
- A nightly job compares provider settlement files with ledger totals per provider and currency. Mismatches open tickets, never silent edits; corrections are new compensating ledger entries.
- Audit events are append-only and archived to WORM storage for 7 years.
- Tokenization keeps raw card data out of our systems; secrets and provider credentials live in a managed secret store; webhooks are signature- and replay-protected.
Trade-offs and common mistakes
- Failing over on timeout is the classic double-charge bug.
- Using one idempotency key for both the client request and provider calls makes retries on a second provider impossible to reason about.
- Enforcing invariants only in application code. Keep database constraints as the backstop.
- Processing webhooks in arrival order rather than by state-machine rules.
- Strong consistency across regions costs latency, so pin each payment to a home shard and accept intents anywhere.