Design a Payment System
A payment system is the one place where a retry can charge a customer twice and a lost message can ship goods for free. This lesson designs checkout payments for an online store: a payment state machine, idempotency keys at every step, a double-entry ledger as the source of truth, webhooks and reconciliation to catch what went wrong, and safe refunds.
What you will learn
- Correctness beats latency: never charge twice, never lose a payment.
- Model a payment as a state machine and persist every transition before acting on it.
- Idempotency keys on every call, ours and the provider's, make retries safe.
- An unknown result is a real state: resolve it by asking the provider, never by guessing.
- Record money in a double-entry ledger; balances are derived, never edited.
- Reconcile daily against the provider's settlement files to catch every mismatch.
In this lesson
- The question
- Step 1: Clarify the requirements
- Step 2: Back-of-the-envelope estimates
- Step 3: Who is involved
- Step 4: The API
- Step 5: The payment state machine
- Step 6: The high-level design
- Step 7: Idempotency, everywhere
- Step 8: Timeouts and unknown results
- Step 9: The double-entry ledger
- Step 10: Webhooks and reconciliation
- Step 11: Refunds and security
- Step 12: Payouts and currencies
- Step 13: The follow-up questions
- Recap
Short on time? Read the answer outline for design a Payment System.
Practice this question with MaxThe question
Welcome to lesson thirteen of the InterviewDryRun system design course. Today we design a payment system: what happens between a customer clicking pay on an online store and the money arriving in the store's bank account.
Payments are different from everything else in this course. In a news feed, a duplicate post is a small annoyance. In payments, a duplicate is a customer charged twice, and a lost message is goods shipped for free. The traffic is usually modest. What the interviewer is testing is whether you can make a distributed system exactly right, when networks time out, services crash halfway and external providers reply late or not at all.
Max asks
“Design the checkout payment flow for an online store, including retries and refunds.”
That is how Max, our AI interviewer, asks it. The words retries and refunds are the hint. Retries mean the interviewer wants to talk about failure and idempotency. Refunds mean money moves in both directions and must be tracked precisely. The happy path will take five minutes. The rest of the interview is about what happens when things go wrong.
The plan: requirements and numbers, then how card payments really work, so we design with the right parties. Then the API, the high-level design and the payment state machine. Then the deep dives: idempotency, timeouts and unknown results, the ledger, webhooks, reconciliation, refunds, and security. And the follow-up questions.
Step 1: Clarify the requirements
- 01Pay for an orderCards first; wallets and bank transfers later
- 02Authorise, then captureHold at checkout, take the money when shipped
- 03RefundsFull or partial, possibly days later
- 04Payment statusFor the order service, support and the customer
- 05PayoutsSettle money to the store's bank account
Start with questions.
Which payment methods? Cards are the core; wallets and bank transfers can be added later through the same design. Ask whether we process cards ourselves or use a payment service provider. Almost every company uses a provider, which talks to the card networks and banks. That keeps us out of the hardest security obligations, so assume a provider, and say why.
Ask about the flow. Online stores usually authorise at checkout, which reserves the money on the customer's card, and capture later, when the order ships, which actually takes it. If the item turns out to be out of stock, the authorisation is released instead. That two-step flow is worth naming, because it shows you know how card payments work.
Refunds, full or partial, sometimes weeks later. A status that the order service, customer support and the customer can see. And payouts: the money collected by the provider is settled into the store's bank account, typically daily, minus fees. Our system must account for all of it.
- 01Exactly once in effectNo double charges, no lost payments
- 02AuditableEvery cent traceable, for years
- 03SecureCard data never touches our servers
- 04AvailableCheckout down means revenue lost
- 05LatencyA few seconds is fine; correctness is not optional
The qualities, in order. Correctness: every payment happens exactly once in effect, even if messages are sent several times. This one requirement dominates the design.
Auditable: every cent must be traceable from the customer's card to the store's bank account, and kept for years for accountants and regulators. And secure: card numbers should never touch our servers at all.
Availability matters, because a broken checkout loses sales, but notice the trade-off. If we must choose between being unavailable and being wrong, we choose unavailable. Ask the interviewer to confirm. And latency: a payment that takes two seconds is fine. This is the opposite of most designs, where we trade correctness for speed.
Step 2: Back-of-the-envelope estimates
A quick sizing, and it gives a surprising answer.
Even a very large store, with ten million orders a day, is about a hundred and twenty payments a second on average, and a couple of thousand at a sale-day peak. Each payment writes several ledger entries, so maybe a hundred million entries a day. Those are modest numbers. A well-run relational database handles them, with sharding only at the very high end.
The important number is the last one: the provider's response time. Half a second to three seconds normally, and sometimes, no answer at all. That is the real design constraint. Say it clearly: scale is not the hard part of this problem. Correctness, across unreliable calls to an external party, is.
Sale days deserve a note. Twenty times the normal rate arrives in a few minutes when a big sale starts. The payment service itself is easy to scale, but the provider may impose its own rate limits, and the database must not lock up under bursts of conditional updates. So we load test with the provider's test environment, agree limits with the provider in advance, and queue non-urgent work, like captures, behind the urgent authorisations.
Step 3: Who is involved
Before designing, it helps to name the parties, because many candidates draw a payments box and stop there. The customer has a card. Our store wants to be paid.
Between us and the banks sits the payment service provider. Crucially, the customer types their card details into a form hosted by the provider, embedded in our checkout page. The provider stores the card and gives us back a token, a meaningless reference. So card numbers never reach our servers, which keeps us out of most of the security obligations that come with handling card data.
The provider sends the authorisation through the card network to the customer's bank, the issuer, which approves or declines based on funds and fraud checks. Later, the money moves through the networks to the provider, and the provider pays out to our bank account, minus fees.
Knowing this tells us what our system must actually do: keep track of orders and their payments, call the provider safely, record what happened in our own books, and reconcile our books against the provider's. We are not building a card network. We are building a careful, auditable client of one.
Step 4: The API
POST /v1/payments
Idempotency-Key: order-8812-attempt-1
{ orderId: 8812, amount: 4999, currency: "INR",
paymentMethodToken: "tok_..." }
→ 201 { paymentId, status: "authorized" | "declined" | "pending" }
POST /v1/payments/{id}/capture Idempotency-Key: ...
POST /v1/payments/{id}/refunds Idempotency-Key: ...
GET /v1/payments/{id}Our own payment service has a small API, used by the order service. Create a payment for an order, with an amount, a currency and the card token from the provider. Capture it later. Refund it, fully or partly. And read its status.
Two details matter. Amounts are integers in the smallest unit of the currency, like paise or cents, never floating point numbers, which cannot represent money exactly. And every call that changes anything carries an idempotency key. If the order service times out and calls again with the same key, it gets the same result, not a second payment.
Notice the status can be pending. We will not always know the answer when we reply, because the provider might not have answered yet. Building that state into the API from the start is far better than pretending every call has a clean yes or no.
Step 5: The payment state machine
The core of the design is a state machine for each payment, stored in our payments database. A payment is created, then moves to authorisation pending when we call the provider.
From pending, it becomes authorised or declined. And here is the rule that makes everything else work: we write the new state to our database before calling the provider, and again after. If we crash in the middle, the stored state tells a recovery job exactly where we were and what to check.
An authorised payment is captured when the order ships, or voided if it is cancelled. A captured payment can be refunded, fully or partly, possibly several times. Each transition is a row in a payment events table as well as an update to the current state, so we keep the full history.
Only allowed transitions are accepted, enforced with a conditional update: change the state to captured only if it is currently authorised. Two concurrent capture requests cannot both succeed, because only one of them will find the payment in the authorised state. That single pattern, a conditional state change, prevents a whole class of double actions.
Keep the state machine small and explicit, and put it in one place in the code. Every new feature, partial captures, disputes, a second provider, becomes new states and allowed transitions, rather than flags scattered across tables. When an auditor or an engineer asks what can happen to a payment, the answer is a single diagram, and the database enforces it.
Step 6: The high-level design
Here is the whole design. The order service asks the payment service to pay for an order.
The payment service stores the payment and its idempotency key in its own database, in a transaction, before doing anything external. That database is a relational one with strong consistency, because we need transactions and unique constraints.
It calls the provider, with the provider's own idempotency key, and records the result. The provider also sends webhooks, asynchronous notifications about events like a capture settling, a refund completing or a customer disputing a charge.
Every movement of money is written as entries in a double-entry ledger, which is the financial source of truth.
And a reconciliation job compares our ledger with the provider's reports every day, so any mismatch, however it happened, is found and fixed. The rest of the lesson goes through each of these pieces.
Step 7: Idempotency, everywhere
BEGIN INSERT idempotency_keys (key, request_hash, status='in_progress') -- unique key: a second request with the same key fails here COMMIT if insert failed: same request? return the stored response (or 409 if still running) different request body? 422: key reused do the work... then store the response under the key
Idempotency is the single most important idea in this lesson. An operation is idempotent if doing it twice has the same effect as doing it once. Networks make clients retry, so every operation that moves money must be idempotent.
On our side, the order service sends an idempotency key, derived from the order, like order eight eight one two, attempt one. The payment service inserts the key into a table with a unique constraint, in the same transaction that creates the payment. A retry with the same key fails the insert, so we look up and return the original response. If the original is still running, we tell the client to wait. If the same key comes with a different amount, that is a client bug, and we reject it.
On the provider's side, we do the same in reverse. When we call the provider to authorise, we send our own idempotency key, typically the payment id plus the operation. If our call times out and we retry, the provider recognises the key and returns the original result instead of charging again. So we have idempotency on both hops: order service to us, and us to the provider.
Interviewers often ask: how long do you keep the keys? Long enough to cover any realistic retry, at least a day, often longer for payments. And they ask: why not just check whether a payment for this order exists? Because an order can legitimately have several payment attempts, after a decline, for example. The key identifies the attempt, not the order.
Step 8: Timeouts and unknown results
| Result | Meaning | What we do |
|---|---|---|
| Approved | money reserved | mark authorised |
| Declined | bank said no | mark declined, tell the customer |
| Error before sending | nothing happened | retry with the same key |
| Timeout | unknown: maybe charged | mark unknown; ask the provider |
Here is the case that separates strong answers from weak ones. We call the provider, and the call times out. Did the payment go through or not? We genuinely do not know. The request may never have arrived, or it may have been approved and the response lost.
Both easy answers are wrong. Treating it as failed and asking the customer to pay again risks a double charge. Treating it as success risks shipping goods without payment. So unknown is a real state. Store it, and resolve it.
How? First, retry the same call with the same idempotency key: the provider returns the original result if it processed it, or processes it now if it never arrived. Either way, the customer is charged at most once. If retries keep failing, a background job keeps asking the provider for the status of that payment, using our reference, until it gets a definite answer. Meanwhile the customer sees a message like we are confirming your payment, and the order waits.
This is the same pattern behind every robust integration with an external system: persist your intent before calling, make the call idempotent, and when in doubt, query the other side rather than guess. If you can explain it in those three steps, the interviewer will be satisfied with this part.
Step 9: The double-entry ledger
| Event | Debit | Credit | Amount |
|---|---|---|---|
| Capture | provider receivable | customer payments | 4,999 |
| Provider fee | fees expense | provider receivable | 150 |
| Payout to bank | bank account | provider receivable | 4,849 |
| Partial refund | customer payments | provider receivable | 1,000 |
Now the books. Our payments table tells us the state of each payment, but finance needs to know where every rupee is at any moment. The proven way to do that, used for centuries, is double-entry bookkeeping.
Every movement of money is recorded as a transaction with at least two entries: a debit to one account and an equal credit to another. When we capture a payment, money is now owed to us by the provider, so we debit provider receivable and credit customer payments. When the provider takes its fee, we record that too.
When the provider pays out to our bank, the money moves from provider receivable to our bank account. And a refund reverses part of the flow. The rule is that in every transaction the debits equal the credits, so the books always balance. If they ever do not, we know immediately that something is wrong.
The ledger is append-only. We never edit or delete an entry. A mistake is fixed with a new, reversing entry. Balances are never stored as editable numbers; they are the sum of entries, perhaps cached for speed. That gives us a complete audit trail for free: to explain any balance, list its entries. Interviewers love hearing append-only and balances are derived, because it shows you understand how financial systems stay trustworthy.
Write ledger entries in the same database transaction as the state change that causes them. Capturing a payment and recording its ledger entries succeed or fail together. If the ledger lives in a separate service, use an outbox: write the entries to an outbox table in the same transaction, and a relay delivers them to the ledger service, with idempotency on the receiving side.
Step 10: Webhooks and reconciliation
- 01VerifyCheck the signature; reject anything unsigned
- 02Store firstSave the raw event, then acknowledge
- 03Process idempotentlySame event id twice changes nothing
- 04Any orderEvents can arrive late or out of order
Many things happen later, outside our calls: a capture settles, a refund completes, a customer disputes a charge with their bank. The provider tells us through webhooks. First, verify the signature on every webhook, because the endpoint is public and anyone could send fake success messages.
Store the raw event durably, then acknowledge quickly, and process it asynchronously. If processing fails, we still have the event and can retry. If we fail to acknowledge, the provider will resend it.
Process idempotently, keyed by the provider's event id, because events will arrive more than once. And never assume order: a refund completed event may arrive before the capture settled event. Apply each event only if it moves the state machine forward, and treat the provider's current status, fetched on demand, as the tie breaker.
- 01InputsOur ledger and the provider's settlement file
- 02MatchBy payment reference and amount
- 03MismatchesMissing on one side, different amounts, fees
- 04ResolveAutomatic fixes for known cases; a queue for people
Even with all this care, things will drift: a webhook lost for days, a bug, a manual adjustment at the provider. So every day, the provider publishes a settlement report listing every transaction, fee and payout. A reconciliation job matches it against our ledger, line by line, by reference and amount.
Mismatches fall into known types: a payment we think failed but the provider settled, a refund on their side we have not recorded, a fee that differs. Known types get automatic fixes, through new ledger entries, never edits. Anything else goes into a queue for the finance team. Reconciliation is not an optional extra. It is how a payment system proves it is correct, and interviewers expect you to mention it.
Step 11: Refunds and security
- 01Its own recordA refund has its own id, state and idempotency key
- 02Never more than capturedSum of refunds checked in the same transaction
- 03AsynchronousPending until the provider confirms
- 04Ledger entriesReversing entries, never deleted ones
Refunds reuse everything. A refund is its own object, with its own id, its own small state machine, and its own idempotency key, so a support agent clicking refund twice refunds once.
Guard the total: in the same transaction that creates the refund, check that existing refunds plus this one do not exceed the captured amount, with the payment row locked. Two concurrent partial refunds cannot together refund more than was paid.
Refunds are asynchronous: pending until the provider confirms by response or webhook, and recorded in the ledger as reversing entries. If the original payment is too old for the provider to refund, the refund becomes a bank transfer handled through the same ledger.
A few words on security. Card data stays with the provider, through its hosted fields and tokens. Our own systems still protect what they hold: encrypt sensitive fields, restrict who can issue refunds and log every such action, verify webhook signatures, and check fraud signals before authorising, such as unusual amounts, mismatched countries, or many cards from one device. Many providers offer fraud scoring we can combine with our own rules.
Step 12: Payouts and currencies
- 01SettlementProvider pays out daily, minus fees and refunds
- 02MarketplacesSplit each payment between sellers and us
- 03CurrenciesStore amount and currency together; convert explicitly
- 04HoldsKeep a reserve for refunds and disputes
The question is about checkout, but money has to end up somewhere, and a complete answer mentions where. The provider settles to our bank account on a schedule, usually daily, sending one transfer that combines many payments, minus fees and minus refunds. The ledger entries we have already described let us explain every rupee of that single transfer.
If the store is a marketplace, each payment must be split: most goes to the seller, some to us as commission. Model sellers as accounts in the ledger, so a capture credits the seller's balance and our commission account in one balanced transaction. A payout job then pays sellers from their balances on a schedule, again with idempotency keys, because a payout run that is retried must never pay a seller twice.
Currencies: never store an amount without its currency, and never add amounts in different currencies. When a customer pays in one currency and we settle in another, the conversion is an explicit ledger transaction with the rate recorded, so finance can explain gains and losses from exchange rates later.
And hold back a reserve. Refunds and disputes can arrive weeks after a payout, so paying out every rupee immediately would leave nothing to cover them. Keeping a small rolling reserve per seller is a common, sensible rule, and mentioning it shows you are thinking about the whole life of the money, not just the checkout click.
Step 13: The follow-up questions
Max asks
“The customer clicks pay twice very quickly. What happens?”
The checkout page sends the same idempotency key for both clicks, since it is generated once per checkout attempt. The first request inserts the key and proceeds. The second fails the unique constraint and receives the first request's result, or a please wait if it is still running. The customer is charged once. We also disable the button after the first click, but the server must never rely on that.
Max asks
“Your payment service crashes right after the provider approved, before you saved the result. How do you recover?”
The payment is still stored as authorisation pending, with the time we called. A recovery job finds payments stuck in pending for more than a minute or two and asks the provider for their status using our reference. The provider says approved, so we move the payment to authorised and continue. Because we wrote our intent before calling, nothing is invisible.
Max asks
“How would you add a second payment provider?”
Put an adapter interface in front of providers, so the state machine and ledger do not change. Route by method, country, cost or health. Store which provider handled each payment, because captures and refunds must go to the same one. And reconcile against each provider's reports separately. Having two also gives failover for new payments when one is down.
Max asks
“Should the order service wait for the payment, or continue asynchronously?”
For authorisation at checkout, wait, with a timeout of a few seconds, because the customer needs to know whether the order went through. If the result is unknown, show a pending state and confirm later by email. Capture and refunds happen later and can be fully asynchronous, driven by events like order shipped.
Max asks
“A customer disputes a charge with their bank. What happens in your system?”
The provider sends a dispute webhook. We create a dispute record linked to the payment, move the disputed amount into a held account in the ledger, and notify the team to submit evidence, like proof of delivery, before the deadline. If we win, the hold is released; if we lose, the amount and a fee leave our books, as ledger entries. The payment's state machine gains a disputed branch, and nothing is ever edited in place.
Recap
- 010 to 5: requirementsAuthorise, capture, refund; never twice, never lost
- 025 to 10: numbers and partiesLow scale; provider, network, issuer; tokens
- 0310 to 20: API and state machineInteger amounts, idempotency keys, conditional transitions
- 0420 to 35: correctnessKeys on both hops, unknown state, double-entry ledger
- 0535 to 45: the restWebhooks, reconciliation, refunds, security
On the clock: five minutes of requirements, ending with: correctness first, never charge twice, never lose a payment. Five minutes on the numbers and the parties, showing that scale is modest and that a provider with tokens keeps card data away from us.
Ten minutes on the API and the state machine: integer amounts, idempotency keys, and transitions written before and after each external call.
Fifteen minutes on correctness: idempotency on both hops, the unknown state resolved by asking the provider, and the append-only double-entry ledger. And ten minutes on webhooks, daily reconciliation, refunds and security. If the interviewer hears you treat a timeout as unknown rather than failed, you will have passed the most important test in this question.
Payments interviews are mostly about failure cases, and the follow-up questions come fast. Practicing out loud is the best way to get comfortable with them. You can practice this exact question with Max, our AI interviewer, at interview dry run dot com. It is free to start, and you get a scored report with what to fix. The written lesson, with every diagram, is on the site too. See you in lesson fourteen.
Now say it out loud
Watching an answer is not the same as giving one. Max asks this exact question, pushes back when an answer is vague and keeps time, then scores you per skill.
Practice with MaxFree: a 5-minute voice round and unlimited typed drills, with scored feedback. No card, and your camera is never recorded.