Basics
Start with the product and the ideas it depends on. If these are clear, the design that follows will feel obvious rather than memorised.
1.1Product in plain words
Who uses it, what a normal day looks like, and why it is harder than it seems.
The checkout of a shopping app: confirm the cart, choose card, UPI or wallet, approve the payment, and get an order confirmation. During big sales it handles tens of thousands of orders an hour.
Who uses it
- Shoppers: in a hurry, sometimes on bad networks, sometimes tapping Pay twice.
- Banks and payment providers: approve payments, sometimes minutes later.
- Finance teams: must match every rupee received with an order.
A day in the life
- He taps Pay ₹2,499 with UPI.
- His UPI app opens; he approves with his PIN and returns.
- The app shows ‘Confirming payment…’ because the bank has not replied yet.
- Thirty seconds later the provider tells the server the payment succeeded.
- His screen switches to ‘Order placed’ and he gets a notification and email.
Why it is hard
Double taps, retries and lost responses must still produce one charge.
Some payments confirm minutes after the user acts, or the response is lost.
Storing card numbers brings heavy compliance obligations.
Every payment must match an order and a ledger entry.
Like ordering at a counter with a numbered token: if you ask twice, the cashier sees the same token number and doesn’t make a second order.
1.2Key concepts
The building blocks this design uses. Each one appears again in the answer.
Every payment attempt carries a key. Repeating the request with the same key returns the original result instead of charging again.
An order moves through explicit states: created, authorising, authorised, captured, failed, refunded. Every transition is recorded, so you always know what happened.
Authorisation reserves money on the card; capture actually takes it. Keeping them separate lets you cancel cleanly if stock runs out.
Banks often confirm minutes later. 'Pending' is a real state, settled from provider webhooks or by polling, never by guessing.
Every money movement is written as balanced debit and credit entries, so totals always reconcile and mistakes are visible.
Card numbers never touch your servers: the provider's SDK turns them into tokens, which keeps most of your system out of PCI compliance scope.
Learn them properly in the deep dives:
Question
Now read the question closely. Agree on what you are building, ask what is unclear, and work out the numbers before you draw anything.
2.1Brief and scope
The question exactly as the interviewer asks it, and what they want to learn from your answer.
Design checkout for a mobile commerce app processing 50,000 orders an hour at peak sales. Cards, UPI and wallets. Networks are flaky, users double-tap, and banks sometimes take minutes to confirm. No customer may ever be charged twice, and no order may be lost.
What it tests: End-to-end idempotency, state machines, asynchronous confirmation, reconciliation and keeping card data out.
The answer in one sentence. An idempotency key from the first tap, a server-side order state machine, the provider’s webhook as the source of truth, and daily reconciliation.
How to spend the 45 minutes
- Clarify~5 minAsk questions, agree on scope and write down assumptions.
- Estimate~5 minRough numbers for users, data and traffic, and what they imply.
- High-level design~11 minComponents, data flow and the key API on the board.
- Deep dive~16 minThe two or three hardest parts, with real mechanisms.
- Trade-offs and wrap-up~9 minDecisions, failure modes, and what you would do next.
2.2Clarify the problem
The first five minutes. Each answer removes a guess from your design.
| You ask | Interviewer answers |
|---|---|
| Who processes payments? | A payment service provider (PSP) such as Stripe, Adyen or Razorpay. |
| Asynchronous methods? | UPI and some cards with 3-D Secure confirm minutes later via webhook. |
| Inventory reservation? | Stock must be held during payment for up to 10 minutes. |
| Refunds and partial captures? | Refunds yes, partial captures for split shipments later. |
2.3Estimate the scale
Say the arithmetic out loud. What matters is the order of magnitude and what it forces you to do.
| Metric | Estimate | How |
|---|---|---|
| Peak orders | 50k/hour ≈ 14/s | |
| Payment API calls | ≈ 60–80/s | create, confirm, webhook, status polls |
| Webhook volume | ≈ 30/s at peak | several events per payment |
| Reconciliation | daily PSP settlement files | match every captured payment |
Detailed answer
The design itself, from the big picture down to the code: components first, then one request end to end, then the parts interviewers push hardest on.
3.1Architecture
The app never decides whether a payment succeeded. It drives a server-side order state machine, and the PSP’s webhook is the source of truth for money.
- Idempotency key
- The app creates a UUID when the user lands on the payment step and sends it with every attempt. The order service and the PSP both dedupe on it, so double taps and retries create one charge.
- Order state machine
- created → payment_pending → paid → fulfilled, with failed, expired and refunded branches. Transitions are conditional updates, so two events can never both move an order.
- PSP SDK
- Card numbers go from the SDK straight to the PSP and come back as a token. Your servers never see them, which keeps you out of most PCI scope.
- Webhook receiver
- Verifies the signature, stores the raw event, dedupes on event ID and applies it to the order. Webhooks arrive late, twice or out of order; the state machine tolerates all three.
- Ledger and reconciliation
- Every money movement is an append-only ledger entry. A daily job matches the PSP settlement report against the ledger and flags any difference.
3.2Key flow, step by step
A UPI payment where the response is lost and the user taps Pay again.
- The second tap reuses the same idempotency key, so it returns the existing order instead of creating a new charge.
- The app shows ‘confirming payment’ while waiting. It polls the order with backoff and also listens for a push, but the webhook decides.
- If the webhook never comes, a sweeper queries the PSP for every order stuck in payment_pending beyond its window.
3.3Front end
Checkout UI is mostly about honesty under uncertainty: never let users create a second charge, never claim success or failure before the server knows, and survive the app being killed while the user is in another app approving payment.
Screen map
- Payment method
- Saved methods are tokens from the provider, displayed as ‘Visa •• 4417’. The app never sees full card numbers.
- Provider sheet
- The provider SDK collects card details or launches the UPI intent; it returns a token or a status to the app.
- Confirming
- Shows a calm message and a timer. It polls the order with backoff and listens for a push; it never retries the charge itself.
- Return from another app
- Android returns through an activity result or deep link; iOS through a universal link. Either way the screen reloads the order from the server by its ID.
Client layers
| Layer | Technology | Responsibility |
|---|---|---|
| UI | Compose / SwiftUI / React Native | Checkout screens and result states |
| Checkout ViewModel | Kotlin sealed state machine | Holds the idempotency key and order ID |
| Saved state | SavedStateHandle / SceneStorage / persisted store | Keeps key and order ID across process death |
| Payment SDK | Stripe, Adyen, Razorpay SDKs | Collect payment details, 3-D Secure, UPI intents |
| Order client | Retrofit / URLSession | Create order, poll status |
Every state the user can see
| State | What the user sees | How it works |
|---|---|---|
| Ready | Pay button enabled with amount | No order yet |
| Submitting | Button disabled with spinner | POST /orders in flight with key K |
| Awaiting approval | ‘Approve in your UPI app’ | External app launched |
| Confirming | ‘Confirming payment…’ and timer | Order is payment_pending |
| Paid | Order placed with summary | Server says paid |
| Failed | Reason in plain words, try another method | Server says failed |
| Unknown | ‘We’ll confirm within 10 minutes; you won’t be charged twice’ | Pending past the polling window |
Code
Checkout state that survives process death (Kotlin)
1sealed interface CheckoutUi {2 data object Ready : CheckoutUi3 data object Submitting : CheckoutUi4 data class Confirming(val orderId: String) : CheckoutUi5 data class Paid(val orderId: String) : CheckoutUi6 data class Failed(val reason: String) : CheckoutUi7}8 9class CheckoutViewModel(private val saved: SavedStateHandle, private val api: OrderApi) : ViewModel() {10 private val idemKey: String = saved["idemKey"] ?: UUID.randomUUID().toString().also { saved["idemKey"] = it }11 val ui = MutableStateFlow<CheckoutUi>(saved.get<String>("orderId")?.let { CheckoutUi.Confirming(it) } ?: CheckoutUi.Ready)12 13 fun pay(cart: Cart, method: MethodToken) {14 if (ui.value !is CheckoutUi.Ready) return // no second submit15 ui.value = CheckoutUi.Submitting16 viewModelScope.launch {17 val order = api.createOrder(cart, method, idempotencyKey = idemKey) // same key on every retry18 saved["orderId"] = order.id19 ui.value = CheckoutUi.Confirming(order.id)20 pollUntilFinal(order.id)21 }22 }23 24 private suspend fun pollUntilFinal(id: String) {25 var wait = 1_000L26 repeat(12) {27 when (val s = api.order(id).state) {28 "paid" -> { ui.value = CheckoutUi.Paid(id); return }29 "failed" -> { ui.value = CheckoutUi.Failed(api.order(id).reason); return }30 }31 delay(wait); wait = min(wait * 2, 15_000L)32 } // stays Confirming; push will update33 }34}3.4Data model and APIs
The tables and contracts that make the design concrete.
State transition (SQL)
1UPDATE orders2 SET state = 'paid', paid_at = now(), psp_payment_id = $23 WHERE id = $1 AND state = 'payment_pending'4RETURNING id; -- zero rows = already moved; do nothingWebhook handler (TypeScript)
1app.post('/webhooks/psp', raw(), async (req, res) => {2 const event = psp.verify(req.body, req.headers['psp-signature']); // throws if forged3 const fresh = await db.insertIfAbsent('psp_events', event.id, req.body);4 if (fresh) await queue.publish('payment-events', event); // process async5 res.sendStatus(200); // ack fast6});3.5Tested code, explained
The core of this design as working code, with what each part does and why.
The moves an order can make
List the allowed moves, and impossible states stop being possible.
1enum class OrderState { PAYMENT_PENDING, PAID, FAILED, CANCELLED, REFUND_DUE }2 3/** The only moves an order can make. Anything else is ignored rather than guessed at. */4private val ALLOWED = mapOf(5 OrderState.PAYMENT_PENDING to setOf(OrderState.PAID, OrderState.FAILED, OrderState.CANCELLED),6 OrderState.CANCELLED to setOf(OrderState.REFUND_DUE), // paid after cancelling: give it back7)8 9data class Order(val id: String, val amount: Long, val state: OrderState)ALLOWED- Anything not listed gets ignored. A late failed webhook can't undo a paid order.
OrderState.CANCELLED to setOf(OrderState.REFUND_DUE)- Money arrived after the customer cancelled. It's a named case, not an exception.
Compiled and tested by npm run test:mobile.
Taking payment exactly once
The phone can retry as much as it likes. These methods make that harmless.
1class OrderService(private val priceOf: (cartId: String) -> Long) {2 private val byKey = HashMap<String, Order>()3 private val byId = HashMap<String, String>()4 private val seenEvents = HashSet<String>()5 private var nextOrder = 8806 7 /** A repeat with the same key gets the stored order back. The phone's price is never read. */8 @Synchronized9 fun create(idempotencyKey: String, cartId: String): Order =10 byKey.getOrPut(idempotencyKey) {11 nextOrder += 112 val order = Order("o-$nextOrder", priceOf(cartId), OrderState.PAYMENT_PENDING)13 byId[order.id] = idempotencyKey14 order15 }16 17 /** Providers resend webhooks, so each event ID counts once. */18 @Synchronized19 fun onWebhook(eventId: String, orderId: String, succeeded: Boolean): Order {20 val key = byId.getValue(orderId)21 val order = byKey.getValue(key)22 if (!seenEvents.add(eventId)) return order23 val wanted = when {24 !succeeded -> OrderState.FAILED25 order.state == OrderState.CANCELLED -> OrderState.REFUND_DUE26 else -> OrderState.PAID27 }28 if (wanted !in ALLOWED[order.state].orEmpty()) return order29 return order.copy(state = wanted).also { byKey[key] = it }30 }31 32 @Synchronized33 fun cancel(orderId: String): Order {34 val key = byId.getValue(orderId)35 val order = byKey.getValue(key)36 if (OrderState.CANCELLED !in ALLOWED[order.state].orEmpty()) return order37 return order.copy(state = OrderState.CANCELLED).also { byKey[key] = it }38 }39 40 /** Daily: find what the provider charged that we still think is waiting. */41 @Synchronized42 fun reconcile(providerPaidIds: Set<String>): List<String> =43 byKey.values.filter { it.state == OrderState.PAYMENT_PENDING && it.id in providerPaidIds }.map { it.id }44}byKey.getOrPut(idempotencyKey)- A repeat returns the stored order. In production, a unique constraint does this.
priceOf(cartId)- The server works out the price. Whatever the phone claims is never read.
seenEvents.add(eventId)- Providers resend webhooks, so each event counts once.
reconcile(...)- Runs daily, and finds charges whose webhook never arrived.
Compiled and tested by npm run test:mobile.
What the customer sees
The phone never decides what happened. It just shows the last answer it got.
1sealed interface CheckoutUi {2 data object Confirming : CheckoutUi3 data class Done(val orderId: String) : CheckoutUi4 data object TryAnotherMethod : CheckoutUi5 data object Refunding : CheckoutUi6}7 8/** No network answer means Confirming. The phone never claims failure when it does not know. */9fun checkoutUi(lastKnown: Order?): CheckoutUi = when (lastKnown?.state) {10 null, OrderState.PAYMENT_PENDING -> CheckoutUi.Confirming11 OrderState.PAID -> CheckoutUi.Done(lastKnown.id)12 OrderState.FAILED, OrderState.CANCELLED -> CheckoutUi.TryAnotherMethod13 OrderState.REFUND_DUE -> CheckoutUi.Refunding14}null, OrderState.PAYMENT_PENDING -> CheckoutUi.Confirming- No answer means confirming, never failed. Telling someone a payment failed when it succeeded makes them pay twice.
Compiled and tested by npm run test:mobile.
3.6Hard parts, in depth
Where interviewers spend the second half of the round.
Idempotency at three layers
The button disables on tap, but that is cosmetic. The real guarantee is the idempotency key: the order service stores it with a unique constraint and returns the stored response for repeats, and the same key is forwarded to the PSP, which also dedupes.
Keys expire after a day. If a user deliberately starts a new checkout, the app generates a new key.
Unknown outcomes
A timeout does not mean failure. The payment may have succeeded at the bank. The order stays payment_pending and the app says so, while webhooks and a status sweeper resolve it.
Never auto-retry a capture with a new key after a timeout; that is how double charges happen.
Inventory holds
Stock is reserved with a hold that expires in ten minutes. A paid event converts the hold into a sale; an expired hold returns stock. If payment succeeds after the hold expired, the order goes to a manual or automatic refund path.
Q&A
The questions that come after the design, with model answers. Answer each one out loud before opening it.
4.1Follow-up questions
What the interviewer asks once the main design is on the board.
How do you test this?
What does the user see if they kill the app mid-payment?
How do refunds work?
4.2Front-end follow-ups
Questions aimed at the client: rendering, state and devices.
The app is killed while the user is in the UPI app. What happens on return?
Why not show success when the SDK says success?
4.3Incidents, probes and traps
Realistic production incidents and pointed probes, grouped by topic.
The product 1
ProbeThe network fails after the user taps Pay. Should the app say the payment failed?
Requirements 1
TrapWhat do candidates forget to ask in a payments round?
Scale 1
ProbeFourteen orders a second is small. Why is this still hard?
Architecture 2
IncidentDuring a sale, customers were charged twice. Logs show two payment intents for one order.
ProbeWhy acknowledge webhooks before processing them?
The key flow 1
IncidentOrders sat in payment_pending for hours although money was taken.
Front end 2
IncidentAndroid users return from the UPI app to an empty checkout, and some pay again.
ProbeHow does the UI prevent double submission?
Data and APIs 1
TrapWhy a conditional UPDATE instead of reading the order state and then writing?
The hard parts 2
IncidentPayment succeeded after the inventory hold expired and the last item went to someone else.
ProbeYour payment provider is down during a sale. What happens?
Trade-offs 1
ProbeWhy an append-only ledger instead of updating a balance column?
Failures 2
IncidentReconciliation finds ₹3.2 lakh captured with no matching order.
IncidentThe webhook signing secret leaked into logs.
Extra depth
What turns a good answer into a strong one: the decisions you rejected, how the system fails, and the signals of seniority.
5.1Trade-offs and decisions
Every choice has a cost. Naming it is what interviewers listen for.
Show detailsHide details
| Decision | Chosen | Rejected | Why |
|---|---|---|---|
| Source of truth | PSP webhook + sweeper | Client callback | Clients lie, crash and lose responses; only the PSP knows. |
| Card data | PSP SDK tokenisation | Own card form | Keeps the app and backend out of most PCI DSS scope. |
| Processing webhooks | Store, ack, process async | Process inline | PSPs retry on slow responses; inline work causes duplicates and timeouts. |
| Ledger | Append-only entries | Balance column updates | Auditable, reconcilable, and never loses history. |
5.2Failure modes
What breaks in production, and how the design keeps working when it does.
Show detailsHide details
| What breaks | How the design copes |
|---|---|
| Webhook delayed for hours | Sweeper polls PSP for pending orders; user sees ‘confirming’. |
| Webhook delivered twice | Event ID dedupe and conditional state transitions. |
| Payment succeeds after order expired | Automatic refund with notification, recorded in the ledger. |
| PSP outage | Circuit breaker, route to a secondary PSP for new payments, queue captures. |
5.3Performance and accessibility
The client-side details that separate a demo from a product.
Performance
- Preload the provider SDK and saved methods when the cart opens, so the payment sheet appears instantly.
- Show the amount and a single primary action; every extra field costs conversion.
- Keep the confirming screen lightweight; it may be on screen for minutes.
Accessibility and localisation
- Amounts are read correctly by screen readers, including currency.
- Indian number grouping (₹1,23,456) via locale-aware formatting.
- Error messages say what to do next, not error codes.
5.4Senior versus principal
The same design, answered at two levels. Use the rubric to score yourself.
A senior answer uses a PSP SDK and handles failure screens.
A principal answer makes idempotency explicit at every hop, models orders as a state machine with conditional transitions, treats timeouts as unknown, designs webhooks and reconciliation, and keeps card data out of scope.
Score yourself
5.5Whiteboard
Draw the design here, in this order. It stays in this browser.
- Order state machine with all branches
- App → order service with an idempotency key
- PSP with webhook back to a receiver that dedupes
- Ledger and daily reconciliation
- Inventory hold with a TTL