Designing a Reliable Checkout and Charge Pipeline
System DesignModel answerLast updated
Sketch a high-level payment backend that charges customers via a third-party provider, guaranteeing no double charges and no orders marked paid without collected funds.
You are asked to sketch, at a high level and within a short time box, the backend for taking payments in an online product. A customer goes through checkout, gets charged, and the purchase is only confirmed after the money has actually been collected.
Your system does not talk to card networks directly. It relies on an external payment service provider (PSP) that handles the card or wallet transaction and reports results back to you.
Requirements
- Correctness matters more than speed. A customer must never be charged twice for one purchase, and an order must never be marked as paid unless the funds were really collected.
- Stay at a high level: describe the main components, the end-to-end flow, the data you persist, and how you deal with failures.
What to cover
- The flow from the moment the user clicks "pay" until the order is confirmed.
- How retries are made safe at each step.
- How you model a payment's lifecycle and record money movement.
- How you handle the PSP's asynchronous result notifications.
- How you detect and repair mismatches with the PSP's records.
- What happens when something fails midway (timeouts, crashes, duplicate or missing notifications).
Questions you may want to ask first
- Is this only money coming in from users, or do we also pay out to sellers?
- Do we ever touch raw card numbers, or does the provider's hosted page or SDK tokenize them?
- Which payment methods and currencies are in scope?
- What is the expected volume and peak rate?
- Does the user wait for a synchronous result, or can confirmation arrive later?
Hints
Hint 1
Generate a unique key per payment attempt on your side and persist it before calling the provider, so any retry can reuse it.
Hint 2
Model the payment as a state machine (created, pending, succeeded, failed, and so on) and only allow forward transitions; treat provider notifications as events that drive those transitions.
Hint 3
Assume every message can be delayed, duplicated, or lost: make handlers idempotent, verify notification signatures, and run a periodic job that compares your records with the provider's.
Hint 4
Store money as integer minor units with a currency code, and write ledger entries append-only rather than editing balances.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions (state them up front)
- Pay-in only; payouts are out of scope for now.
- The PSP's hosted fields or SDK tokenize card data, so our servers never see card numbers. This keeps us out of the heaviest PCI scope.
- Confirmation can be asynchronous: the user may see "processing" briefly.
- Moderate volume (hundreds of payments per second at peak); the bottleneck is correctness, not throughput.
Components
- Checkout/Order service: owns the order and its status.
- Payment service: owns payment attempts, the state machine, and calls to the PSP.
- Ledger: append-only record of money movements.
- Webhook receiver: accepts the PSP's notifications, verifies signatures, enqueues events.
- Queue/worker: processes events and runs retries.
- Reconciliation job: compares our data with PSP reports.
- Database: relational (transactions and unique constraints are essential here).
End-to-end flow
- The user starts checkout. The Order service creates an order in
PENDING_PAYMENTwith the total in integer minor units (e.g. 1999 for 19.99 USD) plus a currency code. - The client asks the Payment service to pay. It creates a
paymentrow with a unique idempotency key (derived from the order and attempt number) in stateCREATED. A unique constraint on the key means a repeated request returns the same payment. - The client collects card details directly in the PSP's hosted component, receiving a token.
- The Payment service calls the PSP to charge the token, passing our idempotency key so the PSP deduplicates too. Before the call, we persist state
PROCESSING, so a crash leaves a trace. - The PSP answers synchronously (success, decline, or "pending/requires action") and later sends a webhook with the final outcome.
- The webhook receiver verifies the signature, stores the raw event (deduplicated by provider event ID), and enqueues it.
- A worker applies the event: moves the payment to
SUCCEEDEDorFAILED, writes ledger entries, and, in the same transaction, writes an outbox record telling the Order service to mark the order paid. - The Order service consumes that event idempotently and sets the order to
PAID, then triggers fulfillment.
The source of truth for "paid" is the confirmed PSP outcome, not the browser redirect or the client's claim.
Idempotency
- Client to us: idempotency key on the pay request.
- Us to PSP: the same key on every retry of the same attempt, so a timeout followed by a retry cannot double-charge.
- PSP to us: webhook events deduplicated by event ID; applying the same event twice is a no-op.
- Internal consumers: the order update is conditional (
PENDING_PAYMENTtoPAIDonly) and keyed by payment ID.
State machine
CREATED -> PROCESSING -> SUCCEEDED | FAILED, with REQUIRES_ACTION (e.g. 3-D Secure) as an intermediate state and later REFUNDED/PARTIALLY_REFUNDED. Transitions are enforced with conditional updates (UPDATE ... WHERE state = 'PROCESSING'). Terminal states are never overwritten, so a late or out-of-order event cannot revert a success.
Data model
orders(id, user_id, amount_minor, currency, status)payments(id, order_id, idempotency_key UNIQUE, psp_reference, state, amount_minor, currency, created_at, updated_at)ledger_entries(id, payment_id, account, direction, amount_minor, currency, created_at): append-only, double-entry (debit and credit sum to zero). Corrections are new entries, never edits.psp_events(event_id UNIQUE, payload, received_at, processed_at)outbox(id, topic, payload, published_at)
Never use floats for money.
Failure handling
- Timeout calling the PSP: the outcome is unknown. Do not assume failure. Leave the payment in
PROCESSING, then query the PSP by idempotency key or reference, or wait for the webhook. Retry with the same key. - Crash between PSP success and our DB write: the webhook or the status-polling job repairs the state.
- Duplicate webhooks: deduplicated by event ID; state transitions are idempotent.
- Lost webhooks: a sweeper polls payments stuck in
PROCESSINGlonger than a threshold. - Out-of-order events: ignore transitions that go backward in the state machine.
- Forged webhooks: verify signature and optionally re-fetch the payment from the PSP before acting.
- Crash between payment update and order update: the transactional outbox guarantees the order event is eventually published.
Reconciliation
A daily (or hourly) job pulls the PSP's settlement report and compares it with our payments and ledger by PSP reference, amount, and currency. Mismatches fall into: paid at PSP but not by us (apply the missing transition, or refund), recorded by us but absent at the PSP (investigate, likely mark failed), and amount differences. Discrepancies raise alerts and go to a review queue.
Trade-offs
- Synchronous confirmation gives a better UX but is fragile under timeouts; relying on webhooks plus polling is more robust at the cost of a short "processing" state.
- A single relational DB keeps transactions simple; at higher scale, shard by user or order ID, keeping each payment's rows together.
- Using multiple PSPs adds resilience but multiplies reconciliation complexity.
Common mistakes
- Marking an order paid from the client redirect.
- Retrying a charge without an idempotency key.
- Treating a timeout as a failure and charging again.
- Storing amounts as floats, or editing ledger rows in place.
- Skipping reconciliation, or ignoring webhook signature checks.
- Spending the whole time on scaling and leaving the correctness core undiscussed.