"Design a payment system" is a question where one wrong sentence costs more than ten right ones. Charge a customer twice and you have a refund and an angry user. Lose a charge and you have unrecorded revenue. The interviewer is not asking you to build a card network. They want to see how you reason when money moves through a system you do not control.
The shape of the problem is this. Your service takes a request from a merchant or your own checkout, calls a payment service provider (PSP) that talks to the card networks and banks, and has to record what happened. The call can time out, the PSP can answer late through a webhook, and your own database can fail between steps. The answer that scores well is built on three ideas: idempotency on every hop, a ledger that records every movement of money as balanced entries, and reconciliation against the PSP's own records, because you will never be perfectly in sync.
Throughout, be exact about guarantees. Networks and retries give you at least once. You build effectively once by making repeats harmless. Say that, not "exactly once". Background: idempotency and distributed transactions. The balances-between-users variant is Design a Digital Wallet, and the order flow around a payment is Design Amazon's Shopping Cart and Checkout.
Clarify the requirements
Functional requirements:
- A merchant (or our checkout) creates a payment for an amount and currency, with a customer payment method.
- The system authorizes the payment with a PSP and, when asked, captures it.
- The customer or merchant can be refunded, fully or partly.
- The merchant is told the outcome: synchronously where possible, and by webhook otherwise.
- Finance can see every movement of money and reconcile it against the PSP's reports.
Out of scope, said aloud: card data collection UI, fraud scoring models, chargeback handling, payouts to bank accounts, tax, and building a PSP or card network yourself.
Non-functional requirements: these decide the design.
- No double charge, no lost charge. Every payment ends in a known state, and a retry never produces a second charge.
- Every cent is accounted for. Records are append-only and balanced, and corrections are new entries, never edits.
- Correctness over speed, availability over rarely-needed features. A payment takes a second or two because the PSP does. We never trade correctness for latency.
- Sensitive data stays minimal. Card numbers are collected by the PSP's hosted fields or SDK and replaced by tokens, so our servers handle tokens, not card numbers. This shrinks the scope of card-data compliance, which is a reason to do it. Check your actual obligations with the standard and your provider rather than assuming.
- Auditable. Anyone can reconstruct why a balance is what it is.
Estimate the scale
Assume 5 million payments a day, each producing about 6 ledger entries (authorization, capture, our fee, the merchant's share and so on).
Payments: 5M ÷ 86,400 ≈ 58 per second, perhaps 290 at a 5× peak (a sale or a billing run).
In-flight calls: a PSP call takes about 2 seconds. By Little's law, concurrency is rate × latency: 290 × 2 ≈ 580 requests in flight at peak. The call budget, not the CPU, is what you size.
Ledger entries: 5M × 6 = 30M a day ÷ 86,400 ≈ 350 writes per second.
Storage: 30M entries × 200 bytes = 6 GB a day, about 11 TB over five years, kept forever in practice because finance and auditors need history.
Webhooks in: about 2 PSP events per payment (authorized, captured) is 10M a day ≈ 116 per second, at least once each.
"58 payments a second is modest. The load is not the difficulty. The difficulty is that each payment is a conversation with an external system that can time out in the middle, so my design is about states, retries and records, not throughput."
Try other numbers in the capacity estimator, where writes stand for ledger entries per payer per day.
API and data model
POST /v1/payments { amount, currency, paymentMethodToken, captureMode }
Idempotency-Key: <client-generated>
-> { paymentId, status }
POST /v1/payments/{id}/capture { amount? } Idempotency-Key
POST /v1/payments/{id}/refunds { amount } Idempotency-Key
GET /v1/payments/{id} -> status, history
POST /webhooks/psp (from the PSP) -> 200 once recordedpayments (id PK, merchant_id, amount_minor, currency, status, psp_ref, idem_key UNIQUE, version)
status: created | authorizing | authorized | captured | failed | canceled | unknown
ledger_entries (txn_id, line PK, account_id, direction: debit|credit, amount_minor, currency, payment_id, created_at)
idempotency (merchant_id, key PK, request_hash, response, status)
psp_events (psp_event_id PK, payment_id, type, payload, processed_at)Two choices to state aloud. Amounts are integers in the currency's minor unit (cents), with the currency stored beside them, because floating point cannot represent decimal money exactly. The minor-unit exponent differs by currency, as ISO 4217 defines, so never assume two decimals. And psp_event_id is the primary key of the event table, so a webhook delivered twice is recorded once.
High-level design
The slice worth running is the payment write path: a gateway, a payment service that records the payment and its ledger entries, the ledger database and an event stream that feeds reconciliation and downstream consumers.
- Clients reach the payment API through a gateway that authenticates and rate-limits.
- The payment service writes the payment and ledger entries to Postgres and publishes events that reconciliation consumes.
Describe this diagram
Components
- clients (Client)
- gateway (API gateway)
- payment api (Service)
- payments ledger (PostgreSQL)
- payment events (Kafka)
- reconciliation (Service)
Connections
- clients sends to gateway
- gateway sends to payment api
- payment api sends to payments ledger
- payment api sends to payment events
- payment events sends to reconciliation
Run it, then try raising the load and watch the ledger database. The PSP is not part of the simulation, so remember that its latency adds to every request in real life.
The write path: the service validates the request, claims the idempotency key, inserts the payment in created state and commits. It then calls the PSP with a key derived from the payment id and moves the payment to authorized or failed in a transaction that also writes the ledger entries and an outbox row.
The read path: status lookups read the payments table, and a webhook can advance the state at any time. Finance reads the ledger and the reconciliation reports.
The interesting problem: a timeout in the middle of a charge
The service calls the PSP to authorize 50.00. The connection drops after 10 seconds. Did the charge happen? You do not know, and every choice has a cost.
Approach A: retry the call
Good: simple, and it works when the first call never arrived.
Bad: if the first call succeeded and only the response was lost, the customer is charged twice. This is the failure that the idempotency lesson is built around.
Approach B: record the intent, then call with a stable idempotency key
- Write the payment to the database in
createdstate, with a unique id. Commit. - Mark it
authorizingand call the PSP, passing an idempotency key derived from the payment id (the PSP deduplicates calls with the same key). - On a definite answer (approved or declined), record it. On a timeout, do not guess: set the status to
unknown. - Resolve
unknownby asking the PSP for the payment by our reference, or by retrying the same call with the same key, which the PSP answers with the original result. A webhook may also arrive and settle it.
Good: a retry cannot create a second charge, and there is always a record of what we tried. unknown is an honest state with a worker to resolve it.
Bad: more states and a resolver to run, and it depends on the PSP supporting idempotency keys or lookups by reference.
Approach C: do everything asynchronously through a queue
Accept the request, return 202, and let a worker call the PSP.
Good: absorbs bursts and isolates PSP slowness from callers.
Bad: the caller must wait for the result or poll, and the same timeout and duplicate problems exist inside the worker. It is a delivery mechanism, not a correctness fix.
The recommended answer is B, optionally delivered through C. The principle to state: persist the intent before the side effect, give the side effect a stable key, and treat "I don't know" as a first-class state that a process resolves. At no point does the customer get charged twice, and at no point is a payment silently forgotten.
Diagram, as text
- Request with Idempotency-Key leads to Insert payment: created
- Insert payment: created leads to Call PSP with key from payment id
- Call PSP with key from payment id leads to Record result and ledger entries (approved or declined)
- Call PSP with key from payment id leads to Status unknown (timeout)
- Status unknown leads to Resolver: look up by reference or retry same key
- Resolver: look up by reference or retry same key leads to Record result and ledger entries
- PSP webhook leads to Record result and ledger entries
The second decision: the ledger and reconciliation
A double-entry ledger. Every movement of money is a transaction made of two or more entries, and the entries in each transaction sum to zero: for each currency, total debits equal total credits. Capturing a 50.00 payment with a 1.50 fee might record: debit the "customer funds in transit" account 50.00, credit the merchant's payable account 48.50, credit the platform's fee revenue account 1.50. A single entry on its own is never valid. The ledger is append-only: a mistake is fixed by a reversing transaction, never an update, so the history stays auditable. The balance of an account is the sum of its entries, which you can cache as a running total updated in the same transaction.
Write the ledger entries, the payment status change and the outbox event in one database transaction. That is the cheap way to make the three agree without a distributed transaction.
Webhooks. The PSP tells you about events later and may repeat or reorder them. Verify the signature, insert the event by its psp_event_id (a duplicate fails and is acknowledged), apply it only if it moves the payment forward in the state machine, and return success only after it is recorded. A webhook that arrives before the API response is normal, so state changes must tolerate any order.
Reconciliation. Your records and the PSP's settlement reports will disagree sometimes: a payment you believe failed that the PSP captured, a fee different from the one you expected, a missing refund. A daily job matches your ledger against the PSP's report by reference, classifies mismatches (missing on our side, missing on theirs, amount differs) and opens a work item for each. Reconciliation does not assume the system is correct, which is why it is needed. Say that the goal is that every difference is found and explained.
Bottlenecks and failures
PSP slow or down. Calls have a timeout, a retry limit and a circuit breaker. If the PSP is down, new payments fail fast with a clear status, or you route to a second PSP where the contract allows it. Never retry forever on a user's request.
Retry storms. A burst of timeouts causes retries that add load. Use jittered backoff and a retry budget.
A crash between steps. The payment sits in authorizing. A sweeper finds payments stuck in an in-flight state beyond a limit and resolves them through the lookup path. This is why the intent is persisted first.
Hot merchants. Updating one merchant's balance row on every payment serializes on a hot row. Append ledger entries (no contention) and compute balances from them or from periodic roll-ups, not by updating one row in every request.
Idempotency misuse. Reusing a key with a different request body is a client bug. Store a hash of the request and return a conflict error, not the old response.
Refund races. Two refunds for the same payment must not exceed what was captured. Enforce refunded_total <= captured with a conditional update, and key each refund by its own idempotency key.
Data protection. Store only tokens, encrypt sensitive fields, restrict access and log access to payment records. Do not log full request bodies that might contain payment details.
Trade-offs to name aloud
- An
unknownstate and a resolver: more machinery, in exchange for never guessing about money. - Append-only ledger: corrections are new entries and storage grows forever, in exchange for a history auditors can trust.
- Synchronous response plus webhooks: two paths to the same state, in exchange for fast answers and resilience to lost responses.
- One PSP or several: one is simpler, several give resilience and cost control but multiply the reconciliation work.
What interviewers listen for
- A working answer: a payments table with states, an idempotency key on the API, a call to a PSP, and a record of what happened.
- A strong answer: persists intent before calling the PSP, sends the PSP a stable idempotency key, models an unknown outcome, handles duplicate and reordered webhooks and uses integer minor units.
- A standout answer: designs a double-entry, append-only ledger written in the same transaction as the state change, reconciles against settlement reports, distinguishes the caller's key from the PSP key and says "effectively once" rather than "exactly once".
Check your understanding
Common mistakes
Saying "exactly once". Networks give at least once. You build effectively once with idempotency and deduplication, and you should say so.
Calling the PSP before recording anything. A crash then leaves a charge with no record. Persist the intent first.
Storing money as floats. Use integers in minor units with the currency, and remember currencies differ in minor-unit size.
Updating a balance in place. Append entries and derive balances. An in-place update loses the history and creates a hot row.
Trusting your own records. Without reconciliation against the PSP, drift stays hidden until finance finds it.
Treating a timeout as a failure. It is an unknown, and the two cases need opposite responses.
Practice
Finance's daily reconciliation shows 40 payments marked failed in your system that the PSP shows as captured. How did this happen, and what do you do?
Write your own answer first, on paper or in a note. Then compare.
Show a hint
Think about which of your code paths could turn an unknown outcome into a failure.
Show a strong answer
The likely cause. A timeout handler marked the payment failed instead of unknown, or a webhook reporting success arrived after the payment was already closed as failed and was ignored by a state rule that did not allow failed to captured.
Fix the 40. For each, the PSP reference is the source of truth for the money. Create ledger entries to record the capture, move the payment to captured through an explicit, audited transition, and notify the merchant. If the customer should not have been charged, issue a refund through the normal path.
Fix the code. A timeout becomes unknown, never failed. Allow a late success to override an earlier unconfirmed failure, and alert when the PSP's state disagrees with ours.
The pattern worth keeping: reconciliation is not a formality. It finds the cases where your state machine and the outside world disagree, and each finding becomes a test.
A merchant's integration retries a create-payment request with the same Idempotency-Key but a different amount. What should the API do, and why?
Write your own answer first, on paper or in a note. Then compare.
Show a hint
Consider what each possible response would mean for the money.
Show a strong answer
Return a conflict error. The key identifies one intent. A second request with the same key and a different body is a bug in the client, or an attack, not a retry.
How the service knows. Store a hash of the request body with the key. On a repeat, compare hashes. If they match, return the stored response. If they differ, return an error such as 409 with a clear message.
What not to do. Do not run the new request, because it would charge a different amount under an old key. Do not silently return the old result, because the merchant would believe the new amount was accepted.
The pattern worth keeping: an idempotency key binds an identity to one specific request, so check the request as well as the key.
Key takeaways
- The hard part is the outside world, a PSP you do not control, not the load.
- Persist intent first, call with a stable key, and treat unknown as a state with a resolver.
- Say effectively once: at-least-once delivery plus idempotent handling.
- A double-entry, append-only ledger written in the same transaction as the state change.
- Webhooks are duplicated and reordered: dedupe by event id and respect the state machine.
- Reconcile daily against the PSP, because drift is a fact, not an exception.
Further reading
- ISO 4217: the standard for currency codes and each currency's minor-unit exponent.
- Stripe API documentation, "Idempotent requests": how a payment provider documents idempotency keys.
- IETF Internet-Draft, "The Idempotency-Key HTTP Header Field": a proposed standard header for idempotent requests.
- Martin Kleppmann, "Designing Data-Intensive Applications" (O'Reilly, 2017): chapters on transactions and on the end-to-end argument for duplicate suppression.