Case study: Payment system

Topic 14 of 15 in Week 7: Classic case studies15 min readAdvancedFree course

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

Text
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

Text
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

Text
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_at

5. High-level design

Payment system design. Checkout for order 981 calls the payment service with an idempotency key. The payment service calls a payment service provider such as Stripe or Razorpay, which talks to card networks. The payment service records state per attempt in a payments database, which writes double-entry records to an append-only ledger. The provider reports asynchronous results to a webhook handler, which verifies signatures, deduplicates and updates the payments database. A daily reconciliation job compares records with the provider’s report. Raw card numbers are never stored; the provider tokenises them, and money is stored as integer minor units plus a currency code. If the outcome is unknown, for example after a timeout, the payment stays pending and is resolved by webhook, status query or reconciliation.

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

Payment state machine. A payment moves from CREATED to PENDING when it is sent to the provider, then to SUCCEEDED when captured, and optionally to REFUNDED, fully or partially. From PENDING it can move to FAILED when declined or timed out, after which a retry creates a new attempt. Each transition writes a ledger entry and an outbox event such as PaymentSucceeded in one transaction.

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:

  1. the PSP’s webhook (most PSPs report the final result asynchronously),
  2. polling the PSP’s status API for pending payments after a delay,
  3. 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:

Text
debit  psp_receivable           2,499.00
credit seller_payable:s17       2,249.10
credit platform_revenue           249.90

Rules: 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.

Exercise

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.

Text
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:

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.