{}DSA Atlas

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.

Advanced6 interview questions

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

customer merchant /payment svc PSP /acquirer card network(Visa / MC) issuing bank(customer's) 1. authorise: approve + hold funds (seconds) 2. capture → 3. clearing & settlement (T+1 / T+2) funds move issuer → network → acquirer → merchant, minus interchange + scheme + PSP fees later: refunds, chargebacks (disputes) flow back the same chain
A card payment is a synchronous authorisation followed by asynchronous settlement.

3. API

HTTP
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

checkout payment svcidempotency · FSM risk / fraudscore PSP routeradapters Stripe Adyen payments DB+ outbox event bus ledger svcdouble entry webhookingest order /fulfilment reconciliation(daily files) payouts(batch)
The payment service owns state; the ledger owns money; reconciliation keeps both honest.

5. Deep dives

Payment state machine

created requires_action processing authorized succeeded refunded disputed failed / canceled capture
Only valid forward transitions are applied — duplicate or late webhooks become no-ops.
Python
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 responseMeaningAction
successchargedrecord, publish
definitive declinenot chargedmark failed, show reason
timeout / 5xxunknowndon't mark failed; retry with the same idempotency key or query status; webhook will settle it

Reconciliation

internal ledger PSP settlement file matcherby reference + amount matched ✓ auto-fix rules exceptions → finance ops
Daily three-way matching: your records, the PSP's, and the bank's.

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

DecisionChoice
Storerelational DB with ACID (Postgres/MySQL, sharded by merchant if needed)
Consistencystrong within the payment service; events via outbox to others
Multi-PSProuting for cost/auth-rate/failover vs complexity and vaulting needs
Sync vs asyncsync auth for UX, async webhooks for truth
Money representationinteger minor units + currency, never floats

Interview questions

0 / 6 marked confident

Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.