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.
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
| Quantity | Math | Result |
|---|---|---|
| Orders | 10M a day / 86,400 | about 115 payments/s (peak 10x on sale days) |
| Ledger entries | about 4 per payment (auth, capture, fee, settlement) | about 40M rows a day |
| Ledger storage | 40M × 200 bytes × 365 | about 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:
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.
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_771Amounts 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 webhooksorder_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
Tokenize. Card details go from the browser straight to the PSP, which returns a token. Our servers never touch a card number.
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.
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.
Order the server's handling of a request with an Idempotency-Key.
- Tap the steps below in the right order.
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:
| txn | account | debit | credit |
|---|---|---|---|
| t1 sale | psp_receivable | 4999 | |
| t1 sale | revenue | 4999 | |
| t2 fee | fees_expense | 175 | |
| t2 fee | psp_receivable | 175 | |
| t3 refund | revenue | 1000 | |
| t3 refund | psp_receivable | 1000 |
Entries are append-only. A mistake is never edited; it is fixed with a new reversing transaction, so the history explains itself.
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.
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.
The row is created as pending before we call the PSP.
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 failure to the defence.
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_entriesby 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.
- 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.