Skip to content

    System Design

    Case Study: Payment System

    Design a payment system around an outside provider: payment states, idempotent requests, a webhook inbox, ledger posting, refunds and reconciliation.

    By Published 22 min read

    Share

    What you'll learn: By the end of this lesson you will be able to (1) design the payment service that sits between a shop and an outside payment provider, (2) keep a payment correct when requests time out and events arrive twice or out of order, (3) connect the payment state machine to an append-only ledger without letting one corrupt the other, (4) handle refunds, disputes and failures as normal events, and (5) say what reconciliation checks and what to do when it finds a difference.

    A cashier hands you a printed receipt for every sale and keeps a carbon copy in a book. At closing time the cashier counts the till and compares it with the book. If they differ, nobody says "the till is wrong" or "the book is wrong". They find the sale that explains the difference. The receipt number makes sure one sale is never written twice, and the carbon copy is never erased, only added to.

    A payment system is that cashier at scale, with one twist: the till belongs to someone else. A payment provider decides whether a card payment succeeds. Your system asks, waits, is told the answer more than once and sometimes not at all, and must still end up with exactly one charge, one record and one ledger entry set for each purchase.

    This lesson is the system-level case study. It builds on payments and double-entry ledgers for the ledger and provider lifecycle, and on idempotency keys and safe retries for the request mechanism; it assumes both and does not repeat them. The booking half of the same problem is the planned Ticket Booking and Overselling case study, which applies the seat claim in front of a payment.

    IMPORTANT

    This lesson is a design lesson, not legal, tax, compliance or financial advice. Rules for holding customer money, record keeping, card-data handling, reporting, refunds and chargebacks differ by country and by provider contract, and none of them are described here. Take those questions to your compliance, legal and finance owners.

    This is an educational reference design, not the verified internal architecture of any company. It names no payments company as a model. Stripe's documentation is cited only as one concrete example of how a provider behaves, and nothing is claimed about how any provider works inside. Figures are illustrative assumptions. Verified on 2026-12-02 against the Stripe documentation (idempotent requests, webhooks, PaymentIntents lifecycle, refunds, disputes, integration security) and the PostgreSQL 18 documentation. The SQL on this page was checked to parse and behave as described on a single connection in PGlite, a WebAssembly build of PostgreSQL; there is no lab and no output is shown.

    The core idea

    A payment system is a state machine that talks to an unreliable outside provider, joined by durable records to an append-only ledger that only ever receives balanced, uniquely identified facts. Every boundary (request out, event in, ledger post, refund) is made safe to repeat, and a daily reconciliation compares the whole thing with the provider's own records.

    Three illustrations run through the lesson:

    • Minimal example: one payment from request to ledger, with a timeout in the middle.
    • Realistic example: the ShopStream grocery marketplace taking 500,000 orders a day, paying sellers later and refunding some orders.
    • Failure example: the provider's event for a captured payment arrives twice, then a refund event arrives before it.

    Requirements and scope

    Functional: take a payment for an order, authorise now and capture later (a grocery order's final price can change when items are substituted), refund fully or partly, receive the provider's asynchronous events, record every money movement, pay sellers, and report differences against the provider.

    Out of scope: how a card network or bank works, fraud scoring models, tax, identity checks, becoming a regulated payment institution, and card storage. The reference design never touches card numbers.

    Non-functional (assumptions):

    • A buyer is never charged twice for one order, and a paid order is never lost.
    • Every cent can be explained from an immutable record.
    • A provider outage degrades checkout but never corrupts records.
    • Operations are safe to repeat: retries, duplicate events and replays are normal inputs.

    Back-of-envelope estimate

    The order volume is the shared ShopStream figure, 500,000 orders per day, with a peak of 58 checkouts per second. The rest are illustrative assumptions.

    Quantity Assumption Result
    Payments 500,000 per day About 5.8 per second on average, 58 at peak
    Provider events About 3 per payment (created, succeeded, others) 1,500,000 per day, about 17 per second, about 170 at a 10x peak
    Ledger entries 3 per captured payment, 5 percent refunded at 3 entries each, 5,000 daily seller payouts at 2 each 1,500,000 + 75,000 + 10,000 = 1,585,000 per day, about 18 per second
    Ledger growth 1,585,000 per day About 580 million rows per year; at 100 bytes a row, about 58 GB before indexes
    Idempotency store One row per mutating request Kept at least as long as the longest client retry window

    Nothing here is large for one well-run relational database. The difficulty is not volume but correctness under repeats: the same events, requests and webhooks arriving several times in any order. Event traffic is spiky (a provider delivering a backlog after your outage), so the design puts a queue between receiving and processing.

    API design

    POST /v1/payments                       header Idempotency-Key
         {orderId, amountMinor, currency, paymentMethodToken, captureMode: "auto" | "manual"}
         201 {paymentId, status}             status may be requires_action, processing, authorized or captured
    GET  /v1/payments/{paymentId}           the current state, the source of truth for the UI
    POST /v1/payments/{paymentId}/capture   header Idempotency-Key; {amountMinor}
    POST /v1/payments/{paymentId}/cancel    header Idempotency-Key
    POST /v1/payments/{paymentId}/refunds   header Idempotency-Key; {amountMinor, reason}
    POST /webhooks/provider                 called by the provider, not by clients

    Four design points. Money is an integer in minor units with a currency code, never a float. A response of 201 processing is a legitimate success: the final state comes later. The client polls GET or listens for your own event, and never treats the first HTTP response as the final answer. Every mutating call takes an Idempotency-Key. And the payment token represents a payment method the provider already holds; the card number never reaches your servers.

    Data model

    CREATE TABLE payment (
      payment_id     uuid PRIMARY KEY,
      order_id       uuid   NOT NULL,
      amount_minor   bigint NOT NULL CHECK (amount_minor > 0),
      currency       char(3) NOT NULL,
      status         text   NOT NULL CHECK (status IN
                       ('created', 'requires_action', 'processing', 'authorized', 'captured', 'failed', 'canceled')),
      provider_ref   text,
      captured_minor bigint NOT NULL DEFAULT 0,
      refunded_minor bigint NOT NULL DEFAULT 0,
      CHECK (captured_minor <= amount_minor),
      CHECK (refunded_minor <= captured_minor)
    );
    
    -- one live payment per order: failed and canceled ones do not count
    CREATE UNIQUE INDEX one_live_payment_per_order ON payment (order_id)
      WHERE status NOT IN ('failed', 'canceled');
    
    -- inbox: every provider event, once
    CREATE TABLE provider_event (
      event_id     text PRIMARY KEY,
      event_type   text NOT NULL,
      payload      jsonb NOT NULL,
      received_at  timestamptz NOT NULL DEFAULT now(),
      processed_at timestamptz
    );
    
    CREATE TABLE ledger_transaction (
      txn_id    bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
      source_id text NOT NULL UNIQUE,        -- the provider event id or our own operation id
      posted_at timestamptz NOT NULL DEFAULT now()
    );
    
    CREATE TABLE ledger_entry (
      entry_id     bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
      txn_id       bigint NOT NULL REFERENCES ledger_transaction,
      account      text   NOT NULL,
      amount_minor bigint NOT NULL CHECK (amount_minor <> 0),  -- debits positive, credits negative
      currency     char(3) NOT NULL
    );

    PostgreSQL's documentation says a unique constraint builds a unique index and that a check constraint raises an error when a row would violate it. Here they do the quiet work: the unique source_id is what makes a ledger post repeatable, and the CHECK constraints on captured_minor and refunded_minor make an over-refund an error instead of a silent overspend. The partial unique index is the same technique used for seats in the booking lesson: it enforces "one live payment per order" while allowing any number of failed attempts.

    erDiagram accTitle: Payment system data model accDescr: An order has payments. A payment has refunds and provider events. A provider event can produce one ledger transaction, identified by its source id. A ledger transaction has several balanced ledger entries against named accounts. ORDER ||--o{ PAYMENT : paid_by PAYMENT ||--o{ REFUND : refunded_by PAYMENT ||--o{ PROVIDER_EVENT : reported_by PROVIDER_EVENT ||--o| LEDGER_TRANSACTION : posts LEDGER_TRANSACTION ||--|{ LEDGER_ENTRY : has PAYMENT { uuid payment_id PK string status bigint captured_minor bigint refunded_minor } PROVIDER_EVENT { string event_id PK string event_type } LEDGER_TRANSACTION { bigint txn_id PK string source_id UK } LEDGER_ENTRY { bigint txn_id FK string account bigint amount_minor }

    Figure 1. Data model. How to read this: the payment row is the working state and may be updated; the ledger tables only ever receive new rows. source_id links a ledger transaction to the single event or operation that caused it.

    High-level design

    Payment system reference designCheckout service to Payment service; Payment service to Idempotency store; Payment service to PostgreSQL (state); Payment service to Payment provider (request); Payment provider to Webhook endpoint (events); Webhook endpoint to Event queue; Event queue to Ledger worker; Ledger worker to Ledger (post); Ledger worker to PostgreSQL; Reconciliation job to LedgerCheckout serviceCheckoutservicePayment service: state machinePaymentservicestate machineIdempotency storeIdempotencystorePostgreSQL: payments, inboxPostgreSQLpayments, inboxWebhook endpointWebhookendpointEvent queueEvent queueLedger workerLedger workerLedger: append onlyLedgerappend onlyReconciliation jobReconciliationjobPayment providerPaymentproviderstaterequesteventspost

    Figure 2. Reference design. How to read this: requests go out through the payment service; answers come back as events through the webhook endpoint and queue. The ledger worker is the only writer of the ledger, and reconciliation reads it against the provider's reports.

    sequenceDiagram accTitle: A payment from request to ledger with a timeout accDescr: The checkout service asks the payment service to pay with an idempotency key. The payment service stores the attempt, calls the provider with a key derived from the payment id and times out. It marks the attempt unknown and returns processing. The provider's event arrives at the webhook endpoint, is verified, written to the inbox and queued. The ledger worker posts balanced entries keyed by the event id and updates the payment to captured. participant C as Checkout participant P as Payment service participant V as Provider participant W as Webhook endpoint participant L as Ledger worker C->>P: POST payments (key k1) P->>P: insert payment, status created P->>V: create and confirm (key pay-123-1) V--xP: timeout, outcome unknown P-->>C: 201 processing V->>W: event e1 captured W->>W: verify signature, insert inbox row W-->>V: 200 quickly W->>L: enqueue e1 L->>L: post ledger entries (source e1), set captured

    Figure 3. A payment with a lost reply, the minimal example. How to read this: the timeout does not mean failure. The payment service reports processing, and the outcome arrives later as an event. Every hop that can repeat has a key: k1 from the client, pay-123-1 to the provider, e1 into the inbox and the ledger.

    The payment state machine

    The payment service owns a state machine that mirrors the provider's, because the provider decides the outcome. Stripe's PaymentIntent lifecycle is one concrete example: it starts at requires_payment_method, may pass through requires_confirmation and requires_action (for example 3D Secure), processing and requires_capture when authorisation and capture are separate, and ends succeeded or canceled. A failed attempt returns it to requires_payment_method so it can be retried. The documentation says succeeded means the flow is complete, the funds are in your account, and you can fulfil the order.

    stateDiagram-v2 accTitle: Internal payment states accDescr: A payment starts created. It may require customer action, then processing. Processing leads to authorized when capture is separate, or captured. An authorized payment is captured or canceled. A failure returns to created for a retry or ends failed. Captured payments can be partly or fully refunded without changing the captured state, which is tracked by the refunded amount. [*] --> Created Created --> RequiresAction : customer step needed RequiresAction --> Processing : step done Created --> Processing : submitted Processing --> Authorized : funds held Processing --> Captured : paid Processing --> Failed : declined or error Authorized --> Captured : capture Authorized --> Canceled : cancel Captured --> [*] Failed --> [*] Canceled --> [*]

    Figure 4. Payment states. How to read this: refunds do not add a state. They raise refunded_minor on a captured payment, so a partial refund and a full one are the same mechanism. Terminal states never go back.

    Transitions are driven by provider events and never by assumption. A state is only advanced by an update that names the state it expects (UPDATE payment SET status = 'captured' ... WHERE payment_id = :id AND status IN ('processing', 'authorized')), so a late duplicate event that would move a captured payment backwards matches no rows and is ignored.

    Deep dive 1: the request that may or may not have happened

    The payment service calls the provider and the call times out. Did the charge happen? Unknown. Idempotency keys are the mechanism, and three details decide whether it works.

    The key belongs to the operation, not to the attempt. Derive the provider-facing key from the payment id and the operation (pay-123-1, capture-123, refund-123-2), so a retry from a different process or after a restart reuses it. Stripe's documentation says that for API v1 it saves the status code and body of the first request made with a key, returns the saved response on retries including 500 errors, errors if a retry's parameters differ, and may prune keys after at least 24 hours. Keys are suggested to be random with enough entropy, up to 255 characters, and not built from sensitive data. A random key per attempt would defeat the purpose.

    Record the attempt before you send it. Insert the payment row (created) and the intended operation first, commit, then call. If the process dies between, the row shows an attempt in doubt and a recovery job can retry with the same key. If you call first and write afterwards, a crash loses the only evidence the charge was ever requested.

    A timeout is a state, not an error. Mark the attempt unknown, tell the caller processing, and resolve it by retrying with the same key, which returns the first outcome, or by waiting for the event. Stripe's documentation also says a request that fails validation or conflicts with one still executing is not saved, so it can be retried. The same shape appears in your own Idempotency-Key handling of inbound calls, which the lesson on idempotency keys builds: a stored response for a finished operation, 409 for one still in flight, 422 for a reused key with different content.

    Retries are bounded. Use exponential backoff with jitter and a deadline, and stop retrying when the answer is final (timeouts, retries, backoff and jitter). Retrying a provider that is down for everyone amplifies the outage (load shedding and retry storms).

    Deep dive 2: events in, exactly once in effect

    The provider reports outcomes by webhook. Stripe's documentation lists what to expect, and each item drives a design rule.

    Provider behaviour (from the Stripe documentation) Design rule
    Verify each event with the Stripe-Signature header; the raw body is required, and any change to it breaks verification Verify before parsing, on the raw bytes; never trust unsigned events
    The signature carries a timestamp, and libraries default to a 5-minute tolerance, to resist replay Reject old signed events; keep clocks synchronised
    Return a 2xx quickly, before complex logic Write to the inbox, enqueue, answer; do the work after
    An endpoint may receive the same event more than once Deduplicate by event id
    Delivery order is not guaranteed; do not use created to order events Never assume order; fetch the current object when in doubt
    Failed deliveries are retried with exponential backoff for up to three days in live mode; events can be resent manually Be able to replay events safely, and accept a backlog after an outage
    Process events with an asynchronous queue to absorb spikes Queue between receiving and processing

    The receiving transaction is deliberately tiny:

    INSERT INTO provider_event (event_id, event_type, payload)
    VALUES (:event_id, :event_type, :payload)
    ON CONFLICT (event_id) DO NOTHING;
    -- 0 rows inserted: a duplicate. Answer 200 and stop.

    PostgreSQL's documentation says ON CONFLICT DO NOTHING avoids inserting the row, so a repeated delivery changes nothing. The worker then processes the inbox row: it reads the payment's current state, applies the transition if it is allowed from where the payment is, and posts the ledger entries in the same database transaction, using the transactional outbox to tell the order service. Events that arrive early are handled by asking the provider for the current object rather than trusting the order of arrival, and a poison event goes to a dead-letter queue with an alert (dead-letter queues and retries).

    The failure example. The event for a captured payment (e1) arrives twice, and a refund event (e2) arrives before either. The duplicate of e1 hits the inbox conflict and is dropped. e2 finds a payment that is not yet captured: the refund guard (below) refuses to apply a refund to something that was never captured, the worker re-queues it with a delay and fetches the payment's real state, and when e1 has been processed e2 succeeds. No state moved backwards and no ledger entries were posted twice.

    Deep dive 3: the ledger at system level

    The ledger lesson gives the full mechanics; here are the system decisions.

    One post, one statement. The ledger worker posts a transaction and its entries so that a repeat creates nothing:

    WITH t AS (
      INSERT INTO ledger_transaction (source_id)
      VALUES (:provider_event_id)
      ON CONFLICT (source_id) DO NOTHING
      RETURNING txn_id
    )
    INSERT INTO ledger_entry (txn_id, account, amount_minor, currency)
    SELECT t.txn_id, e.account, e.amount_minor, 'GBP'
    FROM t, (VALUES ('provider_clearing', 4500),
                    ('seller_payable', -4000),
                    ('platform_fees', -500)) AS e(account, amount_minor);

    If source_id already exists, the first step returns no row and the second inserts nothing. The three signed amounts sum to zero (debits positive, credits negative, a convention chosen for this page), which is the invariant a balanced post must keep.

    Append only. A wrong entry is corrected by a new reversing transaction, never an edit. History is the audit trail and the reconciliation input.

    Hot accounts. Every payment touches the platform fees and provider clearing accounts. If balances are stored as a number updated in place, those few rows become a lock queue. Store entries only, compute balances by summing them, and keep periodic snapshots for fast reads. At the assumed 18 entries per second this is not yet a problem; at much higher rates, a per-account sub-ledger keyed by shard is the usual relief, at the cost of summing across shards.

    Separate databases, or at least separate schemas. The payment state is mutable and the ledger is not. Separating them (or giving the ledger tighter permissions) means a bug in the payment service cannot rewrite history. Whether this is worth a second database at your scale is a cost decision.

    Deep dive 4: authorise, capture and the order saga

    Checkout touches inventory, payment and fulfilment, which are separate services. A single database transaction cannot span them, so the flow is a saga: each step is a local transaction, and a failed later step is undone by a compensating step (distributed transactions). For payments, compensation is never deletion. Cancel an authorisation before capture; refund after.

    For a grocery order the price is not final until the items are picked, so the design authorises at checkout and captures at fulfilment. The Stripe documentation describes the hold-then-capture shape: when authorisation and capture are separate, a PaymentIntent waits in requires_capture, cancelling a PaymentIntent releases any held funds and cannot be undone, and a PaymentIntent in requires_capture is cancelled rather than refunded. Two design consequences follow. The order service must capture, or cancel, every authorisation: an authorisation left open keeps a customer's funds on hold until it is captured or cancelled, so a daily job lists authorisations older than your policy allows. And the capture amount may differ from the authorised amount, which the payment row records in captured_minor.

    flowchart TD accTitle: Choosing the compensation for a failed order step accDescr: If the payment is only authorised, cancel the authorisation. If it is captured, issue a refund and post reversing ledger entries. If the outcome is unknown, resolve it first by retrying with the same key or waiting for the event, never by creating a second payment. f["A later order step failed"] --> s{"Payment state?"} s -- "authorized" --> c1["Cancel the authorisation"] s -- "captured" --> c2["Refund, with reversing ledger entries"] s -- "processing or unknown" --> c3["Resolve first: same key or wait for the event"] c1 --> done["Order cancelled, no money moved"] c2 --> done2["Order cancelled, refund pending"] c3 --> s

    Figure 5. Compensation follows the state. How to read this: the unknown branch loops back. You never start a second payment while the first one's outcome is unresolved, because that is how a buyer gets charged twice.

    Deep dive 5: refunds, disputes and things that go wrong later

    Money moves after the sale, and the system treats those moves as ordinary events.

    Refunds. Stripe's documentation says you can issue more than one refund against a charge but never more than the original amount, that refunds can only go back to the original payment method, that a refund can fail (for example for a closed account, in which case the bank returns the money to the provider and you must arrange another way to pay the customer), that a refund appears to the customer after roughly 5 to 10 business days depending on the bank, and that an insufficient balance can leave a card refund pending for up to 45 days. The design follows from it. A refund is its own operation with its own idempotency key, a status, and its own ledger transaction when it succeeds, and its failure is an event the system handles. The "never more than the original" rule is enforced in the data, not only in the code:

    UPDATE payment
    SET refunded_minor = refunded_minor + :amount
    WHERE payment_id = :payment_id
      AND refunded_minor + :amount <= captured_minor;
    -- 0 rows: refuse the refund

    Two concurrent refund requests cannot both fit, and the CHECK (refunded_minor <= captured_minor) backs the condition up.

    Disputes. A dispute (chargeback) is initiated by the cardholder with their issuer. Stripe's documentation says the issuer creates a formal dispute on the card network, which immediately reverses the payment and pulls the amount plus one or more network dispute fees, after which the provider debits your balance. For the design: a dispute is an inbound event you did not ask for, it creates ledger entries (the amount back out, plus fees), it needs a workflow to gather and submit evidence within the provider's deadlines, and an order whose payment is disputed should not also be refunded. The refund page lists a failure reason for a refund that was still pending when its charge was disputed, and recommends responding to the dispute instead, to avoid reimbursing the customer twice. The deadlines and the rules for contesting a dispute belong to the provider and the card networks, so the system tracks them and does not hard-code them.

    Late states. A payment can stay in processing for days (asynchronous methods can take up to a few days), so set a policy: how long checkout waits, what the order shows, and when support is alerted.

    Deep dive 6: reconciliation and the multi-provider temptation

    Reconciliation compares your ledger and payment table with the provider's reports and turns each difference into a named item, as in the ledger lesson. The system-level points: run it daily at least; join on provider ids, never on amount and date; classify breaks (at the provider but not in the ledger, in the ledger but not at the provider, amounts differ, timing only); and alert on any break older than the expected settlement window. It is also the net under every other mechanism: a webhook that was never delivered is invisible to the inbox, and visible to reconciliation.

    Multiple providers. A second provider is tempting for resilience and routing. The danger is the unknown outcome. If provider A times out and you retry the charge on provider B, the buyer may be charged twice, once by each. The rule in this reference design: a payment stays with its provider until its outcome is known; only a new payment, created after the first is resolved as failed or canceled, may be routed elsewhere. This is a design rule of this lesson, not a documented behaviour of any provider. Each provider has its own idempotency, events and reports, so a second provider doubles the reconciliation, and an abstraction layer should keep provider-specific states out of your own payment states.

    Security and compliance boundaries

    The Stripe integration security guide describes PCI DSS as the global security standard for entities that store, process or transmit cardholder data, says compliance is a shared responsibility, and says that handling raw card numbers directly may require meeting more than 300 security controls, whereas integrations in which payment details go straight to the provider without passing through your servers reduce your obligations. That is why the reference design uses provider-collected payment tokens and never stores or logs card numbers. The guide also lists non-sensitive card data (card type, last four digits, expiry) as storable. Which standards, attestations and reports apply to a particular business is a compliance decision for its owners and advisers; this lesson does not state them.

    Engineering controls that follow: verify webhook signatures and use TLS on the endpoint; keep provider secret keys in a secrets manager and rotate them (secrets management); never log payloads that could contain sensitive data; and write an audit record of every state change and every manual action (audit logging).

    Failure modes

    Failure Effect Mitigation
    Timeout on the provider call Unknown outcome Idempotent retry with the operation key; mark unknown; wait for the event
    Duplicate webhook Double ledger posting Inbox ON CONFLICT, unique source_id
    Events out of order Wrong state Transition guards; fetch the current object
    Webhook endpoint down Events delayed, retried by the provider for days Replay; reconciliation catches gaps
    Worker crashes mid-post Half-posted ledger One transaction for post and state change; replay is safe
    Over-refund from concurrent requests Money lost Conditional update plus CHECK
    Capture on an authorisation the provider no longer honours Capture fails Capture-age alert; check the provider's rules, reauthorise or cancel the order
    Provider outage Checkout fails Clear message, no automatic cross-provider retry on unknown outcomes
    Dispute arrives Funds pulled, fees Event handler posts entries; evidence workflow
    Reconciliation break A named difference Triage by break type; post the missing fact

    Trade-offs

    Decision Option A Option B How to choose
    Charge timing Capture at checkout Authorise, capture at fulfilment Authorise first when the final price can change; open authorisations need a sweeper
    Source of truth for outcome Provider response Provider events (plus fetch) Events; the response may be lost
    Ledger store Same database as payments Separate database Separate when write isolation and permissions matter more than the cost
    Balances Stored and updated Derived from entries Derived, with snapshots, when correctness matters most
    Providers One Several One until an outage or fee reason is concrete; then separate payments, not retries

    Build it

    There is no lab. The runnable material that exists is the Node ledger script in payments and double-entry ledgers and the Spring filter in idempotency keys and safe retries. The SQL on this page was checked on a single connection only; it does not show behaviour under concurrent sessions, and no output is claimed.

    In practice: ShopStream replaces in-place balances

    This is a realistic scenario, not a case history.

    The situation

    ShopStream, the course's running example grocery marketplace, takes 500,000 orders a day and pays stores a day later. The checkout calls the payment provider inline and sets orders.paid = true on a 200. Seller balances are columns edited in place. Last month, checkout timeouts produced 212 orders that were charged but not marked paid, and finance could not explain a gap between the provider's payout report and the balances. These numbers are illustrative.

    Starting architecture

    Starting architecture: inline call, in-place balancesCheckout to Payment provider (charge); Checkout to Orders DB (set paid)Checkout: calls provider inlineCheckoutcalls providerinlineOrders DB: paid flag, balancesOrders DBpaid flag,balancesPayment providerPaymentproviderchargeset paid

    Figure 6. Starting point. How to read this: if the provider call succeeds and the reply is lost, the charge exists and the flag does not. A webhook that edits a balance in place would double-count a duplicate.

    Options considered

    Option Gain Cost Wrong when
    A. Retry the charge on timeout Small change A retry without a key charges twice Never, without keys
    B. Add idempotency keys and a webhook inbox, keep balances in place Fixes duplicates and lost replies Still no history or reconciliation Finance needs to explain every cent
    C. Payment state machine, inbox and queue, keys derived from the payment id, append-only ledger, daily reconciliation Repeat-safe at every boundary; explainable New components; two models to keep consistent Volume is trivial

    The decision

    Option C, introduced in stages. The payment service owns the state machine and the idempotency keys. Provider events go through a signature check, an inbox and a queue. A ledger worker posts balanced transactions keyed by event id, and the old seller balance becomes a cache rebuilt from entries. Orders authorise at checkout and capture at fulfilment. A daily job reconciles against the provider's reports. Legal and accounting questions, such as how long records are kept, go to the finance and legal owners.

    Rollout and verification

    1. Add idempotency keys to the existing provider calls first; this alone stops duplicate charges.
    2. Run the inbox and ledger worker in shadow mode: post every event, keep the old balance as the truth, and compare daily.
    3. Replay a day of events twice and confirm nothing changes; send a duplicate and an out-of-order refund in a test environment and confirm the guards hold.
    4. Force a timeout after the provider has accepted the request and confirm the order ends up paid exactly once.
    5. Switch reads to the ledger when reconciliation has been clean for an agreed period.

    The 2 a.m. failure

    The page reads: "reconciliation difference of one payout, provider net higher than the ledger". The ledger worker's dead-letter queue holds 40 events: after a deploy, the worker rejected a new event type it did not recognise, and the transition guard refused them. First checks: the dead-letter queue age, the event types in it, and which payments are in processing longer than policy. Mitigation: deploy a handler that records unknown event types in the inbox without acting on them, replay the dead-letter queue (safe, because posting is keyed by event id), and rerun reconciliation. The lasting fix: a contract test that every event type the integration subscribes to has a handler, and an alert on dead-letter depth.

    Architect's notes

    • Make the provider authoritative for card outcomes. Your state machine follows its states.
    • Derive keys from the operation. A fresh random key per attempt defeats idempotency.
    • Write intent before acting. Commit the attempt, then call the provider.
    • Treat every inbound event as untrusted and repeatable. Verify, record once, process later.
    • Keep money records append-only. Corrections are new rows.
    • Do not hard-code provider rules. Deadlines, fees and windows change; store them as configuration with a source.

    Common mistakes

    • Treating the first HTTP response as the final state. processing is a valid, common outcome.
    • A new idempotency key per retry. Each retry then becomes a new charge.
    • Processing webhooks inline. A spike or a slow dependency makes the provider retry and pile up.
    • Trusting event order. Fetch the current object when state and event disagree.
    • Editing balances in place. There is no history and a duplicate double-counts.
    • Retrying on a second provider after an unknown outcome. That is how a buyer pays twice.
    • Logging full payloads. Webhook and request bodies can hold sensitive data.
    • Hard-coding settlement or dispute windows. They belong to the provider and change.

    Key takeaways

    • A payment system is a state machine plus an append-only ledger, and the boundary between them is unique ids.
    • A timeout is a state: record the attempt first, retry with the same operation key, and wait for the event.
    • Inbox, queue and transition guards turn at-least-once, unordered events into exactly-once effects.
    • Refunds, disputes and failures are ordinary events with their own keys, states and ledger entries.
    • Over-refund and double posting are prevented in the data (conditional update, CHECK, unique source_id), not only in code.
    • Reconciliation is the net under everything, and a break is a named item, not a mystery.

    Practice exercises

    Exercise 1, Starter (30 min): Using the illustrative table, recompute ledger rows per day if 10 percent of orders are refunded and each refund posts 3 entries. How many rows per year, and does anything in the design change?

    Exercise 2, Intermediate (2 hours): Write the transition table for the payment states in Figure 4: for each (state, event) pair say the new state, or "ignore" for a late duplicate. Which pairs raise an alert?

    Exercise 3, Intermediate (2 hours): Design the recovery job for payments stuck in processing. What does it query, which operation key does it reuse, and when does it stop and page a human?

    Exercise 4, Advanced (half day): Add a second provider for one payment method only. Specify how a payment is assigned to a provider, what happens to an unknown outcome, and what the reconciliation job joins on for each provider.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments