Case study: Payment system
Overview
Payments are where “eventually it’ll be fine” isn’t good enough. Charging twice, losing a payment or miscounting a seller’s balance costs real money and trust. The scale is usually modest; the challenge is correctness under failure: timeouts, retries, duplicate webhooks and partial outages.
Try the exercise first: 45 minutes, then compare.
1. Requirements
Functional
- Accept customer payments for orders via cards, UPI and wallets through a payment service provider (PSP) such as Stripe, Razorpay or Adyen.
- Refunds (full and partial).
- Track seller balances (minus commission) and pay sellers out weekly.
- Payment history and status for customers, sellers and finance.
Non-functional
- Exactly-once effect: never charge twice, never lose a payment.
- Auditable: every money movement traceable; nothing silently edited.
- Secure and compliant (PCI DSS scope minimised, data protection).
- Highly available for checkout, but correctness wins over availability.
2. Estimates
payments : 1M / day ≈ 12 / s average, peaks ~100 / s during sales
ledger : ~4 entries per payment → 4M rows / day ≈ 1.5B / year (fine for a sharded or well-partitioned relational DB)3. API
POST /v1/payments
Idempotency-Key: order-981
{"order_id": "981", "amount": 249900, "currency": "INR", "method_token": "tok_…"}
→ 201 {"payment_id": "pay_…", "status": "pending" | "succeeded" | "requires_action"}
GET /v1/payments/{id}
POST /v1/payments/{id}/refunds Idempotency-Key: refund-981-1 {"amount": 50000}
POST /webhooks/psp (from the PSP, signed)Amounts are integers in minor units (paise), always with a currency.
4. Data model
payments: payment_id | order_id | idempotency_key (unique) | amount | currency
status | psp_reference | created_at | updated_at
payment_events: payment_id | from_status | to_status | reason | at (append-only)
ledger_entries: entry_id | transaction_id | account | debit | credit | currency | created_at
(each transaction's debits = credits)
accounts: customer_clearing, platform_revenue, seller_payable:{seller_id}, psp_receivable, …
webhook_events: psp_event_id (unique) | payload | processed_at5. High-level design
6. Deep dives
Idempotency end to end
- The client sends an
Idempotency-Key(the order ID). The payment service stores it with a unique constraint; a repeated request returns the stored result instead of creating a new payment. - The service passes an idempotency key to the PSP too, so a retried PSP call after a timeout doesn’t create a second charge.
- Webhooks are deduplicated by the PSP’s event ID.
The payment state machine
Each transition is a conditional update (“from pending to succeeded”) recorded in payment_events; illegal transitions are rejected. Together with a ledger entry and an outbox event, each transition is written in one database transaction, so state, money records and notifications never disagree.
Unknown outcomes
If the PSP call times out, the payment stays PENDING: you don’t know whether the customer was charged. Resolve it by:
- the PSP’s webhook (most PSPs report the final result asynchronously),
- polling the PSP’s status API for pending payments after a delay,
- daily reconciliation.
Show the customer “payment processing” rather than an error that tempts them to pay again.
The double-entry ledger
Every money movement is recorded as a transaction of entries that balance (total debits = total credits). For a ₹2,499 order with 10% commission:
debit psp_receivable 2,499.00
credit seller_payable:s17 2,249.10
credit platform_revenue 249.90Rules: entries are append-only (corrections are new reversing entries, never edits), balances are derived by summing entries (cached if needed), and every entry links to the payment, refund or payout that caused it. This makes the books auditable and errors detectable: if the ledger doesn’t balance, something is wrong.
Reconciliation
Once a day, download the PSP’s settlement report and compare it line by line with internal records: payments, refunds, fees and payouts. Mismatches (a webhook was missed, a refund failed, a fee differs) create alerts and correction workflows. Reconciliation is the safety net that catches everything the real-time path missed.
Payouts
A weekly batch computes each seller’s payable balance from the ledger and creates payouts through the PSP or bank APIs, idempotent per seller and period, recording ledger entries for each.
Security and compliance
Use the PSP’s hosted fields or SDKs so card numbers go directly to the PSP and you only see tokens; this keeps you mostly out of PCI DSS scope. Encrypt sensitive data, restrict access, keep audit logs and verify webhook signatures.
7. Trade-offs and bottlenecks
- Strong consistency and transactions over raw throughput: a well-run relational database is the right default.
- The PSP is a critical external dependency: timeouts, circuit breakers, and potentially a second PSP for failover.
- Every shortcut (editing a row, skipping the ledger for “simple” cases) eventually becomes an incident.
8. Follow-up questions
- Multiple currencies? Ledger entries per currency; FX conversions as explicit transactions.
- Fraud? A risk check before authorisation (rules plus ML scores), with step-up authentication (3-D Secure).
- Split payments to several sellers in one order? One payment, multiple ledger credits per seller.
Recap
A payment system prioritises correctness: idempotency keys from client to PSP, an explicit state machine with recorded transitions, and a double-entry, append-only ledger written in the same transaction as each state change. Unknown outcomes stay pending until webhooks, polling or reconciliation resolve them; daily reconciliation catches anything missed; and PSP tokenisation keeps card data out of your systems.
Design it yourself (45 minutes)
Set a 45-minute timer and design the payment system for an e-commerce marketplace: customers pay by card or UPI through an external payment service provider (PSP); the marketplace keeps a commission and pays sellers weekly; refunds are supported; 1 million payments per day. The system must never charge twice, never lose money and be auditable. Use the framework, then compare.
1. Clarifying questions:
2. Functional requirements:
3. Non-functional requirements:
4. Estimates:
5. API:
6. Data model (payments, ledger):
7. High-level design:
8. Deep dives (idempotency, states, ledger, webhooks, reconciliation):
9. Trade-offs and bottlenecks:A strong answer covers:
- Estimates: 1M/day ≈ 12/s avg (peaks ~100/s); correctness matters far more than scale.
- Payment service: creates a payment with an idempotency key (order ID); calls the PSP
with the same key; never stores raw card data (PSP tokenisation / hosted fields).
- Explicit state machine: created → pending → succeeded / failed → refunded; each
transition recorded (append-only), with outbox events.
- Ledger: double-entry, append-only; every payment = balanced entries (customer →
platform clearing → seller payable + commission revenue); balances derived from entries.
- Async results: PSP webhooks (verify signature, dedupe by event ID) + status polling for
pending payments.
- Reconciliation: daily compare internal records with PSP settlement reports; flag and
fix mismatches.
- Payouts: weekly batch from seller balances, idempotent per seller-period.
- Strongly consistent relational DB; money as integers + currency; audit logs; PCI scope minimised.Summary
- Correctness dominates: every request is idempotent, every state transition explicit and recorded.
- Never handle raw card data yourself: use a PSP's tokenisation to minimise PCI scope.
- A double-entry, append-only ledger records every money movement as balanced entries; balances are derived.
- Handle asynchronous outcomes with signed webhooks, status polling and a PENDING state for unknown results.
- Reconcile daily against the PSP's reports to catch anything the online path missed.