All posts
System Design Mastermind · Part 33
  • System design
  • Interview prep
  • Payments
  • Idempotency
  • Platform

Payment system design (Stripe): idempotency, unknown outcomes, the ledger and reconciliation

How to design a payments platform like Stripe in real interview order: calls held open on slow banks, the platform's own fee account and the money in 0.01% as the numbers that matter, an API with amounts in cents and an Idempotency-Key on every POST, an explainer that turns a $100 payment into fees and double-entry journal entries, a card vault, payments API, risk engine, gateway, outbox, event log, ledger, webhooks, reconciliation and payouts built in passes, one $60 payment walked from checkout to the merchant's bank, a lab on timeouts and retries that charge twice or take money without an order, a lab on hot ledger accounts with sub-accounts and batching, a reconciliation lab that finds two real breaks among the noise, the lifecycle of a payment, and what happens when each part fails.

27 Oct 2026 · 33 min read · interactive

Share

The 1-minute answer

The customer's card goes from the browser straight to a card vault, which returns a token; the merchant only ever sees the token. The merchant's server creates a payment and confirms it with an Idempotency-Key. The payments API checks the key (replay the saved answer if it's seen it), writes an attempt row before calling anyone outside, asks a risk engine for a score, and sends the authorization through a gateway to the acquirer, card network and issuing bank, with short timeouts and a circuit breaker per acquirer. The result, an outbox event and the saved response commit in one transaction; a relay puts the event on a log, where an append-only double-entry ledger posts it and a webhook sender tells the merchant, signed and retried for days. A timeout is a third outcome: the attempt goes unknown, the payment shows "processing", and a resolver asks the bank with the same reference, never a new one. The next day a reconciliation job matches the ledger against the acquirers' settlement files and bank statements, and payouts move merchants' balances to their banks. The hard parts: never charging twice or losing a charge when calls time out, a ledger that always balances and stays fast on hot accounts, and reconciling with the outside world.

How this page follows the interview

Each phase is a section below, in the order you'd present it. Click a phase for what to say, what to write, and the trap.

✅ Seen: said publicly (cited)🔶 Inferred❓ Unknown: state it as an assumption🧭 Interview choice

Idempotency keys, exactly-once and sagas in general are in Foundations F11; queues and the outbox idea in F10; the log itself in Part 27 (Kafka). This page puts them together for the one problem where every mistake is someone's money.

Requirements and numbers

Agree what's promised, then size it. For payments, the rate is modest; what decides the design is how long each call waits on a bank, which ledger account every payment touches, and what one mistake in ten thousand costs. Change any input: each number comes with the decision it forces.

Functional

  • Merchants charge cards via an API
  • Authorize now, capture later
  • Refunds, full or partial
  • Webhooks for every state change
  • Balances and payouts to merchants

Non-functional

  • Never charge twice, never lose a charge
  • Every cent explainable, for years
  • Confirm p99 in about 2 s
  • 99.99%+ available; refuse over guess
  • Card data in a small PCI zone

Out of scope (say it)

Fraud models' internals, card network internals, subscriptions and invoicing, tax, currency exchange in depth, onboarding and KYC.

Capacity calculator

Every input is an assumption 🔶: say it out loud. Anchors: businesses on Stripe processed $1.9 trillion in 2025 ✅ Stripe Feb 2026, and over Black Friday–Cyber Monday 2025, 578 million transactions with a peak above 152,000 a minute (~2,500/s) ✅ Stripe Dec 2025. At ~$69 a payment that's roughly 75 million payments on an average day, so 100 M a day with a 3× peak is a round, slightly generous interview scale. 🔶

Three rules for this estimate
  1. A day is 86,400 seconds; size the API for the peak, storage for the day.
  2. Little's law: calls open at once = calls per second × seconds each takes. Slow banks need big pools.
  3. Price the error: money per day × 0.01% is what one mistake in ten thousand costs.
They'll push on thisAnswer out loud, then open.

Core entities and the API

Five merchant calls and one webhook. What they listen for: amounts in cents, an Idempotency-Key on every POST, authorize and capture as separate steps, and a timeout that comes back as "processing", not as a decline.

EntityKey fieldsNote
Request
Response

Where a payment's money goes, in double-entry

A $100 card payment isn't $100 to the merchant, and it isn't one number in a database. Change the inputs and watch the fee and the journal entries: in every entry, debits equal credits.

The journal entries

Account names are illustrative; the fee is Stripe's US list price for online cards (2.9% + 30¢, +1.5% international, +1% conversion) ✅ Stripe pricing. Interchange and network fees are inside that price; how it splits isn't public per payment. ❓

They'll push on thisAnswer out loud, then open.

High-level design

Build it in passes and say why each box exists. Click any box to see what it does, what it owns, what's inside it and what you'd watch.

They'll push on thisAnswer out loud, then open.

Walk one payment, box by box

A customer buys a $60 pair of shoes. Follow the payment from checkout to the bank's approval, the ledger and the webhook, then the capture when the order ships, the next day's settlement file, and the payout to the merchant's bank. Each step lights up the path and shows what goes over the wire, what's stored and how long it takes.

On the wire

Arrows show who calls whom, and the numbers give the order. Consumers pull from the event log (it isn't pushed to them), and reconciliation reads the files and statements. Replies, like the bank's approval, go back along the same line.

What the payments API does on confirm

This is the one call that moves money. Two short transactions with one outside call between them:

    Data and storage choices

    Two kinds of data with different rules: payment state changes (with transactions and keys), and money movements, which are only ever appended. The ledger is the source of truth for balances and payouts.

    DataPickConsideredWhy not those

    The one handler to know

    # Confirm a payment. Illustrative.
    def confirm(merchant, key, payment_id, pm):
      with db.tx():
        k = keys.get_for_update(merchant, key)
        if k and k.done:  return k.response         # replay
        if k and k.params != hash(payment_id, pm): raise 400
        if k:  raise 409                            # still running
        keys.insert(merchant, key, hash(…), "started")
        att = attempts.insert(payment_id, "authorizing",
                              ref=new_ref())
      res = gateway.authorize(att.ref, timeout=5)   # outside call
      with db.tx():
        attempts.update(att, res.state, res.charge)  # or "unknown"
        payments.update_status(payment_id, res)
        outbox.insert(event_for(payment_id, res))
        keys.finish(merchant, key, response(res))
      return response(res)

    Illustrative. The order is the point: key and attempt committed first, the outside call with no transaction open, then result, outbox and saved response in one commit. 🧭

    What the big platforms do

    1. Stripe's Ledger: an immutable log of events, double-entry, 5 billion events a day; money that should have moved on sits in a clearing account and is detected. ✅ Stripe 2024
    2. Stripe's databases: DocDB, built on MongoDB Community: 5 million+ queries a second, 2,000+ shards, 99.999% uptime. ✅ Stripe 2024
    3. Uber's LedgerStore: append-only, verifiably immutable, over a trillion entries (a few PB). ✅ Uber
    4. Airbnb: payment workflows as a graph of retryable, idempotent steps; five 9s of payment consistency. ✅ Airbnb

    More storage questions

    They'll push on thisAnswer out loud, then open.

    Deep dive: never charge twice, never lose a charge

    Two calls can time out: the merchant's call to you, and your call to the bank. A timeout means "I don't know", and each wrong guess has a price: a retry without a key charges twice, "failed" takes money without an order, a new reference charges again. Pick a preset, then change one setting at a time.

    The rules this lab teaches

    1. Same key, same parameters, same answer: Stripe saves the first response (even a 500) and replays it; a different payload with the key is an error. ✅ Stripe docs
    2. Without a key, a retry is a new payment: double charges = retried calls × approval². 🧭
    3. A timeout is unknown: "treat the outcome of a request that returns 500 as indeterminate"; check status before retrying. ✅ Stripe docs · Adyen docs
    4. The safe default wins: an authorization that's never captured is released when it expires. ✅ Stripe docs

    Numbers to quote

    Stripe keeps idempotency keys at least 24 hours; after that window, "don't retry with either the old key or a new one", reconcile instead. ✅ Stripe docs

    Shopify starts from a 1 s connect and 5 s read timeout instead of library defaults (60 s in Ruby, none in Go or Node). ✅ Shopify 2022

    Online card authorizations are valid about 7 days (Visa merchant-initiated: 4 days 18 hours). ✅ Stripe docs The rates in the lab are teaching values. ❓

    They'll push on thisAnswer out loud, then open.

    Deep dive: the ledger and hot accounts

    Every entry must balance, and every balance is a sum of entries. The catch: your own accounts (fees, money owed by card networks) get a line from almost every payment, and one row under a lock takes only 1 ÷ lock time writes a second. Pick a preset, then change the inputs.

    Capacity = sub-accounts × batch ÷ (lock time + batch × per-posting cost). Waiting for the lock uses an M/M/1 queue in units of writes, a conservative assumption; waiting for a batch to fill is (batch − 1) ÷ 2 arrivals. 🔶

    What to build

    1. Append entries; don't update a balance per payment unless the account must never go negative. ✅ Stripe 2024
    2. Split hot accounts into sub-accounts and sum on read; never for a balance with a "can't go below zero" rule. 🧭
    3. Batch postings so commit and replication are paid once per batch, and let batches shrink when it's quiet. ✅ TigerBeetle docs
    4. Unique on event id so a replayed event can't post twice. 🧭

    Numbers to quote

    Stripe's Ledger processes 5 billion events a day and explains over 99.9999% of money movement; 99.99% of dollar volume is fully ingested and verified within four days. ✅ Stripe 2024

    TigerBeetle: "a small number of hot accounts are often involved in a large proportion of the transactions"; it takes up to 8,190 transfers per request. ✅ TigerBeetle docs

    Lock time = commit + synchronous replication. Within a zone it's milliseconds; across regions, tens of ms. 🔶

    They'll push on thisAnswer out loud, then open.

    Deep dive: reconciling with the outside world

    Your ledger says what you think happened; the acquirer's settlement file says what the bank did. Below are six payments from one day and two days of files. Two real problems are hidden in them: find them without drowning in false breaks. Pick a preset, then change one rule at a time.

    Our ledgerTheir fileResult

    Made-up rows; fees are 2.9% + 30¢ rounded to the cent. The processor's day closes before midnight UTC, so a payment at 23:58 lands in the next file. 🧭

    The rules this lab teaches

    1. Match on an id you stored, the processor's charge id from the moment the call returned; amounts collide. 🧭
    2. Look across the cut-off before calling something missing. 🧭
    3. Compare like with like: files report gross, fee and net; so should your ledger. 🧭
    4. Automate known shapes, queue the rest: Shopify logs mismatches as typed anomalies, fixes some automatically, and developers look at the rest. ✅ Shopify 2022

    Numbers to quote

    Stripe scores its data on clearing, timeliness and completeness; "a single missing, late, or incorrect transaction immediately creates a detectable accuracy issue." ✅ Stripe 2024

    Webhooks are retried for up to three days; events can be listed for 30 days, so a merchant can recover missed ones. ✅ Stripe docs

    India: for failed UPI transactions where the account was debited, RBI requires auto-reversal by T+1 or ₹100 a day in compensation, which is why reconciliation runs daily. ✅ RBI 2019

    They'll push on thisAnswer out loud, then open.

    A payment's lifecycle

    A payment is created, authorized (maybe after 3D Secure), captured, settled and paid out, or it's declined, times out into unknown, expires, is refunded or disputed. Click events to move it; ones that can't happen from the current state are disabled. Each event shows what fires across the system.

    NormalSomething went wrongGreyed out: not possible from the current state.

    States are named for teaching and map roughly onto Stripe's statuses (requires_payment_method, requires_action, processing, requires_capture, succeeded, canceled); settled and paid out live in the ledger, not on the payment. ✅ Stripe docs

    Edge cases interviewers love

    They'll push on thisAnswer out loud, then open.

    Failure, monitoring and recovery

    Most failures here aren't outages; they're uncertainty about money. The design answers each one by refusing rather than guessing, recording what it doesn't know, and resolving it later against the bank. Click a box to take it down: red is the failed part, amber is its blast radius. Each answer covers impact, degraded mode, the alert, automatic and manual recovery, and how you'd trace it.

    Tracing it back: a normal confirm vs a bank timeout

    Time from confirm to the merchant knowing the outcome. In the second trace the bank never replies; the attempt goes unknown, and a status inquiry 30 seconds later finds it was approved.

    How one failure becomes three

    What you'd alert on (SLOs)

    SignalTargetAlert

    Incident playbook

      The toolkit

      Name the technique, then say where it goes in this design.

      They'll push on thisAnswer out loud, then open.

      Making it fast, and who owns what

      The merchant waits for milliseconds of our work and a second of the bank's; the truth arrives in seconds (webhooks), minutes (unknowns) and a day (settlement), on purpose. Bars are sizing estimates, not measured figures.

      TeamOwnsPaged when…

      Senior follow-ups beyond the happy path

      Interviewers pick from these themes once the design is on the board. Have one concrete answer per theme, tied to this design.

      Practice ladder

      Real interviews go level by level. Answer out loud before opening each one. Levels 6–7 are where Senior becomes Staff.

      Sources

      Checked October 2026. Stripe's figures are as published: $1.9 trillion of volume in 2025 (annual letter, 24 Feb 2026), 578 million transactions and a peak above 152,000 a minute over Black Friday–Cyber Monday 2025 (2 Dec 2025), Ledger's 5 billion events a day (16 Feb 2024), DocDB's 5 million queries a second on 2,000+ shards (6 Jun 2024). Mechanisms come from Stripe's docs (idempotent requests, advanced error handling, PaymentIntent lifecycle, authorization windows, webhook retries, US list pricing), Stripe's 2017 idempotency post, Shopify's 2022 resilient-payments post, Adyen's timeout docs, TigerBeetle's performance docs, Uber's LedgerStore migration post and Airbnb's payment orchestration post, and RBI's 2019 failed-transaction circular. Average volume per day is inferred from those figures. The labs use rounded teaching values for timeout, retry and approval rates, lock times and the reconciliation rows, and say so. Techinterview.org is a third-party prep site, used only to cross-check what interviewers expect. Nothing here comes from any employer's internal systems.

      System Design Mastermind · Platform & Infra

      Series home

      All of Platform & Infra

      5 published · 7 comingWhat Senior platform loops lean on.

      19

      Distributed job scheduler system design: on time, at least once, never lost

      Jobs in a sharded store with a precomputed next_run_at → one scheduler per shard (lease + fencing token) claims due jobs every second: insert run (unique job_id + time) and advance next_run_at in one transaction → durable queue with deliver-at, enqueued a little early → workers lease runs, heartbeat, call the target with the run id as idempotency key → backoff, then a DLQ. At-least-once, made safe by idempotency.

      32 min · interactive Preview
      24

      Metrics and logging system design (Datadog-style): series, roll-ups and alerts you can trust

      Agents add up metrics for 10 s and batch them with logs → intake checks key and quotas, appends to a durable log, then 202 → writers map tags to series ids in an inverted index and store compressed points with roll-ups → logs: index a slice, archive all → monitors evaluate a window that ends in the past, and the whole stack is watched from outside.

      32 min · interactive Preview
      27

      Kafka system design: a distributed log that never loses an acknowledged message

      Topics split into partitions; the producer hashes the key, batches and sends to the partition leader → the leader appends to the page cache, followers in other zones pull, acks=all waits for every in-sync copy (RF 3, min ISR 2) → consumer groups pull from offsets and commit them → KRaft controllers move leaders; tiered storage keeps history.

      33 min · interactive Preview
      30

      Ad click aggregator system design: exactly-once counts, late clicks and hot ads

      Signed click URL → click service appends to Kafka and 302s → Flink dedupes by click id, counts per ad in 1-minute event-time windows, upserts (ad, minute) rows into an OLAP store → a per-click counter paces budgets → a nightly recount from raw clicks is what billing reads.

      32 min · interactive Preview
      33

      Payment system design (Stripe): idempotency, unknown outcomes, the ledger and reconciliation

      Card → vault → token; confirm with an Idempotency-Key → attempt row written before the bank call → gateway with timeouts and breakers → result + outbox in one commit → event log → append-only double-entry ledger and signed webhooks → a timeout is 'unknown', resolved by status check and the next day's settlement file → payouts from balances.

      You're reading this Preview
      ··

      Web crawler

      Coming next
      ··

      File sync (Dropbox)

      Coming next

      More posts