Skip to content

Lesson 29 of 38Case studies

Design a Payment System

Design checkout payments with a provider, webhooks, idempotency keys, a double-entry ledger, and nightly reconciliation.

22 min read0/4 questions

In most systems a bug means a broken page. In payments it means charging someone twice, or shipping goods nobody paid for, and the customer remembers. Payment systems are where "retry until it works" becomes dangerous and where "exactly once" turns out to be a careful illusion. Interviewers at any company that takes money love this question.

Requirements

Functional

  • A customer pays for an order by card at checkout.
  • Payments can be authorized (money held), captured (money taken), and refunded.
  • The merchant (us) sees an accurate balance and a history of every money movement.
  • Orders are fulfilled only after payment succeeds.

Non-functional

  • Never charge twice for the same order, even with retries, timeouts, and crashes.
  • Never lose a payment: every cent is accounted for, and the books always balance.
  • Correctness over latency and over availability: it is better to fail a checkout than to record money wrongly.
  • Keep card numbers out of our systems (PCI DSS compliance is expensive).

Out of scope: building a card network or acquiring bank (we use a payment provider like Stripe or Adyen), fraud models, currency conversion, payouts to sellers.

Back-of-the-envelope numbers

QuantityMathResult
Orders10M a day / 86,400about 115 payments/s (peak 10x on sale days)
Ledger entriesabout 4 per payment (auth, capture, fee, settlement)about 40M rows a day
Ledger storage40M × 200 bytes × 365about 3 TB a year, kept for 7+ years

The throughput is modest. A well-indexed Postgres primary handles it. The hard part is not scale, it is correctness under failure.

How a card payment flows

Most companies never talk to Visa directly. A payment service provider (PSP) like Stripe sits between you and the card networks. Step through a typical flow:

Card payment with a PSP
BrowserOur serverPSPCard networkcard details (hosted fields)POST /payments {order, token}create + confirm paymentauthorizeapprovedstatus: processing / succeededwebhook: payment_intent.succeededorder confirmed

The card form is served by the PSP (an iframe or SDK). The card number goes straight to the PSP, never to us. We get back a token like pm_1Q2w.

1/8
Quick check
The API call to the PSP timed out after 30 seconds. Did the customer get charged?
Need a nudge? A hint rules out a wrong answer.

API

POST /v1/payments
Idempotency-Key: 6f1c2e0a-order-8812
{ "order_id": "o_8812", "amount": 4999, "currency": "usd", "payment_method": "pm_1Q2w" }
 
200 OK
{ "payment_id": "pay_771", "status": "authorized" }
 
POST /v1/payments/pay_771/capture
POST /v1/payments/pay_771/refunds   { "amount": 1000 }
POST /webhooks/psp                  (called by the PSP, signature checked)
GET  /v1/payments/pay_771

Amounts are integers in the smallest unit (cents). Floating point cannot represent 0.1 exactly, and money math must be exact.

Data model

payments (payment_id PK, order_id UNIQUE, amount, currency, status, psp_ref, created_at, updated_at)
idempotency_keys (key PK, request_hash, response, status, created_at)  -- kept 24h+
ledger_entries (entry_id PK, txn_id, account, debit, credit, currency, created_at)  -- append-only
webhook_events (psp_event_id PK, type, payload, processed_at)            -- dedupes webhooks

order_id UNIQUE is a second line of defence: even with a bug in idempotency, the database refuses a second payment for the same order. webhook_events uses the PSP's event ID as its primary key so a redelivered webhook is detected.

High-level design

Payment system
Async processingCheckoutCheckoutOrders APIOrders APIPayment svcPayment svcIdempotency: keysIdempotencykeysPSP: Stripe-likePSPStripe-likeLedger: PostgresLedgerPostgresWebhooksWebhooksEventsEventsFulfilmentFulfilmentReconcile: nightlyReconcilenightlySettlement: PSP reportSettlementPSP reportcard → tokenpaychargewebhook

Tokenize. Card details go from the browser straight to the PSP, which returns a token. Our servers never touch a card number.

1/9

Deep dive 1: idempotency keys

An operation is idempotent if doing it twice has the same effect as doing it once. A charge is not naturally idempotent, so we make it one: the client generates a unique key per logical payment (often derived from the order ID) and sends it with every retry. The server stores the first result under that key and replays it for any repeat.

Run this. The network "loses" the first response, the client retries, and the customer is still charged once.

Pythonidempotency.py
import random class PaymentServer: def __init__(self): self.charges = [] # what the bank actually did self.responses = {} # idempotency key -> stored response def charge(self, key, order_id, amount): if key in self.responses: # seen it: replay, do nothing new return self.responses[key] self.charges.append((order_id, amount)) # the real side effect resp = {"status": "succeeded", "charge_no": len(self.charges)} self.responses[key] = resp return resp def flaky_call(server, key, order_id, amount, lose_response): resp = server.charge(key, order_id, amount) if lose_response: raise TimeoutError("response lost on the way back") return resp server = PaymentServer()key = "order-8812"for attempt in range(1, 4): try: resp = flaky_call(server, key, "o_8812", 4999, lose_response=(attempt == 1)) print(f"attempt {attempt}: {resp}") break except TimeoutError as e: print(f"attempt {attempt}: {e}, retrying with the SAME key") print("bank charges:", server.charges) # Without a stable key, every retry looks like a new payment:naive = PaymentServer()for attempt in range(1, 3): naive.charge(f"random-{random.random()}", "o_8812", 4999)print("naive charges:", naive.charges)
Output
Press Run (⌘ Enter) to see what happens.

In production the key store is a database table, and the hard case is two requests with the same key at the same time. Claim the key atomically first (INSERT ... ON CONFLICT DO NOTHING with status in_progress); the loser gets 409 Conflict and retries later. Also store a hash of the request body: the same key with a different amount is a client bug and should be rejected.

Put it in order5 steps

Order the server's handling of a request with an Idempotency-Key.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Deep dive 2: the double-entry ledger

A balance column that you add to and subtract from is a trap: one bug or race and the number is wrong forever, with no history of why. Accountants solved this 500 years ago with double-entry bookkeeping: every transaction is recorded as at least two entries, debits on some accounts and credits on others, and debits always equal credits. Balances are never stored as the truth; they are derived by summing entries.

A $49.99 sale, a $1.75 PSP fee, and a $10 refund look like this:

txnaccountdebitcredit
t1 salepsp_receivable4999
t1 salerevenue4999
t2 feefees_expense175
t2 feepsp_receivable175
t3 refundrevenue1000
t3 refundpsp_receivable1000

Entries are append-only. A mistake is never edited; it is fixed with a new reversing transaction, so the history explains itself.

Pythonledger.py
from collections import defaultdict entries = [] def post(txn, lines): debits = sum(d for _, d, _ in lines) credits = sum(c for _, _, c in lines) if debits != credits: raise ValueError(f"{txn} is unbalanced: {debits} != {credits}") for account, debit, credit in lines: entries.append((txn, account, debit, credit)) post("t1 sale", [("psp_receivable", 4999, 0), ("revenue", 0, 4999)])post("t2 fee", [("fees_expense", 175, 0), ("psp_receivable", 0, 175)])post("t3 refund", [("revenue", 1000, 0), ("psp_receivable", 0, 1000)]) balances = defaultdict(int)for _, account, debit, credit in entries: balances[account] += debit - creditfor account, cents in balances.items(): print(f"{account:15} {cents / 100:8.2f}")print("books balance:", sum(balances.values()) == 0) try: post("t4 typo", [("revenue", 0, 500), ("psp_receivable", 50, 0)])except ValueError as e: print("rejected:", e)
Output
Press Run (⌘ Enter) to see what happens.

The PSP owes us $38.24 (49.99 − 1.75 − 10.00), fees are $1.75, and revenue shows as −39.99 because it is a credit account: computed as debits minus credits, credit balances come out negative. Revenue is $39.99. If the books do not sum to zero, there is a bug, and you know immediately.

Quick check
An engineer recorded a refund of $100 instead of $10. How should it be fixed?
Need a nudge? A hint rules out a wrong answer.

Deep dive 3: the payment state machine

A payment moves through a fixed set of states, and only some moves are legal. Encoding this as a state machine means a duplicate or out-of-order webhook cannot push a payment backwards.

Payment states
pendingpendingauthorized: money heldauthorizedmoney heldcaptured: money takencapturedmoney takenrefundedrefundedfailed: declinedfaileddeclinedcanceled: hold releasedcanceledhold releasedapprovedeclinecapturevoidrefund

The row is created as pending before we call the PSP.

1/5
TypeScriptpayment-state.ts
type State = "pending" | "authorized" | "captured" | "refunded" | "failed" | "canceled"; const ALLOWED: Record<State, State[]> = { pending: ["authorized", "failed"], authorized: ["captured", "canceled"], captured: ["refunded"], refunded: [], failed: [], canceled: [],}; function transition(from: State, to: State): State { if (from === to) return from; // duplicate webhook: harmless no-op if (!ALLOWED[from].includes(to)) throw new Error(`illegal: ${from} -> ${to}`); return to;} let s: State = "pending";for (const event of ["authorized", "captured", "captured", "authorized"] as State[]) { try { s = transition(s, event); console.log("now", s); } catch (e) { console.log((e as Error).message, "(ignored and alerted)"); }}
Output
Press Run (⌘ Enter) to see what happens.

In SQL the same guard is a conditional update: UPDATE payments SET status = 'captured' WHERE payment_id = ? AND status = 'authorized'. If zero rows change, the transition was not legal.

Reconciliation and the exactly-once illusion

Networks lose messages, so no system can promise a message is delivered exactly once. What we can build is exactly-once effect: at-least-once delivery (retry until acknowledged) plus idempotent handling (duplicates do nothing). Idempotency keys, webhook event IDs, order_id UNIQUE, and the state machine are all layers of the same idea.

Even so, our records and the PSP's can drift: a webhook lost for days, a manual refund in the PSP dashboard, a bug. Reconciliation is the safety net. Every night, download the PSP's settlement report and match each line to our ledger by psp_ref. Anything missing on either side, or with a different amount, goes to a queue for a human. Finance teams treat an unreconciled difference as an incident.

Match the pairs0/5 matched

Match the failure to the defence.

Choose an item, then its match on the other side.

PCI scope, bottlenecks, and 10x scale

PCI DSS is the security standard for anyone who stores, processes, or transmits card numbers. Full compliance is a major audit. With tokenization, the card number goes straight from the browser to the PSP's hosted fields and you only ever hold a token, which shrinks your compliance burden to a short self-assessment questionnaire.

  • PSP outage. Checkout fails. Show a clear error, never mark an order paid without confirmation. Large merchants integrate two PSPs and route around an outage.
  • Webhook backlog. Handlers must be fast and idempotent; process in the background, return 2xx quickly.
  • Ledger growth. Partition ledger_entries by month; keep derived balance snapshots per day so balance queries do not sum seven years of rows.
  • 10x (1,000+ payments a second): still fine for a sharded Postgres; shard by merchant or account. Correctness rules do not change with scale, which is the point.
Key terms
idempotency key
A client-supplied unique ID for one logical operation; the server returns the stored result for repeats instead of acting again.
double-entry ledger
Every transaction is recorded as debits and credits that sum to zero; balances are derived from entries.
authorize vs capture
Authorize holds the money on the card; capture actually takes it, often later.
webhook
An HTTP call from a provider to your server announcing an event, retried until you acknowledge it.
reconciliation
Comparing your records with an external source (the PSP's settlement report) to catch any drift.
tokenization
Replacing a card number with a token held by the PSP, keeping card data out of your systems and PCI scope.