Case studies

Design a payment system

Take card payments through a payment service provider without ever charging twice or losing a payment, using idempotency keys, a double-entry ledger and reconciliation.

Case study25 min read
Video walkthrough: not recorded yet. The lesson below is complete without it.

The problem

A customer taps Pay on an order of £49.99. Your server calls the payment provider, and 10 seconds later the HTTP call times out. Three things could have happened. The request never arrived. It arrived and the card was declined. Or it arrived, the card was charged, and the response was lost on the way back. From your side they look identical.

The habits that serve well elsewhere are dangerous here. Retry blindly and you may charge the customer twice. Give up and report a failure, and you may have taken £49.99 for an order you then cancel. Tell the customer nothing and they tap Pay again.

By the usual measures a payment system is small. Even a large merchant handles hundreds or a few thousand payments a second, which one well-run relational database can absorb. What makes it a senior interview question is that every step can fail halfway, one of the participants is a third party you do not control, and the cost of a mistake is someone’s money.

Requirements

Functional

  • A customer pays for an order by card or wallet through a payment service provider (PSP) such as Stripe or Adyen.
  • Every movement of money is recorded in a ledger.
  • Full and partial refunds.
  • The system accepts asynchronous results from the PSP by webhook.
  • A daily reconciliation compares internal records with the PSP’s settlement report.

Out of scope unless asked: pay-outs to sellers, fraud scoring, subscriptions, currency conversion. Card numbers never reach our servers: the browser or app sends them straight to the PSP’s hosted fields and we receive a token. That keeps most of the PCI DSS burden with the PSP.

Non-functional

  • Correctness: no double charges and no lost payments. Every state change is auditable.
  • Consistency over availability: if the system cannot durably record a payment, it must refuse it.
  • Durability: an acknowledged payment survives the loss of any one machine or zone.
  • Latency: a card authorisation commonly takes a second or two, so a p99 of a few seconds is acceptable.
  • Availability: 99.99% is the aim, but never at the cost of the first two points.
  • Scale: 10 million payments a day.

Capacity estimates

Quantity Working Result
Payments 10M a day / 86,400 about 115 per second
Peak 10x on a sale day about 1,200 per second
Ledger entries 10M payments x 3 entries 30 million rows a day
Ledger storage 30M x 200 bytes x 365 about 2.2 TB a year
Webhook events about 3 per payment 30 million a day, about 350 per second

The conclusion is unusual for a design interview: scale is not the hard part. A replicated relational primary handles this write rate, with the ledger partitioned by month. Spend the interview on failure handling, not on sharding.

API

POST /v1/payments
Idempotency-Key: 0b7e6c1a-52d3-4c0e-9a51-6f0c2d1e77aa

{ "order_id": "ord_9912", "amount": 4999, "currency": "GBP", "payment_method": "pm_tok_3fa9" }

201 Created    { "payment_id": "pay_5t1", "status": "CAPTURED" }
202 Accepted   { "payment_id": "pay_5t1", "status": "PENDING" }
GET  /v1/payments/{payment_id}
POST /v1/payments/{payment_id}/refunds       Idempotency-Key required
POST /v1/webhooks/psp                        called by the PSP, signature verified

Amounts are integers in the currency’s minor unit, never floating point. 202 is an honest answer when the outcome is not yet known. A repeat of the same key returns the stored response. The same key with a different body is rejected (422 is a common choice), and a repeat while the first request is still running gets 409.

Data model

Table Key columns Notes
payments payment_id, order_id, amount, currency, status, psp_reference one row per payment attempt
idempotency_keys (client_id, key) unique, request_hash, payment_id, response written in the same transaction as the payment
ledger_entries entry_id, transaction_id, account_id, direction, amount insert only
psp_events event_id unique, payload, processed_at raw webhooks, for deduplication and audit

The payment’s status is a state machine:

CREATED → PENDING → AUTHORISED → CAPTURED → REFUNDED
          PENDING → DECLINED     AUTHORISED → VOIDED

PENDING means “we have asked the PSP and do not know the answer yet”. Every transition is a conditional update on the current status, so a late or repeated message cannot move a payment backwards.

High-level architecture

Payment system reference architecture11 components: Browser or app, API gateway, Payment service, Payments DB, Payment provider, Ledger service, Ledger DB, Webhook handler, Event queue, Settlement reports, Reconciliation job. Connections: Browser or app to API gateway; Browser or app to Payment provider (card details for token); API gateway to Payment service (POST /payments); Payment service to Payments DB; Payment service to Payment provider (authorise, capture); Payment service to Ledger service (post entries); Ledger service to Ledger DB; Payment provider to Webhook handler (webhooks); Webhook handler to Event queue; Event queue to Payment service (apply result); Payment provider to Settlement reports (settlement file); Settlement reports to Reconciliation job; Reconciliation job to Ledger DB (compare).Browser or appAPI gatewayPayment servicestate machine, idempotencyPayments DBpayments, keys, outboxPaymentproviderPSPLedger servicedouble entryLedger DBappend-only entriesWebhook handlerverify, dedupe, ackEvent queueSettlementreportsdaily files from the PSPReconciliationjobcard details for tokenPOST /paymentsauthorise, capturepost entrieswebhooksapply resultsettlement filecompare
Payment system reference architecture

Pay path. The client sends card details directly to the PSP and gets a token. It then calls POST /v1/payments with that token and an idempotency key. The payment service inserts the key and a PENDING payment row in one transaction, and only then calls the PSP to authorise and capture. On the result it updates the status and writes an outbox row in one transaction. The ledger service posts the entries, and an event tells the order service the payment succeeded.

Webhook path. The PSP also reports results by calling our webhook handler. The handler verifies the signature, stores the raw event under its unique id, puts it on a queue and returns 200 quickly. The payment service consumes the queue and applies each event through the same state machine.

Reconciliation path. Each day a job fetches the PSP’s settlement report and compares it line by line with the ledger.

Deep dives

Idempotency keys and the unknown outcome

No network delivers a message exactly once. What a payment system builds instead is at-least-once delivery with idempotent handling at every hop, so that the effect happens once however many times the message is sent.

  • Client to us. The client creates one key per purchase attempt, when the customer taps Pay, and reuses it on every retry of that tap. The server inserts the key under a unique constraint. If the insert conflicts, it returns the stored result.
  • Us to the PSP. The payment service sends its own key derived from the payment, such as pay_5t1:capture, so a repeated call returns the original result. PSPs keep keys for a limited time (Stripe documents at least 24 hours), so after that window you query, not retry.
  • PSP to us. Each webhook has an event id, stored under a unique constraint.
  • Us to the ledger. Each posting has a key such as pay_5t1:capture, also unique.
A timeout calling the payment provider, and a safe retry4 components: Checkout, Payment service, Payments DB, Payment provider. Connections: Checkout to Payment service (pay with key); Payment service to Payments DB (record first); Payment service to Payment provider (charge with key).Checkoutbrowser or appPayment servicePayments DBPaymentproviderpay with keyrecord firstcharge with key

Step 1 of 8

A customer taps Pay for an order of 49 pounds 99. The app creates an idempotency key once for this purchase and sends it with the request.

Read the steps as text
  1. A customer taps Pay for an order of 49 pounds 99. The app creates an idempotency key once for this purchase and sends it with the request.
  2. Before calling anyone, the payment service stores the key and a payment row with status pending, in one transaction. From now on there is a record that this payment was attempted.
  3. The service asks the provider to charge the card, sending its own key derived from the payment id. The provider charges the card, but its response is lost on the way back.
  4. The call times out. The service cannot tell a lost request from a lost response, so it does not guess. The payment stays pending and the customer is told it is processing.
  5. The app retries with the same key. The service finds that key already stored and picks up the existing payment. It does not create a second one.
  6. The service calls the provider again with the same provider key. The provider recognises the key and returns the result of the original charge. The card is not charged a second time.
  7. Now there is evidence. The service marks the payment captured, the ledger entries are posted, and the customer sees a confirmation.
  8. If no retry had come, a background job would have asked the provider about every payment stuck in pending, and a webhook would have reported the result too. A timeout is never treated as a failure.
A timeout calling the payment provider, and a safe retry

Now the timeout. The payment row already exists as PENDING, because it was written before the call. The service returns 202 and the customer sees “processing”. The payment is then resolved in one of three ways:

  1. Retry the PSP call with the same key, using bounded backoff.
  2. Query the PSP for the payment by our reference.
  3. Receive the webhook.

A sweeper job runs the query for any payment that has been pending for more than a minute, which also covers a crash between the PSP’s reply and our database write.

Two rules follow. Never mark a payment failed because of a timeout. And never send a second PSP request under a new key for the same payment. If the customer abandons the page and starts a new checkout, the old pending payment must still be resolved, and voided or refunded if it turns out to have succeeded. A unique constraint allowing one successful payment per order backs this up.

The double-entry ledger

A single balance column that code increments and decrements has no history and no way to check itself. A double-entry ledger records every movement as a transaction of two or more entries in which total debits equal total credits. Money cannot appear or vanish: it only moves between accounts.

A £50.00 payment on a marketplace that keeps a £5.00 fee:

Account Debit Credit
PSP receivable (asset) 5000
Seller payable (liability) 4500
Platform revenue 500

When the PSP later settles that payment to the bank, less a 95p fee:

Account Debit Credit
Bank (asset) 4905
PSP fees (expense) 95
PSP receivable 5000

PSP receivable is back to zero for this payment. Any balance left on that account is money the PSP still owes us, or a discrepancy.

Entries are immutable. A mistake is fixed by posting a reversing transaction, never by an update. An account balance is the sum of its entries, usually kept as a running total updated in the same database transaction as the insert. The store needs real transactions: entries of one transaction commit together or not at all. Accounts that every payment touches, such as platform revenue, become hot rows if each insert locks a balance, so their totals are often computed in batches.

Webhooks and reconciliation

Webhooks arrive at least once, in no guaranteed order, and sometimes before the synchronous response to the call that caused them. The handler verifies an HMAC signature over the payload and a timestamp, rejects old timestamps to stop replays, stores the event and acknowledges. If the handler is down, PSPs retry for hours or days. Processing is asynchronous and idempotent by event id, and the state machine ignores transitions that no longer apply.

Reconciliation is the safety net under all of it. Each day, match every line of the PSP’s settlement report to a ledger transaction by reference, amount and currency.

  • In the PSP report, failed or missing on our side. A response was lost and recovery did not run. Correct the payment and post the entries, then fulfil or refund.
  • Captured on our side, missing from the report. Often a cut-off timing gap that closes in the next file. If it does not, it is a bug or fraud.
  • Amounts differ. Fees, partial captures or currency conversion.

Small, well-understood differences are fixed automatically. The rest go to a queue for finance staff. Idempotency is the claim that effects happen once. Reconciliation is the test.

Paying for an order usually spans services: reserve stock, take payment, confirm the order. The PSP cannot join a database transaction, so this is a saga with compensating actions: void the authorisation or refund, and release the stock.

Bottlenecks and failure modes

  • Crash after the PSP charged, before our write. The payment stays PENDING. The sweeper or the webhook resolves it.
  • PSP outage. A circuit breaker fails new payments fast. A second PSP can take new payments, but an in-doubt payment is never re-sent to a different provider.
  • Database failover. Use synchronous replication so an acknowledged payment is on more than one machine. During failover the service returns 503 and clients retry with their keys. This is the CP choice: refusing a payment is better than recording it in two places that disagree.
  • Webhook handler down. The PSP retries, and the sweeper polls in the meantime.
  • Ledger posting fails after capture. The outbox relay retries until the unique posting key is stored. Reconciliation catches anything still missing.
  • Refund races. Two partial refunds together could exceed the captured amount. Check the refunded total and insert the refund in one transaction with the payment row locked.
  • Disputes. A chargeback can arrive weeks later by webhook. It is a new ledger transaction, not an edit.

Trade-offs

Decision Chosen Alternative Why
Card data PSP-hosted fields and tokens Handle card numbers ourselves Keeps servers out of most PCI DSS scope; ties checkout to the PSP
Timeout handling Stay pending, resolve with evidence Fail and let the customer retry Cannot double charge; the customer sometimes waits
Ledger Append-only double entry Mutable balance column Auditable and self-checking; more rows to store and sum
Consistency Single primary, synchronous replicas Multi-region active-active writes No conflicting money records; lower availability, slower writes
Order flow Saga with compensation Two-phase commit The PSP cannot join a transaction; needs void and refund paths

45-minute interview script

A pacing guide. Interviewers differ, so treat the timings as a default and follow their lead.

  1. 0:00 to 5:00

    Requirements 5 min

    Confirm this is pay-in through a payment service provider, with refunds. Ask about pay-outs, currencies and whether you store card numbers (you should not). State that correctness beats availability and say what that means in practice.

  2. 5:00 to 8:00

    Capacity estimates 3 min

    Derive payments per second, ledger rows per day and webhook volume. Say the conclusion, which is that throughput is modest and the design effort goes into failure handling.

  3. 8:00 to 12:00

    API 4 min

    Create payment with an idempotency key, get payment, refund, and the webhook endpoint the provider calls. Amounts are integers in minor units with a currency code.

  4. 12:00 to 17:00

    Data model 5 min

    Payments with a status, idempotency keys, immutable ledger entries, stored provider events. Draw the state machine and explain what pending means.

  5. 17:00 to 24:00

    High-level design 7 min

    Draw the card details going straight to the provider, then the pay path, the webhook path and the reconciliation path. Narrate one successful payment end to end.

  6. 24:00 to 32:00

    Deep dive: idempotency and the unknown outcome 8 min

    A key on every hop. Walk through a timeout calling the provider, why you must not mark it failed, and the three ways the payment is resolved (retry with the same key, status query, webhook).

  7. 32:00 to 39:00

    Deep dive: ledger and reconciliation 7 min

    Double-entry with a worked example, immutability and reversing entries, then daily reconciliation against the settlement file and what each kind of mismatch means.

  8. 39:00 to 43:00

    Failure modes and trade-offs 4 min

    Crash between charge and database write, provider outage, duplicate and out-of-order webhooks, database failover. Mention sagas for the order flow.

  9. 43:00 to 45:00

    Wrap-up 2 min

    Summarise in three sentences. Name what you would add next, such as pay-outs or a second provider.

Sketch this design on the whiteboard Run it as a timed mock

Key takeaways

  • A timeout from the provider means the outcome is unknown, not that the payment failed. Keep it pending until you have evidence.
  • Put an idempotency key on every hop (client to you, you to the provider, provider webhooks to you, you to the ledger) so that any message can be safely repeated.
  • Record the intent in your database before calling the provider, so a crash can never leave a charge you do not know about.
  • A double-entry ledger is append-only and every transaction sums to zero, which makes missing or invented money detectable with a query.
  • Exactly-once effects come from at-least-once delivery plus idempotent handling. Reconciliation against the provider's records is the proof that it worked.
  • When the system cannot record a payment safely, it refuses it. Consistency wins over availability.

Check yourself

1. Your call to the payment provider times out after 10 seconds. What should the payment's status be?
2. Why does the payment service write a pending payment row before it calls the provider?
3. A client retries a payment with the same idempotency key but a different amount. What should the server do?
4. In a double-entry ledger, how do you correct a payment that was recorded with the wrong amount?
5. The provider sends the "captured" webhook twice, and the second copy arrives after a "refunded" webhook. What stops the payment going back to captured?

0 of 5 answered

Flashcards

These 6 cards are in your review deck. Tap a card to see the answer.

What are authorisation, capture and settlement?

Authorisation asks the card issuer to approve and hold the amount. Capture instructs the money to be taken. Settlement is the funds reaching your bank account, typically days later and net of fees.

What does an idempotency key guarantee?

Repeating a request with the same key has the same effect as sending it once. The server stores the key with the result and returns that result for any repeat.

What is the invariant of a double-entry ledger?

Every transaction has at least two entries, and total debits equal total credits. Entries are never updated or deleted.

Three ways to resolve a payment stuck in pending?

Retry the provider call with the same idempotency key, query the provider for the payment's status, or wait for the provider's webhook. A sweeper job does the query for anything pending too long.

Why store money as integers in minor units?

Binary floating point cannot represent values such as 0.1 exactly, so sums drift. Store 4999 with currency GBP, and remember that currencies differ in decimal places (yen has none, Kuwaiti dinar has three).

What is reconciliation?

A scheduled comparison of your ledger with the provider's settlement report and the bank statement. Every difference is either a timing gap that will close or a bug to investigate.

Review the deck