Design a Payment System (Stripe / PayPal checkout)
Moving money correctly — the payment lifecycle (authorise, capture, refund), integrating payment service providers and card networks, idempotency end to end, double-entry ledgers, the payment state machine, webhooks and asynchronous outcomes, reconciliation with settlement files, retries without double charging, PCI scope reduction, fraud checks, and payouts.
1. Requirements
Functional
- Accept payments for orders (cards, wallets, bank transfers) via one or more PSPs.
- Authorise, capture, void, refund (full/partial); handle disputes/chargebacks.
- Pay out merchants/sellers (marketplace) on a schedule.
- Ledger of all money movements; reporting.
Non-functional
- Correctness above all: no double charges, no lost money, exact accounting.
- Auditability; compliance (PCI DSS, KYC/AML for payouts).
- High availability for checkout; latency matters less than correctness (seconds acceptable).
- Moderate throughput: e.g., 1,000–10,000 payments/s at peak for a large platform.
2. Payment lifecycle
3. API
POST /v1/payments
Idempotency-Key: 7c1d8f4e-… # one per checkout attempt
{
"order_id": "ord_981",
"amount": {"value": 4999, "currency": "USD"},
"payment_method": "pm_tok_123", # token from PSP hosted fields
"capture": "automatic"
}
201 {"id": "pay_01J…", "status": "requires_action", "next_action": {"type": "3ds_redirect", "url": "…"}}
POST /v1/payments/{id}/capture {"amount": 4999}
POST /v1/payments/{id}/refunds {"amount": 1000, "reason": "requested_by_customer"} Idempotency-Key: …
POST /webhooks/psp (signed events from the PSP)
4. High-level design
5. Deep dives
Payment state machine
TRANSITIONS = {
"created": {"requires_action", "processing", "authorized", "failed"},
"requires_action": {"processing", "authorized", "failed", "canceled"},
"processing": {"authorized", "succeeded", "failed"},
"authorized": {"succeeded", "canceled"},
"succeeded": {"partially_refunded", "refunded", "disputed"},
"partially_refunded": {"partially_refunded", "refunded", "disputed"},
}
def apply_event(payment_id, new_status, event_id):
with db.transaction():
if db.exists("processed_events", event_id): # idempotent webhook handling
return
p = db.select_for_update("payments", payment_id)
if new_status not in TRANSITIONS.get(p.status, set()):
log.info("ignored transition %s -> %s", p.status, new_status) # late / out of order
else:
db.update("payments", payment_id, status=new_status, version=p.version + 1)
db.insert("outbox", {"type": f"payment.{new_status}", "payment_id": payment_id})
db.insert("processed_events", {"id": event_id})
The ledger
Transaction T-981 (charge order ord_981, $49.99, fee $1.75)
DEBIT psp_clearing:stripe 4999
CREDIT merchant_payable:m_42 4824
CREDIT revenue:processing_fees 175
-------------------------------------
sum 0 ✓ must always be zero
Transaction T-1203 (refund $10.00)
DEBIT merchant_payable:m_42 1000
CREDIT psp_clearing:stripe 1000
CREATE TABLE ledger_entries (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
transaction_id UUID NOT NULL,
account_id TEXT NOT NULL,
direction CHAR(1) NOT NULL CHECK (direction IN ('D','C')),
amount_minor BIGINT NOT NULL CHECK (amount_minor > 0),
currency CHAR(3) NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- invariant check (run continuously): every transaction balances
SELECT transaction_id
FROM ledger_entries
GROUP BY transaction_id, currency
HAVING SUM(CASE direction WHEN 'D' THEN amount_minor ELSE -amount_minor END) <> 0;
Handling timeouts with the PSP
| PSP response | Meaning | Action |
|---|---|---|
| success | charged | record, publish |
| definitive decline | not charged | mark failed, show reason |
| timeout / 5xx | unknown | don't mark failed; retry with the same idempotency key or query status; webhook will settle it |
Reconciliation
Fraud and risk
A risk service scores each payment synchronously (rules + ML on velocity, device, IP, BIN country vs shipping country, amount anomalies) → allow, require 3-D Secure (step-up), review, or block. Chargebacks feed back as labels.
6. Trade-offs
| Decision | Choice |
|---|---|
| Store | relational DB with ACID (Postgres/MySQL, sharded by merchant if needed) |
| Consistency | strong within the payment service; events via outbox to others |
| Multi-PSP | routing for cost/auth-rate/failover vs complexity and vaulting needs |
| Sync vs async | sync auth for UX, async webhooks for truth |
| Money representation | integer minor units + currency, never floats |
Interview questions
Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.