/Interview
Interview room · Mobile system design · 45 minutes

Checkout and payments that never double-charge

PracticeSystem designTier 3 · Edge casesCreate45 minMobile systems

You will be able to: design checkout and payments that never double-charge in 45 minutes, and defend each trade-off.

Mobile engineeringAll mobile pages

Op 7f3a's idempotency key now protects money. The new lesson is where offline-first stops: the server and provider decide, never the phone. Start from the basics in Day 11 →

Study with AI

Ready45:00
ClarifyEstimateHigh-level designDeep diveTrade-offs and wrap-up
Part 1 of 5

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

  1. He taps Pay ₹2,499 with UPI.
  2. His UPI app opens; he approves with his PIN and returns.
  3. The app shows ‘Confirming payment…’ because the bank has not replied yet.
  4. Thirty seconds later the provider tells the server the payment succeeded.
  5. His screen switches to ‘Order placed’ and he gets a notification and email.

Why it is hard

Never charge twice

Double taps, retries and lost responses must still produce one charge.

Answers arrive late

Some payments confirm minutes after the user acts, or the response is lost.

Card data is dangerous

Storing card numbers brings heavy compliance obligations.

Money must reconcile

Every payment must match an order and a ledger entry.

Think of it like this

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.

01Idempotency

Every payment attempt carries a key. Repeating the request with the same key returns the original result instead of charging again.

02Payment state machine

An order moves through explicit states: created, authorising, authorised, captured, failed, refunded. Every transition is recorded, so you always know what happened.

03Authorise, then capture

Authorisation reserves money on the card; capture actually takes it. Keeping them separate lets you cancel cleanly if stock runs out.

04Unknown outcomes

Banks often confirm minutes later. 'Pending' is a real state, settled from provider webhooks or by polling, never by guessing.

05Double-entry ledger

Every money movement is written as balanced debit and credit entries, so totals always reconcile and mistakes are visible.

06Tokenised cards

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:

Part 2 of 5

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.

Interviewer

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

  1. Clarify~5 minAsk questions, agree on scope and write down assumptions.
  2. Estimate~5 minRough numbers for users, data and traffic, and what they imply.
  3. High-level design~11 minComponents, data flow and the key API on the board.
  4. Deep dive~16 minThe two or three hardest parts, with real mechanisms.
  5. 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 askInterviewer 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.

MetricEstimateHow
Peak orders50k/hour ≈ 14/s
Payment API calls≈ 60–80/screate, confirm, webhook, status polls
Webhook volume≈ 30/s at peakseveral events per payment
Reconciliationdaily PSP settlement filesmatch every captured payment
Part 3 of 5

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.

APPCOMMERCE BACKENDPROVIDERCheckout screenidempotency keyPSP SDKcard / UPI UIOrder servicestate machineInventoryholds with TTLPayment servicePSP adapterLedgerappend-onlyWebhook receiververify + dedupeReconciliationdaily jobPSPauthorise · captureBank / UPIcustomer approvalorderholdcreate intentAPItokenisedwebhookevententries
ClientServiceData storeExternal
Reference design. Boxes show components; arrows show who calls whom.
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.

UserAppOrder svcPayment svcPSPtap PayPOST /orders (key K)create intent (K)create (K)intent pi_9pending · client_secretSDK: collect UPINetwork drops; user taps Pay againPOST /orders (same K)same order, still pendingwebhook: succeededmark paid (if pending)poll statuspaid ✓
Solid arrows are requests; dashed arrows are responses.
  1. The second tap reuses the same idempotency key, so it returns the existing order instead of creating a new charge.
  2. The app shows ‘confirming payment’ while waiting. It polls the order with backoff and also listens for a push, but the webhook decides.
  3. 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

Cartitems · totalsAddresssaved · newPayment methodUPI · card · walletProvider sheetPSP SDK UISuccessorder id · ETAConfirmingpolling + pushFailedreason · retryUPI appexternal approvalpayintentreturnpaidfailed
ClientExternal
Screens and how users move between them.
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

LayerTechnologyResponsibility
UICompose / SwiftUI / React NativeCheckout screens and result states
Checkout ViewModelKotlin sealed state machineHolds the idempotency key and order ID
Saved stateSavedStateHandle / SceneStorage / persisted storeKeeps key and order ID across process death
Payment SDKStripe, Adyen, Razorpay SDKsCollect payment details, 3-D Secure, UPI intents
Order clientRetrofit / URLSessionCreate order, poll status

Every state the user can see

StateWhat the user seesHow it works
ReadyPay button enabled with amountNo order yet
SubmittingButton disabled with spinnerPOST /orders in flight with key K
Awaiting approval‘Approve in your UPI app’External app launched
Confirming‘Confirming payment…’ and timerOrder is payment_pending
PaidOrder placed with summaryServer says paid
FailedReason in plain words, try another methodServer 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)

checkout-state-that.ktKotlin
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}
34 linesUTF-8Kotlin

3.4Data model and APIs

The tables and contracts that make the design concrete.

State transition (SQL)

state-transition-sql.sqlSQL
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 nothing
4 linesUTF-8SQL

Webhook handler (TypeScript)

webhook-handler-typescript.tsTypeScript
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});
6 linesUTF-8TypeScript

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.

Checkout.ktKotlin
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)
9 linesUTF-8Kotlin
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.

Checkout.ktKotlin
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}
44 linesUTF-8Kotlin
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.

Checkout.ktKotlin
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}
14 linesUTF-8Kotlin
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.

Part 4 of 5

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?
PSP sandbox with forced failures, contract tests for webhook payloads, and chaos tests that drop responses between every step.
What does the user see if they kill the app mid-payment?
On next launch the app reads the order by its ID and shows the server state: paid, pending or failed with a retry.
How do refunds work?
A refund is its own idempotent operation with its own key and ledger entries; the order moves to refunded only on the PSP’s confirmation.

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?
SavedStateHandle restored the order ID, so the screen reloads the order from the server and shows its real state; the idempotency key prevents a second charge if Pay is tapped again.
Why not show success when the SDK says success?
The SDK result can be lost or wrong; the order’s server state, driven by the provider webhook, is the only truth.

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?
No. The outcome is unknown; the payment may have succeeded at the bank. Show ‘confirming’, poll the order and wait for the provider’s webhook. Saying ‘failed’ invites a second payment.

Requirements 1

TrapWhat do candidates forget to ask in a payments round?
Asynchronous methods like UPI and 3-D Secure, refunds and partial captures, inventory holds, multiple providers, and how reconciliation is done. Each one changes the state machine.

Scale 1

ProbeFourteen orders a second is small. Why is this still hard?
The challenge is correctness, not throughput: sale spikes of ten times, provider rate limits, retried webhooks, lost responses and hot inventory rows. One duplicate charge costs more trust than a slow page.

Architecture 2

IncidentDuring a sale, customers were charged twice. Logs show two payment intents for one order.
The client generated the idempotency key per request, so a retry made a new one, or never forwarded it to the provider. Create the key when the user enters the payment step, persist it across process death, enforce it with a unique constraint, forward it to the provider, and auto-refund duplicates found by reconciliation.
ProbeWhy acknowledge webhooks before processing them?
Providers retry when your endpoint is slow, creating duplicates and timeouts. Verify the signature, store the raw event, return 200 and process asynchronously with dedupe on the event ID.

The key flow 1

IncidentOrders sat in payment_pending for hours although money was taken.
The webhook endpoint was failing (a rotated signing secret or a firewall change) and nothing else checked. Run a sweeper that queries the provider for pending orders past their window, alert on webhook failure rate, and track the age of the oldest pending order.

Front end 2

IncidentAndroid users return from the UPI app to an empty checkout, and some pay again.
The OS killed the process while the UPI app was open and the screen state was lost. Persist the idempotency key and order ID in SavedStateHandle, and on return reload the order from the server and show its real state.
ProbeHow does the UI prevent double submission?
The button disables and the screen state machine ignores Pay unless it is in Ready, with the same idempotency key reused on retries. The UI reduces duplicates; the backend key guarantees it.

Data and APIs 1

TrapWhy a conditional UPDATE instead of reading the order state and then writing?
Two events, such as a webhook and a sweeper result, can race. ‘UPDATE … WHERE state = payment_pending’ lets exactly one win atomically; the other sees zero rows and does nothing.

The hard parts 2

IncidentPayment succeeded after the inventory hold expired and the last item went to someone else.
Detect it when the paid event arrives, then auto-refund with an apology or offer a backorder, and record it in the ledger. Prevent it by making holds longer than the payment window and extending holds while payment is pending.
ProbeYour payment provider is down during a sale. What happens?
A circuit breaker trips, new payments route to a secondary provider, captures for existing intents are queued, and the app shows a clear message. Never retry a capture with a new idempotency key.

Trade-offs 1

ProbeWhy an append-only ledger instead of updating a balance column?
Every change is auditable and reconcilable, history can never be lost, and corrections are new entries. Finance and regulators can rebuild any balance at any point in time.

Failures 2

IncidentReconciliation finds ₹3.2 lakh captured with no matching order.
Payments were created before orders, or orders failed to commit after timeouts, so webhooks referenced unknown orders. Always create the order before the payment intent, store the provider ID on it, park unknown webhooks for review, and apply an automatic refund policy after a window.
IncidentThe webhook signing secret leaked into logs.
Rotate it immediately, scrub logs, and add log redaction. Because forged ‘paid’ events are possible, also confirm high-value payments by fetching them from the provider’s API before fulfilment.
Part 5 of 5

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
DecisionChosenRejectedWhy
Source of truthPSP webhook + sweeperClient callbackClients lie, crash and lose responses; only the PSP knows.
Card dataPSP SDK tokenisationOwn card formKeeps the app and backend out of most PCI DSS scope.
Processing webhooksStore, ack, process asyncProcess inlinePSPs retry on slow responses; inline work causes duplicates and timeouts.
LedgerAppend-only entriesBalance column updatesAuditable, 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 breaksHow the design copes
Webhook delayed for hoursSweeper polls PSP for pending orders; user sees ‘confirming’.
Webhook delivered twiceEvent ID dedupe and conditional state transitions.
Payment succeeds after order expiredAutomatic refund with notification, recorded in the ledger.
PSP outageCircuit 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.

Senior answer

A senior answer uses a PSP SDK and handles failure screens.

Principal answer

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.

  1. Order state machine with all branches
  2. App → order service with an idempotency key
  3. PSP with webhook back to a receiver that dedupes
  4. Ledger and daily reconciliation
  5. Inventory hold with a TTL
Tip: draw boxes first, then arrows, then label them with Text.
AI Engineer · interview room