Design a Payment Processing Service with an External PSP
System DesignModel answerLast updated
Design a backend payment service that collects money via a third-party payment provider, guarantees exactly-once charging, and maintains an auditable money ledger.
The Problem
Your company's product services — checkout, billing, subscriptions — need a single internal service to handle collecting money from customers. Build the backend payment service that sits between those product services and an external Payment Service Provider (PSP).
The PSP handles raw card and bank data. Your system stores only the tokens and references the PSP hands back.
Core Operations
- Charge: a calling service requests that a specific amount and currency be collected from a customer, tied to an order or invoice.
- Settlement: the PSP communicates the final result either synchronously in its response or asynchronously via a webhook.
- Refund: a settled charge may be reversed, fully or partially.
- Lookup: internal services and support tooling can retrieve the current state and full history of any payment.
Hard Requirements
- A customer must never be billed twice for the same order, even if the caller, your service, or the PSP retries the request.
- All monetary values must be represented exactly — no floating-point rounding anywhere on the money path.
- Every state change must be durably recorded and auditable after the fact.
Clarifying Questions to Raise
Before diving into the design, a strong candidate would ask:
- Is this for one internal product or a multi-tenant merchant platform?
- What charge patterns are needed — one-time, recurring, usage-based, or mixed?
- What are the expected peak transaction rates, and which currencies and regions must be covered?
- Does the customer wait synchronously for a payment result (checkout screen), or is async completion acceptable?
- Does the system only collect money, or does it also need to pay out (to sellers, partners, etc.)?
- Is there one PSP or multiple, with routing or failover logic?
Work through these with your interviewer before committing to scope. The design below assumes one company's product, a mix of one-time and recurring charges, a single primary PSP, and a peak load in the low thousands of transactions per second.
Hints
Hint 1
Start by drawing the payment state machine explicitly — list every state a payment can be in and every transition. The tricky one is the 'outcome unknown' state you land in when a PSP call times out without a response.
Hint 2
Exactly-once charging requires idempotency at three independent layers: the API your callers hit, the internal workflow that drives the charge, and the request your service makes to the PSP. Think about what idempotency key you use at each layer and where it's stored.
Hint 3
Don't conflate the payment record with the ledger. The payment record tracks what happened operationally; the ledger records money movement in double-entry form. Reconciliation means comparing your ledger entries against the PSP's settlement reports — think about what discrepancies can arise and how you detect them.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Framing and Priorities
State this up front: correctness beats throughput. A payment system that double-charges or loses a transaction is broken in a way that's hard to recover from. Design for durability and exactly-once semantics first; scale the happy path afterward.
Payment State Machine
Every payment moves through a defined set of states. Skipping this step leads to vague failure handling later.
CREATED → PENDING_PSP → AUTHORIZED → CAPTURED → REFUNDED (partial or full)
↘ FAILED
↘ OUTCOME_UNKNOWN ← timeout with no response
↓
(poller resolves to CAPTURED or FAILED)
OUTCOME_UNKNOWN is the state you land in when your HTTP call to the PSP times out before you get a response. The charge may or may not have gone through on their side. This state drives the reconciliation loop described below.
API Design
POST /payments
{
"idempotency_key": "order_789_charge", // caller-generated, stable per order
"customer_id": "cust_123",
"psp_token": "tok_abc",
"amount_minor_units": 4999, // cents, pence, etc. — never floats
"currency": "USD",
"reference_id": "order_789"
}
GET /payments/{payment_id}
GET /payments/{payment_id}/history
POST /payments/{payment_id}/refund
POST /webhooks/psp // inbound PSP callbacks
Amounts are always integers in the smallest currency unit (cents, pence). Never use float or decimal types that can accumulate rounding error; use BIGINT in the database.
Exactly-Once Charging: Three Layers
Layer 1 — API idempotency. The caller supplies an idempotency_key. On receipt, your service does an upsert: if a payment record with that key already exists, return the existing record immediately without touching the PSP. Store idempotency keys in a table with a unique constraint; handle the race with a database-level lock or INSERT ... ON CONFLICT DO NOTHING.
Layer 2 — Workflow durability. Use a transactional outbox or a workflow engine (Temporal, Step Functions). The state transition and the outbound PSP call are decoupled: write the new state to the DB first, then dispatch the PSP call. If the worker crashes mid-flight, the poller retries from the last durable state rather than re-running the whole charge.
Layer 3 — PSP idempotency key. Pass your internal payment ID as the idempotency key on every PSP API call. A well-designed PSP (Stripe, Adyen) deduplicates on this key server-side, so retrying after a timeout doesn't double-charge.
Data Model (simplified)
payments (
id UUID PRIMARY KEY,
idempotency_key TEXT UNIQUE NOT NULL,
customer_id UUID NOT NULL,
psp_token TEXT NOT NULL,
amount BIGINT NOT NULL, -- minor units
currency CHAR(3) NOT NULL,
status TEXT NOT NULL,
psp_reference TEXT,
created_at TIMESTAMPTZ NOT NULL,
updated_at TIMESTAMPTZ NOT NULL
)
payment_events (
id UUID PRIMARY KEY,
payment_id UUID REFERENCES payments(id),
event_type TEXT NOT NULL,
payload JSONB,
occurred_at TIMESTAMPTZ NOT NULL
)
ledger_entries (
id UUID PRIMARY KEY,
payment_id UUID REFERENCES payments(id),
direction TEXT NOT NULL, -- DEBIT | CREDIT
account TEXT NOT NULL,
amount BIGINT NOT NULL,
currency CHAR(3) NOT NULL,
created_at TIMESTAMPTZ NOT NULL
)
payment_events is append-only — never update or delete rows. ledger_entries implements double-entry bookkeeping: a captured payment creates a DEBIT to receivables and a CREDIT to the customer account. Every entry has a corresponding contra-entry; if they don't balance, something is wrong.
Completion Paths
Synchronous: the PSP responds before your timeout. Transition the payment to CAPTURED or FAILED, write ledger entries in the same DB transaction, return the result.
Webhook-driven: the PSP calls POST /webhooks/psp after the fact. Verify the webhook signature immediately. Then treat it as an event: write to payment_events, transition the payment state, and write ledger entries. Webhooks can arrive out of order or more than once — make state transitions idempotent (ignore a CAPTURED event if the payment is already CAPTURED; reject events that would move backwards through the state machine).
Timeout / OUTCOME_UNKNOWN: a background poller queries the PSP's status API for all payments in this state. The PSP's response resolves the state. This poller should run every few minutes and page through stuck payments.
Reconciliation
Nightly (or more frequently), pull the PSP's settlement report and compare it line-by-line against your ledger:
- PSP shows charged, ledger shows captured → OK
- PSP shows charged, ledger shows
OUTCOME_UNKNOWN→ resolve and write the ledger entry - PSP shows charged, your system has no record → alert, investigate for double-charge
- Your ledger shows captured, PSP shows no record → alert, possible fraud or integration bug
Automate the matched cases; route unmatched rows to a human review queue.
Common Mistakes to Avoid
- Using floats for money. Always integers in minor units.
- Skipping the
OUTCOME_UNKNOWNstate. Treating a timeout as a failure and retrying without a PSP-side idempotency key is the most common double-charge path. - Mutable payment records. If you overwrite state in place with no history, you can't audit or debug after the fact.
- Trusting webhooks without signature verification. An unauthenticated webhook endpoint is an easy attack surface.
- No reconciliation loop. The system will drift from PSP reality over time without it; you won't know until a customer complains.
Key Metrics
- Payment success rate, broken out by PSP response code
- Percentage of payments in
OUTCOME_UNKNOWNat any given time - Reconciliation mismatch count per settlement cycle
- Webhook processing lag (time from PSP delivery to your state update)
- End-to-end latency for the synchronous charge path (p50, p99)