Interview Study Guide

Guide / System design Most asked

Design: payment system

A payment flow that never double-charges or loses money: payment states, idempotency, double-entry ledger, gateway integration, webhooks, reconciliation, refunds and PCI scope.

Created · Updated · 5 min read

Payments test correctness above all else. The recurring ideas: idempotency, a state machine, an immutable ledger, and reconciliation.

Fundamentals (the design)#

1. Requirements#

Functional: accept payments (cards, UPI, wallets), authorise/capture, refund, payouts to merchants, webhooks to merchants, statements. Non-functional: no double charge, no lost payment, auditability, strong consistency for balances, high availability of checkout, PCI-DSS compliance, latency dominated by the external network (1–3 s).

2. Estimates#

1M transactions/day ≈ 12 TPS average, peak 100–500 TPS. Low QPS but zero tolerance for errors, so favour a relational DB with ACID, not exotic scale tricks. Data retention for years (regulatory), so partition by time.

3. Payment lifecycle (state machine)#

CREATED → PENDING → AUTHORIZED → CAPTURED → SETTLED
             │           │            └→ REFUND_PENDING → REFUNDED
             └→ FAILED   └→ VOIDED / EXPIRED

Only valid transitions are allowed, enforced with conditional updates (UPDATE ... SET status='CAPTURED' WHERE id=? AND status='AUTHORIZED') so two concurrent or repeated requests cannot both succeed.

4. Architecture#

Client → API gateway (auth, rate limit) → Payment API ─► Payment DB (payments, idempotency keys, outbox)
                                              │
                                              ├─► PSP/gateway adapter (Stripe/Razorpay/bank), with circuit breaker and timeouts
                                              ├─► Ledger service (double-entry, append-only)
                                              └─► Outbox → Kafka → webhooks to merchants, notifications, analytics, risk
PSP webhooks → Webhook receiver (verify signature, dedupe by event id) → state machine updates
Reconciliation job: our ledger vs PSP settlement files vs bank statements

5. The create-payment flow#

  1. Client sends POST /payments with Idempotency-Key, amount (minor units), currency, payment method token. Card data never touches your servers: the client SDK sends it to the PSP or a token vault, returning a token (tokenisation keeps you out of most PCI scope).
  2. Insert idempotency key + payment (CREATED) in one transaction.
  3. Run risk checks (velocity, device, amount, 3-D Secure/OTP step-up).
  4. Call the PSP with your idempotency key and a timeout. Set PENDING.
  5. Success → AUTHORIZED/CAPTURED; failure → FAILED with reason; timeout → PENDING_UNKNOWN: never assume failure. Resolve by querying the PSP using your reference or via webhook.
  6. Write ledger entries and an outbox event in the same transaction as the state change.
  7. Return the stored response on retries (Idempotency).

6. Ledger (double entry)#

Every money movement posts two or more immutable entries that sum to zero: debit customer receivable, credit merchant payable, credit fees. Balances are derived (or maintained with a guarded update). Entries are never updated or deleted; corrections are new reversing entries. This gives auditability and makes reconciliation possible. Use NUMERIC/integer minor units, never floats; store currency with every amount.

7. Webhooks and reconciliation#

  • Receiving PSP webhooks: verify HMAC signature and timestamp, dedupe by event ID, process idempotently, tolerate out-of-order events, ack 2xx quickly.
  • Sending merchant webhooks: signed payloads, retries with exponential backoff for days, unique event IDs, a dashboard for replay.
  • Reconciliation (daily/hourly): compare your payments and ledger to PSP reports and bank settlement; flag mismatches (missing, duplicate, amount differences); auto-repair known classes, queue the rest for ops. This is the safety net for everything above.

8. Refunds, chargebacks and payouts#

Refund = new linked transaction, bounded by captured amount (invariant sum(refunds) ≤ captured, enforced in SQL), idempotent per refund request ID. Chargebacks arrive asynchronously from the PSP: freeze funds, collect evidence. Payouts to merchants: batch by schedule, hold for risk, idempotent transfer IDs, retry safely.

9. Failure handling#

PSP down → circuit breaker; route to a secondary PSP where contracts allow (smart routing); queue and show “processing”. DB failover → synchronous replication for the payments DB (RPO ≈ 0). Duplicate submission (double click) → same idempotency key from the client. Partial failure after PSP success but before DB write → the webhook and reconciliation repair state.

Most asked questions#

1. How do you prevent double charges? Idempotency keys at your API and the PSP, a state machine with conditional transitions, webhook dedupe, and reconciliation.

2. What if the PSP call times out? State PENDING_UNKNOWN; look up the status by reference, wait for the webhook, never retry with a new key.

3. How do you store money? Integer minor units plus currency in a double-entry append-only ledger.

4. How do you stay out of PCI scope? Tokenise via the PSP’s hosted fields or SDK; never log or store PAN/CVV; segment networks.

5. What is reconciliation? Comparing internal records to external settlement data to find and fix discrepancies.

6. How do you design refunds? Linked, idempotent transactions bounded by the captured amount, asynchronous status, ledger reversals.

Senior-level questions#

1. “The ledger total does not match the PSP report by ₹12,340.” Find the delta by transaction ID: missing webhook, timeout resolved wrongly, duplicate capture, currency rounding, fee differences, timing cut-off. Add invariants and alerts, and fix the process, not only the data.

2. “Strong consistency or availability for payments?” Consistency for money movement (reject or pend rather than risk wrong state), availability for browsing and checkout UI; degrade by queueing and showing pending status.

3. “Design smart routing across multiple PSPs.” Route by cost, success rate per card BIN/country, and health; retry soft declines on another PSP only if the first definitely did not charge (idempotency and status queries); track per-route metrics.

4. “How do you handle clock and ordering issues in events?” Per-payment sequence/version numbers, state machine guards, ignore stale events, re-fetch authoritative state from the PSP.

5. “How would you scale to 10× TPS?” Shard by merchant or payment ID, partition ledger by time, keep hot-path DB writes minimal, async everything non-critical (webhooks, notifications, analytics), and read from replicas for status pages.

Quiz#

1. Why never mark a payment failed on timeout?

The PSP may have captured the money; marking failed and retrying with a new key can double-charge. Use an unknown state and reconcile.

2. What invariant bounds refunds?

The sum of refunds must not exceed the captured amount, enforced transactionally.

3. Why a double-entry ledger?

Every movement is balanced and immutable, enabling audit, reconciliation and error detection.

4. How do you verify a webhook is genuine?

Check the HMAC signature with the shared secret, validate the timestamp to prevent replay, and dedupe by event ID.

5. Why tokenisation?

Sensitive card data stays with the PSP/vault; your systems handle only tokens, reducing PCI scope and breach impact.

Finished this page?Mark it done to track your progress across the guide.
Pritam Ghosh · System design & AI engineering study notes