Skip to content
Commitwise
Menu
System Design

Design a payment system

Design the payment system of an online shop step by step, with requirements where correctness beats speed, a payment state machine, idempotency keys from the client to the provider, a double-entry ledger, webhooks and timeouts that mean "unknown", daily reconciliation, refunds, and keeping card data out of your servers, with code in Kotlin, Java, Swift and TypeScript.

advanced

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

A customer taps “Pay €49.99”. The app shows a spinner, the network drops, and the customer taps again. Did the first payment go through? Will they be charged twice? A week later, finance finds that the provider’s report shows €1,240 more than the shop’s database, and nobody can explain which orders the difference belongs to.

“Design a payment system” is a favorite senior interview question because the hard part isn’t throughput: a shop with a million orders a day makes about 12 payments a second. The hard part is correctness when every network call can time out, every message can arrive twice, and money must always add up.

New to some of these? Open what you need, or skip ahead.

Basics:What is a payment provider?

Shops rarely talk to banks directly. A payment provider (Stripe, Adyen, Braintree…) accepts card details, talks to the card networks and banks, and tells the shop whether the payment succeeded. It also sends webhooks: HTTP requests from the provider to the shop’s server when something changes later, like a refund or a dispute.

Basics:What is idempotency?

An operation is idempotent if doing it twice has the same effect as doing it once: setting a value is idempotent, adding to it isn’t. Payments use an idempotency key, a unique id sent with the request, so the server can recognize a repeat and return the first result instead of charging again. See idempotencyIdempotencyAn operation is idempotent if doing it twice has the same effect as doing it once.Open in glossary →.

Part Not started

Step 1: Requirements and estimates

Start by asking what the payment system must do and what must never happen.

Functional requirements:

  • Customers pay for orders with cards and wallets (Apple Pay, Google Pay), including extra verification like 3-D Secure.
  • The shop can refund all or part of a payment.
  • The shop pays out to sellers (if it’s a marketplace), minus its fees.
  • Finance gets reports that match what the provider and the bank say.

What must never happen:

  • Charging a customer twice for one order.
  • Losing track of a payment: money taken but no order, or an order marked paid without money.
  • Card numbers stored on the shop’s servers.

The volumes are small compared with other systems, so the design focuses on correctness and auditability, not speed.

Clarify: payment methods and regions (cards, wallets, bank transfers, SCA/3-D Secure in Europe), authorization vs capture (capture on shipment?), partial refunds and partial captures, marketplace splits and payouts, currencies (store amounts as integer minor units with an explicit currency, never floats), and reporting needs. Non-functional: exactly-once effect per order attempt, durability of every money movement, an append-only audit trail, reconciliation with the provider’s settlement reports, and PCI DSS scope minimization through provider tokenization (hosted fields, SDKs) so raw card data never touches your servers. Throughput is modest; availability matters at checkout, but correctness wins every trade-off: a delayed confirmation is acceptable, a double charge isn’t.

Orders:                    1 million / day  → ~12 payments / s average, ~100 / s peak (sales)
Payment API calls:         ~3 per payment (create, confirm, webhook) → a few hundred / s at peak
Ledger entries:            ~4 per payment (charge, fee, payout, refunds) → ~4 million rows / day
Storage:                   ~1 KB per entry with metadata → ~4 GB / day, kept 7–10 years (audit, tax)

Throughput is easy. The hard requirements are:
  - exactly-once effect per order, despite retries and timeouts
  - every cent traceable from order → payment → ledger → provider report → bank
  • 12 payments per second is nothing for a database. A single well-indexed PostgreSQL instance handles it.
  • The ledger grows forever and is kept for years, because accountants and tax authorities need it.
  • So the questions in the next steps are about what can go wrong, not about scaling.
  • Methods, regions, SCA/3-D Secure, authorize vs capture, partial refunds/captures, marketplace payouts, multi-currency (integer minor units + currency code).
  • Exactly-once effect per order attempt, append-only audit trail, reconciliation with provider settlements, PCI scope minimized via tokenization.
  • Low throughput (tens to hundreds per second); correctness beats latency; “unknown” is a real state after timeouts.

Check this part

  1. What is the hardest requirement in a payment system?

  2. Why should card numbers never reach the shop's servers?

  3. How should amounts be stored?

Payments are low volume but must be exactly-once from the customer's point of view, fully auditable and reconcilable with the provider. Card data stays with the provider (tokenization) to keep PCI scope small. Every external call can time out, so 'unknown' is a real outcome, and money is recorded in a double-entry ledger rather than as balances that get overwritten.

Part Not started

Step 2: State machine, idempotency and the ledger

Payment flow

App / web checkoutPayment servicePayments + ledgerPayment providerWebhook handlerOrder service

Tap a box to see what it does.

A state machine. A payment isn’t just “paid” or “not paid”. It moves through states, and each move is saved in the database:

CREATED → PROCESSING → SUCCEEDED → (PARTIALLY_)REFUNDED
                     ↘ FAILED

The rule: save the state before calling the provider, and save the result after. If the server crashes in between, the payment is stuck in PROCESSING, and a background job knows it must ask the provider what happened.

Idempotency keys, twice. The app creates a key for the order attempt and sends it with every retry, so the payment service recognizes the second tap. The payment service also sends its own key to the provider, so if it retries the provider call after a timeout, the provider doesn’t charge again.

A ledgerDouble-entry ledgerAn append-only record of money movements where every transaction is a set of entries across accounts that sums to zero.Open in glossary →. Instead of a balance column that gets updated, every money movement is written as entries that never change: “customer paid €49.99”, “provider fee €0.75”, “shop revenue €49.24”. Like an accountant’s book, you only add lines; corrections are new lines.

The state machine is the contract: transitions are persisted atomically with their side-effect intents, external calls happen between persisted states, and illegal transitions are rejected. Idempotency is layered: the client key (one per order attempt, stored with a unique constraint and a request fingerprint) makes the API safe to retry; the provider key (derived from the payment id) makes provider calls safe to retry; webhook event ids make notifications safe to replay. A timeout or 5xx from the provider is unknown, not failed: query the provider by your key (or wait for the webhook) before deciding; a reconciler sweeps PROCESSING payments older than a threshold. The ledger is double-entry and append-only: each transaction is a set of entries across accounts (customer receivable, provider clearing, fees, merchant payable) that sum to zero per currency; balances are derived (and can be cached in materialized balances updated in the same transaction). Refunds, chargebacks and corrections are new transactions, never updates. The order service learns about outcomes through outbox events, so payments and orders stay decoupled.

@Transactional
fun createPayment(request: CreatePayment, idempotencyKey: String): Payment {
    // A unique constraint on (merchant_id, idempotency_key) makes concurrent duplicates fail here
    payments.findByIdempotencyKey(request.merchantId, idempotencyKey)?.let { existing ->
        require(existing.fingerprint == request.fingerprint()) { "Key reused for a different payment" }
        return existing                                       // a retry: same answer as the first time
    }
    return payments.save(
        Payment(
            id = PaymentId.new(),
            orderId = request.orderId,
            amountMinor = request.amountMinor,                // 4999, never 49.99
            currency = request.currency,
            state = PaymentState.CREATED,
            idempotencyKey = idempotencyKey,
            fingerprint = request.fingerprint(),
        )
    )
}

fun confirm(paymentId: PaymentId) {
    val payment = transitions.moveTo(paymentId, PaymentState.PROCESSING)     // saved before the call
    val outcome = try {
        provider.charge(payment.toChargeRequest(), idempotencyKey = "pay-${payment.id}")
    } catch (e: ProviderTimeoutException) {
        return                                                // UNKNOWN: the reconciler or a webhook decides
    }
    transitions.complete(paymentId, outcome)                  // SUCCEEDED or FAILED, ledger entries, outbox event
}
@Transactional
public Payment createPayment(CreatePayment request, String idempotencyKey) {
    // A unique constraint on (merchant_id, idempotency_key) makes concurrent duplicates fail here
    Optional<Payment> existing = payments.findByIdempotencyKey(request.merchantId(), idempotencyKey);
    if (existing.isPresent()) {
        if (!existing.get().fingerprint().equals(request.fingerprint())) {
            throw new IdempotencyKeyReusedException();
        }
        return existing.get();                                // a retry: same answer as the first time
    }
    return payments.save(Payment.created(request, idempotencyKey));   // amount in minor units: 4999
}

public void confirm(PaymentId paymentId) {
    Payment payment = transitions.moveTo(paymentId, PaymentState.PROCESSING);   // saved before the call
    ChargeOutcome outcome;
    try {
        outcome = provider.charge(payment.toChargeRequest(), "pay-" + payment.id());
    } catch (ProviderTimeoutException e) {
        return;                                               // UNKNOWN: the reconciler or a webhook decides
    }
    transitions.complete(paymentId, outcome);                 // SUCCEEDED or FAILED, ledger entries, outbox event
}
  • findByIdempotencyKey: a second tap with the same key returns the payment that already exists, instead of creating another one. If the same key arrives with a different amount, that’s a client bug and is rejected.
  • amountMinor = 4999: money is stored as whole cents, because 0.1 + 0.2 isn’t exactly 0.3 in floating point.
  • moveTo(PROCESSING) is saved before the provider call, so a crash leaves a clear trace.
  • A timeout returns without deciding. The card may or may not have been charged; a background job will ask the provider, or a webhook will tell.
Spot the bugA retry that charges twice

Tap the line with the bug.

fun pay(order: Order) {
    try {
        provider.charge(order.cardToken, order.totalMinor, order.currency)
        orders.markPaid(order.id)
    } catch (e: SocketTimeoutException) {
        provider.charge(order.cardToken, order.totalMinor, order.currency)
        orders.markPaid(order.id)
    }
}
void pay(Order order) {
    try {
        provider.charge(order.cardToken(), order.totalMinor(), order.currency());
        orders.markPaid(order.id());
    } catch (SocketTimeoutException e) {
        provider.charge(order.cardToken(), order.totalMinor(), order.currency());
        orders.markPaid(order.id());
    }
}

Predict the output

A payment of €49.99 succeeds with a provider fee of €0.75. The ledger records it as a transaction with three entries: customer receivable −4999, provider clearing +4924, fees +75. What do the entries sum to?

Ledger design details

  • Accounts per purpose and currency: customer receivables, provider clearing, fees, merchant payables, refunds, chargebacks. Never net currencies; FX is its own transaction with a rate.
  • Immutability: entries are insert-only, with database permissions that forbid updates and deletes; corrections are reversing transactions with a reason.
  • Invariants checked continuously: every transaction sums to zero per currency; derived balances match cached balances; payments in terminal states have their expected entries.
  • Time: record both the business time (when the charge happened at the provider) and the booking time, because settlement reports and month-end close depend on them.
  • Persisted state machine: CREATED → PROCESSING → SUCCEEDED/FAILED → REFUNDED; save before and after each external call; reject illegal transitions.
  • Idempotency at three levels: client key (unique + fingerprint), provider key (derived from payment id), webhook event ids.
  • Timeout/5xx = UNKNOWN: query by key or wait for the webhook; a reconciler sweeps stale PROCESSING.
  • Double-entry, append-only ledger; entries sum to zero per currency; balances derived; corrections are new transactions.
  • Orders learn outcomes via outbox events.

Check this part

  1. The provider call times out. What should the payment service do?

  2. Why save the PROCESSING state before calling the provider?

  3. What must the entries of every ledger transaction satisfy?

  4. The same client idempotency key arrives with a different amount. Response?

Each payment moves through an explicit state machine (CREATED, PROCESSING, SUCCEEDED, FAILED, REFUNDED), persisted before and after every external call. The client's idempotency key identifies the payment attempt; the provider gets its own key derived from the payment id. A timeout means 'unknown': query the provider before retrying. Money movements go into an append-only double-entry ledger whose entries always sum to zero.

Part Not started

Step 3: Webhooks, reconciliation and refunds

The provider talks back in two ways:

  • The synchronous answer to the charge call: “succeeded”, “declined”, or “needs 3-D Secure”.
  • Webhooks, later: “this payment succeeded” (after 3-D Secure), “refund completed”, “the customer disputed this charge”.

Webhooks can arrive twice, out of order, or before the synchronous answer. So the webhook handler:

  1. Checks the signature, so nobody can fake “payment succeeded”.
  2. Ignores event ids it has already processed.
  3. Moves the payment’s state machine forward, which refuses impossible moves (like FAILED → SUCCEEDED).

Once a day, a reconciliation job compares the shop’s ledger with the provider’s settlement report (the list of everything the provider processed and paid out). Every difference is investigated: a missing webhook, a bug, or a refund made in the provider’s dashboard by someone on the team.

Webhook handling: verify the signature (and timestamp, to resist replays), store the raw event, dedupe by provider event id with a unique constraint, and apply it through the same transition function as synchronous results, so ordering doesn’t matter (transitions are monotonic; late or stale events are no-ops). Acknowledge quickly and process asynchronously. Unknown outcomes: a reconciler queries the provider for PROCESSING payments older than a few minutes, by your idempotency key or the provider’s payment id, and completes them. Settlement reconciliation: ingest the provider’s reports (API or files), match by provider reference, compare amounts, fees and currencies, and produce a discrepancy queue with categories (missing in ledger, missing at provider, amount mismatch, fee mismatch); totals must also match bank payouts. Refunds are their own state machines and ledger transactions (partial refunds, refund failures); chargebacks arrive as webhooks with deadlines for evidence. Clients after 3-D Secure or redirects poll a status endpoint (or receive a push) until the payment reaches a terminal state, showing “processing” honestly in the meantime.

// After 3-D Secure, the app asks the backend until the payment is final (or gives up and shows "processing")
func awaitFinalStatus(paymentID: String) async throws -> PaymentStatus {
    for attempt in 0..<10 {
        let status = try await api.paymentStatus(id: paymentID)
        if status.isFinal { return status }                         // succeeded, failed or cancelled
        try await Task.sleep(for: .seconds(min(1 << attempt, 8)))   // 1, 2, 4, 8, 8… seconds
    }
    return .processing                                              // tell the user; a push will follow
}
// After 3-D Secure, the app asks the backend until the payment is final (or gives up and shows "processing")
suspend fun awaitFinalStatus(paymentId: String): PaymentStatus {
    repeat(10) { attempt ->
        val status = api.paymentStatus(paymentId)
        if (status.isFinal) return status                           // succeeded, failed or cancelled
        delay(minOf(1L shl attempt, 8L).seconds)                    // 1, 2, 4, 8, 8… seconds
    }
    return PaymentStatus.Processing                                 // tell the user; a push will follow
}
// After 3-D Secure, the web checkout asks the backend until the payment is final
async function awaitFinalStatus(paymentId: string): Promise<PaymentStatus> {
  for (let attempt = 0; attempt < 10; attempt++) {
    const status = await api.paymentStatus(paymentId);
    if (status.isFinal) return status;                              // succeeded, failed or cancelled
    await new Promise((r) => setTimeout(r, Math.min(2 ** attempt, 8) * 1000));
  }
  return { state: "processing", isFinal: false };                   // tell the user; an email will follow
}
  • The app doesn’t decide whether the payment worked. It asks the backend, which knows from the provider’s answer or webhook.
  • The waits grow (1, 2, 4, 8 seconds), so thousands of apps don’t hammer the server.
  • After about a minute it stops and shows “Payment processing” honestly, instead of “failed”. The final result arrives later as a push notification or email, and the order screen updates.

Predict the output

A payment succeeds. The provider sends the payment.succeeded webhook, the handler marks the payment SUCCEEDED, and then the synchronous response finally arrives saying 'requires_action' (3-D Secure was needed, as of when the response was created). What should the state machine do with it?

Production puzzles

Predict the output

Reconciliation finds 37 payments that the provider settled but the shop's ledger shows as FAILED. All happened during a 10-minute window when the provider had high latency. What most likely happened?

Exercisehard

Add marketplace payouts

The shop becomes a marketplace: each order can contain items from several sellers. The platform keeps a 10% commission and pays sellers weekly, minus refunds. Extend the design.

›

Think in ledger accounts: where does the money sit between the customer’s payment and the seller’s payout, and what happens when a refund comes after a payout?

SolutionTry it yourself first
  • Split at capture: when a payment succeeds, the ledger moves money from provider clearing into seller payable accounts (per seller, per currency) and a platform revenue account (commission), in one transaction summing to zero.
  • Refunds debit the seller’s payable (and reverse the commission if policy says so). If the seller was already paid, their payable goes negative, and the next payout nets it out; a policy decides when negative balances are collected.
  • Payouts are a weekly job per seller: compute the payable balance as of a cutoff, create a payout record with an idempotency key (payout-<seller>-<week>), call the provider’s payout API, and move the amount from seller payable to provider clearing; failures stay retryable.
  • Holds and disputes: keep a reserve (a held account) for recent sales to cover chargebacks.
  • Compliance: seller onboarding and identity checks (KYC) through the provider’s connected-accounts product, tax reporting per seller, and statements generated from the ledger.
Exercisemedium

Handle a webhook safely

Write the steps of a webhook handler for payment.succeeded, so that a fake request, a duplicate event or a late event can’t cause harm.

›

Think about who could send the request, how many times it can arrive, and in which order.

SolutionTry it yourself first
  1. Verify the signature with the provider’s signing secret, and reject requests with an old timestamp (replays).
  2. Store the event id with a unique constraint; if it already exists, return 200 and stop (a duplicate).
  3. Load the payment by the provider’s payment id and apply the transition → SUCCEEDED through the state machine. If the payment is already SUCCEEDED or in a later state (refunded), do nothing.
  4. In the same transaction, write the ledger entries and an outbox event PaymentSucceeded for the order service.
  5. Return 200 quickly; heavy work happens asynchronously, so the provider doesn’t time out and resend.
  • Webhooks: verify signature and timestamp, store raw, dedupe by event id, apply via the same monotonic transition function; ack fast.
  • Reconciler for stale PROCESSING (query by key); daily settlement reconciliation with a discrepancy queue; totals must match bank payouts.
  • Refunds and chargebacks are their own state machines and ledger transactions; chargebacks have evidence deadlines.
  • Clients poll a status endpoint with backoff after 3-D Secure, then rely on push or email; show “processing” honestly.
  • Marketplaces: seller payable accounts, commission at capture, weekly idempotent payouts, reserves for disputes, KYC via the provider.

Check this part

  1. Why must a webhook handler verify the signature?

  2. What does daily reconciliation compare?

  3. A stale "requires_action" arrives after the payment is SUCCEEDED. What happens?

Webhooks are verified, deduplicated by event id and applied through the same state machine; they can arrive before or instead of the synchronous answer. A reconciler resolves stuck PROCESSING payments by querying the provider. Daily reconciliation matches the ledger against provider settlement reports and flags every difference. Refunds and chargebacks are new ledger transactions. Mobile clients poll or listen for the final state after 3-D Secure.

Key takeaways

  • Payments are about correctness, not scale: never double charge, never lose track of money.
  • Save every state change, and treat a timeout as “unknown”, not “failed”.
  • Idempotency keys make retries safe, from the app to the provider.
  • A double-entry ledger records every movement as entries that sum to zero.
  • Webhooks need signatures, deduplication and a state machine; reconcile with the provider daily.
  • Persisted, monotonic state machines with one transition function for all sources.
  • Idempotency at every hop; reconcilers for unknown outcomes.
  • Append-only, double-entry ledger with continuously checked invariants.
  • Reconciliation and PCI scope minimization are part of the design, not afterthoughts.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.