Design a Checkout-to-PSP Payment Gateway
System DesignModel answerLast updated
Design a fault-tolerant intermediary service that processes charge requests from sellers, coordinates with an external payment provider, and maintains a consistent transaction ledger.
Context
You're building the payment backbone for a multi-merchant e-commerce platform. When a buyer clicks "Pay", the platform needs to forward the charge to an external Payment Service Provider (PSP), track what happened, and make sure the seller's ledger stays accurate — even when the network misbehaves or your service crashes mid-request.
What You're Designing
A payment gateway service that sits between merchant backends and a third-party PSP. It is responsible for accepting charge requests, orchestrating calls to the PSP, and persisting a reliable record of every transaction's lifecycle.
Functional Requirements
- Charge initiation: Accept authorize and capture requests for a given amount and currency from merchant systems.
- No double charges: If a merchant retries a request because of a timeout, the buyer must never be charged twice.
- Crash safety: If the service dies after forwarding a charge to the PSP but before writing the result locally, the system must recover to a correct state on its own.
Non-Functional Requirements
- Strong consistency for financial records — no dirty reads, no lost updates.
- Graceful degradation when the PSP is slow or temporarily unreachable.
- Throughput target: sustain 1,000 transactions per second (TPS), with headroom for 3–5× spikes.
Deliverables
Work through all four of these:
- API surface — what endpoints do merchants call, and what do the requests and responses look like?
- Data model — what tables or collections do you need to track transaction state, guard against duplicate processing, and maintain an append-only ledger?
- Failure handling — walk through what happens when the PSP times out or returns a 5xx. How does the system recover without human intervention?
- Reconciliation — if your local records and the PSP's records diverge (e.g., after a prolonged outage), how do you detect and resolve the gap?
A strong answer discusses trade-offs, names specific failure modes, and explains why each design choice prevents a specific class of bug.
Hints
Hint 1
Before calling the PSP, write your intent to the database first. This gives you something to recover from if the service crashes mid-flight — think about what a background worker needs to find in order to figure out what happened and finish the job.
Hint 2
The PSP is an external side effect you cannot roll back. The key insight is that every call to the PSP should carry a stable, deterministic idempotency key derived from your internal attempt record — so retrying the same call is always safe, whether your service or the PSP is the one retrying.
Hint 3
A transaction's outcome is not always known immediately. 'PENDING' is a valid and honest state to return to the merchant. Design your state machine so a late webhook or recovery worker can only move a payment forward, never backward into a state it already left.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge here is not throughput — it is correctness in the presence of partial failures. Any time you call an external system that moves money, there is a window where your service can die after the side effect happened but before you recorded it. The entire design is built to close that window.
1. Scope and Scale Assumptions
State these upfront to anchor the design:
- Flow: two-step authorize-then-capture, plus a combined "sale" mode. Refunds are in scope but lower priority.
- PSP assumptions: the PSP supports its own idempotency key on every write endpoint, and exposes a
GET /charges?reference=<your-id>lookup. It also sends webhooks. Confirm these with your interviewer — the recovery strategy depends on both. - Volume math: 1,000 TPS × ~4 writes per transaction = ~4,000 writes/second steady, ~20,000/second at peak. At roughly 1 KB per transaction, that's around 90 GB/day and ~30 TB/year. Plan for time-based partitioning and cold archival.
- Money rule: amounts are always integers in minor units (cents, pence, etc.). Never floats.
2. API Design
POST /v1/payments
Headers: Idempotency-Key: <client-generated UUID>
Body: { merchant_id, amount, currency, payment_method_token,
capture: "automatic" | "manual", metadata }
→ 201 { payment_id, status: "AUTHORIZED" | "PENDING" | "FAILED" }
POST /v1/payments/{payment_id}/capture
Headers: Idempotency-Key
Body: { amount? } (optional partial capture)
POST /v1/payments/{payment_id}/refunds
Headers: Idempotency-Key
Body: { amount }
GET /v1/payments/{payment_id}
Outbound webhook → merchant:
payment.authorized | payment.captured | payment.failed
PENDING is a first-class response, not an error. If the PSP times out, the honest answer to the merchant is "we don't know yet." Returning a fake FAILED would cause the merchant to retry and risk a double charge; returning a fake AUTHORIZED would be a lie.
3. Data Model
Use a relational, ACID-compliant store (Postgres is the natural fit). Shard by merchant_id if volume demands it.
-- Guards against duplicate requests from the same merchant
idempotency_keys (
merchant_id, idem_key,
request_hash, -- hash of the full request body
payment_id,
response_code, response_body,
locked_until, -- prevents racing concurrent requests
PRIMARY KEY (merchant_id, idem_key)
)
-- One row per logical payment
payments (
payment_id PK, merchant_id, amount, currency,
status, -- CREATED | PENDING | AUTHORIZED | CAPTURED | FAILED | REFUNDED
authorized_amount, captured_amount, refunded_amount,
psp_reference, -- PSP's own ID, null until known
version, -- optimistic lock counter
next_check_at, -- when the recovery worker should poll
created_at, updated_at
)
-- One row per PSP call (auth, capture, refund)
payment_attempts (
attempt_id PK, payment_id, operation,
psp_idempotency_key UNIQUE, -- = attempt_id, sent to PSP
status, -- IN_FLIGHT | SUCCEEDED | FAILED | TIMED_OUT
psp_response,
created_at
)
-- Append-only double-entry ledger; never UPDATE these rows
ledger_entries (
entry_id PK, payment_id, account,
direction, amount, currency, created_at
)
-- Transactional outbox for merchant webhooks and analytics events
outbox (
event_id PK, aggregate_id, event_type, payload, published_at
)
The split between payments and payment_attempts is deliberate: the business object and the PSP side-effects are tracked separately. This makes it straightforward to replay or inspect any individual PSP call without mutating the payment record.
4. Core Request Workflow
Step 1 — Idempotency check.
Attempt INSERT into idempotency_keys.
- Conflict, record complete: if
request_hashdiffers, return 422 (key reused with a different body). If it matches, replay the stored response. - Conflict, still locked: return 409 or wait briefly and replay once the lock expires.
Step 2 — Persist intent (one DB transaction).
Create the payments row (CREATED), the payment_attempts row (IN_FLIGHT), and link the idempotency key. Commit. The service can crash any time after this and the recovery worker will find the row.
Step 3 — Call the PSP.
Send attempt_id as both your internal reference and the PSP's idempotency key. This means every retry of this call — whether from your service or the PSP's own retry — lands on the same PSP-side operation.
Step 4 — Record the outcome (one DB transaction).
Update the attempt status, advance the payment state with a compare-and-set on version, write ledger entries, and insert an outbox event. The state guard:
UPDATE payments
SET status = 'AUTHORIZED', version = version + 1
WHERE payment_id = ?
AND status IN ('CREATED', 'PENDING')
AND version = ?
This means a late or duplicate webhook can never move a CAPTURED payment backward.
Step 5 — On timeout or 5xx.
Set the payment to PENDING, populate next_check_at, and return PENDING to the merchant. A background recovery worker handles resolution.
5. Recovery Worker
The worker polls for attempts stuck IN_FLIGHT or PENDING past their next_check_at. For each one:
- Call
GET /charges?reference=<attempt_id>on the PSP. - If the PSP has a record, apply its state locally through the normal state machine.
- If the PSP has no record at all (the original call never arrived), retry the original call with the same
psp_idempotency_key. - After N failed retries within the maximum window, escalate to
FAILEDand queue for manual review.
Workers claim rows with SELECT ... FOR UPDATE SKIP LOCKED to avoid stepping on each other.
Retry policy for PSP calls: exponential backoff with jitter, retrying only on timeouts and 5xx responses. Never retry a definitive decline (402, 4xx). Use a per-PSP circuit breaker to shed load during outages.
6. Architecture Overview
Merchant → API Gateway (auth, rate limit)
→ Payment API (stateless, async I/O)
→ Postgres
→ PSP client (circuit breaker, timeouts)
Outbox relay (CDC / polling) → Kafka → webhooks, analytics
Recovery workers (poll PENDING / IN_FLIGHT)
PSP webhook receiver (verify sig, deduplicate, apply state)
Reconciliation job (nightly settlement file comparison)
At 1,000 TPS with ~1 s of PSP latency, you need roughly 1,000 concurrent in-flight PSP connections. Async I/O across 10–20 stateless API instances handles this comfortably.
The outbox pattern is essential: writing the Kafka event inside the same DB transaction as the state change guarantees exactly-once delivery semantics. A direct dual-write to both the DB and Kafka would introduce a gap where the state changed but the webhook never fired (or the webhook fired but the DB write failed).
7. Reconciliation
Three layers, from fastest to most authoritative:
- Near-real-time: incoming PSP webhooks. Verify the signature, deduplicate by PSP event ID, and apply through the state machine.
- Short-lag: the recovery worker catches anything the webhooks missed within minutes.
- Authoritative: nightly settlement file from the PSP. Diff it against your ledger. Flag mismatches — a charge the PSP shows but your DB does not is the most dangerous case and triggers an alert and manual review.
Common Mistakes to Avoid
- Calling the PSP inside a DB transaction. A long-running DB transaction held open while waiting for a 1–2 s PSP response will exhaust your connection pool under any real load.
- Using the merchant's idempotency key directly as the PSP's idempotency key. These are different scopes; use your internal
attempt_idso retry logic is fully under your control. - Treating PENDING as an error state. It is a legitimate outcome that requires follow-up, not an exception to handle and discard.
- Mutable ledger rows. If you ever
UPDATEa ledger entry rather than appending a correcting entry, you lose your audit trail and make reconciliation much harder.