Build a Reliable Card Payment Backend with External PSPs
System DesignModel answerLast updated
Design a backend that takes a card payment from checkout through an external processor to a recorded, reconcilable transaction, with no double charges and no lost successes.
Build a Reliable Card Payment Backend
You are designing the payment backend for an online business, such as a marketplace checkout or a usage-based billing product. Customers pay by credit or debit card. Your system does not move money itself. An external payment service provider (PSP) does that, and the card is tokenized on the client side so your servers only ever see an opaque token.
Your backend orchestrates everything from the moment a customer presses Pay until a confirmed transaction is recorded. That means:
- calling the PSP,
- keeping an authoritative internal record of every charge,
- making sure retries never charge a customer twice,
- supporting full and partial refunds,
- reconciling your records against what the PSP says really happened.
Walk through the end-to-end design: the high-level architecture, the core data model, the write and read paths, failure and retry handling, and how the system scales.
Scope and assumptions
State your own numbers if you prefer. A reasonable starting point:
- About 10 million customers. Peak load is around 1,000 payment requests per second, with bursts during sales or billing runs, and a much lower average.
- PSP calls go over HTTPS, have p99 latency in the hundreds of milliseconds, and can time out.
- Correctness matters more than speed. A payment can take a second or two, but it must never be charged twice and a successful charge must never be lost.
- Multiple currencies are supported. Full and partial refunds are required. Chargebacks and disputes can be handled out of band.
- The system must keep an auditable financial record and reconcile against PSP settlement reports.
- Explicitly out of scope: storing card numbers and PCI scope (delegated to the PSP via tokenization), fraud scoring, and tax calculation.
Questions worth raising up front
- Are we handling one-off purchases, subscriptions, metered billing, or payouts to third parties?
- One PSP or several?
- Must the user see a final result synchronously, or is "we'll confirm shortly" acceptable?
- What are the refund, dispute, and reporting needs?
- Are there audit, immutability, retention, or data-residency rules?
What is expected
A structured design that covers the API, data model and state machine, the write path step by step, webhook handling, reconciliation, scaling, and the trade-offs you are making. Pay particular attention to what happens when a PSP call times out or a process crashes midway.
Hints
Hint 1
Rough numbers show that throughput is modest. The difficulty is correctness under partial failure: crashes and timeouts between your database and the PSP. Say this early and design around it.
Hint 2
Use idempotency at every hop: a client-supplied key for client to you, a deterministic key derived from your payment ID for you to PSP, and event-ID dedupe plus monotonic state transitions for PSP to you.
Hint 3
Record the intent (a PROCESSING row) and commit it before calling the PSP, and treat a timeout as 'unknown' rather than 'failed'. A reconciler then resolves unknown payments by querying the PSP.
Hint 4
Model money with integer minor units plus a currency code, and keep an append-only double-entry ledger written in the same transaction as the state change. Fix mistakes with reversing entries, never edits.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Scope and numbers
State the assumptions first: one-time charges, a single PSP behind an adapter (so a second can be added), card tokenization on the client so we only see a payment_method_token, and a synchronous result when possible with an async "processing" fallback.
Back-of-envelope:
- Throughput: peak is 1,000 req/s and the average is perhaps 50 req/s, which is about 4M payments per day.
- Storage: each payment produces one payment row, a few ledger entries, a few events, and one idempotency row, about 2 KB in total. That is roughly 3 TB per year, which a sharded relational database handles comfortably.
- Concurrency: with PSP p99 near 800 ms, about 1,000 calls are in flight at peak. This sizes the worker and connection pools.
The takeaway is that volume is modest and correctness under partial failure is the real problem.
2. API
POST /v1/paymentswith anIdempotency-Keyheader and a body ofcustomer_id,amount_minor,currency,payment_method_token,order_id. It returnspayment_idand a status ofsucceeded,failed,processing, orrequires_action.GET /v1/payments/{id}POST /v1/payments/{id}/refunds(idempotent, optional amount, default full)POST /webhooks/psp(signature-verified)
Amounts are integers in minor units plus an ISO currency code. Never floats.
3. Data model
- idempotency_keys: primary key
(merchant_id, key), plusrequest_hash,payment_id, a response snapshot, and a lock expiry. The unique key makes concurrent duplicates collide in the database. - payments: id, customer, amount (immutable), currency, status, PSP name and reference, a PSP idempotency key, a version counter, and timestamps.
- payment_events: an append-only log of each transition and raw PSP payload. It serves as the audit trail.
- refunds: same shape, linked to a payment. Invariant: the sum of non-failed refunds is at most the captured amount, enforced in the same transaction.
- ledger_entries: double-entry rows with a transaction ID, account, debit or credit, amount, and currency. Each transaction balances to zero per currency. Rows are never updated, and corrections are reversing entries.
- outbox: events to publish, written in the same transaction as the state change.
State machine: CREATED -> PROCESSING -> SUCCEEDED -> (PARTIALLY_)REFUNDED, with branches to FAILED and REQUIRES_ACTION (for example 3-D Secure) which returns to PROCESSING. Transitions are monotonic and applied with compare-and-set (UPDATE ... WHERE status = expected AND version = v).
4. Architecture
Client, then an API gateway (auth, rate limiting), then a stateless Payment Service backed by a sharded Postgres (shard by merchant or customer). A PSP adapter wraps calls with timeouts and a circuit breaker. PSP webhooks enter a signature-verifying ingest, go onto a queue, and are applied by a processor. A reconciler runs as a sweeper plus a daily settlement job. An outbox relay publishes events to a log (Kafka) for fulfillment, email, and analytics.
5. Write path
- Claim the idempotency key. Same key and same hash with a finished request: return the stored response. Same key still in progress: return 409 or "processing". Same key with a different hash: return 422.
- Create the payment as
CREATEDin the same transaction, with the PSP idempotency key set to thepayment_id. - Move to
PROCESSINGand commit before calling the PSP. If we crash afterward, the record exists and the reconciler finds it. - Call the PSP with its idempotency key. A retry of this call cannot produce a second charge.
- Commit the outcome atomically: status, event, ledger entries, outbox row, and idempotency response snapshot.
- On timeout or 5xx, leave it
PROCESSING. Unknown is not failed. Returnprocessing, and let the client poll or receive a push.
Webhooks: verify the signature, dedupe on the PSP event ID, then apply through the same compare-and-set. If the webhook beats the synchronous response, the later writer sees a terminal state and does nothing.
6. Exactly-once effect
Every hop is at-least-once, so we stack dedupe layers: the client key (client to us), the PSP key (us to PSP), and event-ID dedupe with monotonic transitions (PSP to us). Because the ledger write is inside the transition transaction, money is booked exactly once.
7. Reconciliation
- Sweeper (about every 30 s): find payments stuck in
PROCESSINGfor over a minute and query the PSP by reference or key. If the PSP has no record, retry with the same key, which is safe. After a deadline with still no record, mark it failed. If it stays ambiguous, escalate to a human. - Daily settlement job: ingest the PSP settlement file and join it to the ledger on PSP reference. Match amounts and currency, book fees and FX differences, and send mismatches to an exceptions queue. Resolve them with adjusting entries, never edits.
8. Refunds
Lock the payment row, check that the refund fits within the remaining refundable amount, create the refund as pending with its own idempotency key, call the PSP, and on success write reversing ledger entries in one transaction. Partial refunds are just smaller amounts under the same invariant.
9. Scaling and resilience
- The service is stateless and scales horizontally. Shard the database by merchant or customer so a payment and its ledger rows live together.
- Rate-limit and queue during bursts. Use bounded concurrency toward the PSP and a circuit breaker so a PSP outage degrades to "processing" instead of cascading.
- For multiple PSPs, route behind the adapter and persist the chosen PSP on the payment. Never re-route a payment with an unknown outcome until the first PSP's state is resolved, or you risk a double charge.
- Keep read replicas for reporting, but serve status reads for in-flight payments from the primary.
10. Trade-offs and common mistakes
- Marking a timed-out payment as failed, which leads to a retry and a double charge.
- Calling the PSP before durably recording the intent.
- Using floats for money or mutating ledger rows.
- Generating a fresh PSP idempotency key on each retry.
- Updating state and publishing events in separate steps instead of using an outbox.
- Skipping settlement reconciliation and trusting only webhooks.
Synchronous checkout gives better UX but ties latency to the PSP. Returning processing plus push confirmation is more robust at the cost of a more complex client.