Skip to content

    System Design

    Payment Systems and Double-Entry Ledgers

    Design payments around a provider and a double-entry ledger: payment states, retries, webhooks, integer money, immutable entries, reversals and reconciliation.

    By Published 12 min read

    Share

    Standard lessonadvancedBackend System Design

    Before this: Idempotency Keys and Safe Retries, Distributed Transactions: 2PC and Sagas

    What you'll learn: By the end of this lesson you will be able to separate a payment's lifecycle from the record of money, model a payment provider's asynchronous states and webhooks, store amounts as integers, build a double-entry ledger whose entries always balance and are never edited, post to it idempotently, undo a mistake with a reversal, and reconcile the ledger against a provider's report.

    A club treasurer keeps a cash book. Every pound that moves is written twice: once where it came from, once where it went. Nothing is rubbed out. If a line is wrong, a correcting line is added below it. At the end of the month the treasurer compares the book with the bank statement, and any difference is a thing to explain, not to hide.

    A payment system keeps the same discipline in software. This lesson is a design lesson, not legal, tax or financial advice. Rules about holding customer funds, record retention, card-data handling and reporting depend on the country and the provider's terms, and none are described here; ask your compliance and legal advisers. The lesson builds on idempotency keys and the distributed transactions lesson. A longer worked example with SQL is in the ShopStream payments and ledger stage; this lesson is the dedicated treatment of the ledger idea. It is an educational reference design, not the verified internal architecture of any company.

    Verified on 2026-12-02 against the Stripe API documentation (as one example of a provider; its behaviour is cited, nothing is claimed about its internals) and the PostgreSQL manual. The Node script on this page was run on that date; there is no lab.

    The core idea

    A payment system is two things kept apart: a state machine that talks to an unreliable outside provider, and an append-only ledger that records what money moved. The state machine may retry, wait and be told the same thing twice. The ledger only ever receives balanced, uniquely identified facts. Everything in this lesson protects that boundary.

    Three illustrations run through it:

    • Minimal example: the Node script below, a four-account ledger with a capture, a refund and a payout.
    • Realistic example: a marketplace that takes a fee and pays sellers later.
    • Failure example: a provider event the system never recorded, found only by reconciliation.

    The lifecycle belongs to the provider

    A card payment is not instant or binary. Stripe's PaymentIntent lifecycle is one concrete example: a payment moves through requires_payment_method, requires_confirmation, requires_action (for example 3D Secure), processing and succeeded, and can be canceled before it processes. Asynchronous methods such as bank debits can sit in processing for days. A failed attempt returns the intent to requires_payment_method so it can be retried. Your own order record should mirror these states and never assume success from the first HTTP response.

    Authorize, then capture. A card can be authorized, which holds the amount, and captured later. Stripe's documentation says the funds must be captured before the authorization expires, otherwise they are released and the payment is canceled; validity windows vary by card brand and transaction type, and a partial capture releases the rest. The design consequence: a hold is a promise, not money, so it is not a ledger movement. Record the authorization on the payment, and post to the ledger at capture.

    Retries, webhooks and duplicates

    Two failures are certain: your request to the provider times out, and the provider's notification to you arrives more than once.

    For the first, send an idempotency key with each create or update. Stripe's documentation says that for API v1 it saves the status code and body of the first request with a key and returns the same response for retries, including 500 errors, that reusing a key with different parameters is an error, and that keys may be pruned after at least 24 hours. It also says a request that fails validation or conflicts with one still executing is not saved, so it can be retried. The general design is in idempotency keys and safe retries.

    For the second, the webhook handler follows the provider's guidance:

    • Verify the signature over the raw body before trusting anything (Stripe signs each event with HMAC-SHA256 and recommends a timestamp tolerance to stop replays).
    • Return a 2xx quickly, then process through a queue.
    • Expect duplicates and disorder. The documentation says an endpoint may receive the same event more than once, delivery order is not guaranteed, and events should be deduplicated by event id. It suggests fetching the current object when events arrive out of order.
    sequenceDiagram accTitle: A captured payment reaching the ledger accDescr: The checkout service asks the provider to capture with an idempotency key. The provider confirms by webhook, possibly more than once. The webhook handler verifies the signature, returns success quickly and enqueues the event. A worker posts balanced entries to the ledger using the provider event id as the unique source id, so a duplicate posts nothing. participant S as Checkout service participant P as Provider participant H as Webhook handler participant L as Ledger S->>P: capture (idempotency key) P-->>H: webhook: captured (event id e1) H->>H: verify signature on raw body H-->>P: 200 quickly H->>L: post(source e1, balanced entries) P-->>H: same event again (duplicate) H->>L: post(source e1) finds it already posted

    Figure 1. Idempotency at both ends. How to read this: the key protects the request out, the event id protects the fact in. Each is a uniqueness check, not a hope.

    Money is an integer

    Never store money as floating point. The PostgreSQL manual says real and double precision are inexact, so "storing and retrieving a value might show slight discrepancies", and recommends numeric for monetary amounts. A common design stores an integer count of the currency's smallest unit (minor units: 4500 for 45.00 in a two-decimal currency) next to a currency code, in a bigint (range up to 9,223,372,036,854,775,807). Never add amounts of different currencies. Fractions return with percentages: decide the rounding rule once, compute one side, and get the other by subtraction so the parts always sum to the whole.

    The double-entry ledger

    A ledger is the permanent record of money movements. An account is a named place money can be (provider_clearing, seller_payable, fee_revenue). An entry is one line: account, side (debit or credit) and a positive amount. A transaction is the set of entries that belong together, and its invariant is that, per currency, debits equal credits. Value only moves between accounts; it is never created or destroyed.

    One capture split across ledger accountsBuyer pays to Provider clearing (capture); Provider clearing to Seller payable (owed to seller); Provider clearing to Fee revenue (earned)Buyer pays: 5,000Buyer pays5,000Provider clearing: debit 5,000Providerclearingdebit 5,000Seller payable: credit 4,500Seller payablecredit 4,500Fee revenue: credit 500Fee revenuecredit 500captureowed to sellerearned

    Figure 2. One debit, two credits. How to read this: the arrows are allocation, not three payments. The single debit of 5,000 is matched by credits of 4,500 and 500 (illustrative, a 10 percent fee).

    Four rules make it a ledger rather than a table of numbers:

    1. Entries are immutable. A mistake is fixed by a reversing transaction: a new transaction with the opposite sides. Both the error and the fix stay visible, which is what an auditor needs (audit logging).
    2. Balances are derived. A balance is the sum of an account's entries. A stored balance is a cache that can be rebuilt.
    3. Each transaction has a unique source id, the provider reference or your own operation id, enforced by a unique constraint. A second post with the same source id is a no-op.
    4. The database enforces balance. The application checks it, and a constraint or trigger should too, because a bug later will not.

    The refund shows rule 1: it is not an edit of the capture, it is a new transaction with its own provider reference.

    Running it

    The script below is the whole model: post rejects unbalanced input and deduplicates by source id, and balance sums entries. It then replays a capture (twice), an unbalanced attempt, the provider's fee, a partial refund and a seller payout, all in minor units (illustrative amounts), and finishes with a reconciliation against a provider report.

    const ledger = [];
    const seen = new Map();
    
    function post(sourceId, entries) {
      if (seen.has(sourceId)) return `duplicate of tx ${seen.get(sourceId)}`;
      const sums = {};
      for (const e of entries) {
        if (!Number.isSafeInteger(e.amount) || e.amount <= 0) throw new Error(`bad amount ${e.amount}`);
        sums[e.currency] = (sums[e.currency] ?? 0) + (e.side === "debit" ? e.amount : -e.amount);
      }
      for (const [cur, s] of Object.entries(sums)) if (s !== 0) return `rejected, ${cur} unbalanced by ${s}`;
      const txId = ledger.length + 1;
      ledger.push({ txId, sourceId, entries });
      seen.set(sourceId, txId);
      return `posted as tx ${txId}`;
    }
    
    const balance = (account) => ledger.flatMap((t) => t.entries)
      .filter((e) => e.account === account)
      .reduce((b, e) => b + (e.side === "debit" ? e.amount : -e.amount), 0);
    
    const d = (account, amount) => ({ account, side: "debit", amount, currency: "USD" });
    const c = (account, amount) => ({ account, side: "credit", amount, currency: "USD" });
    const capture = [d("provider_clearing", 5000), c("seller_payable", 4500), c("fee_revenue", 500)];
    
    console.log("capture      ", post("cap_1001", capture));
    console.log("same webhook ", post("cap_1001", capture));
    console.log("unbalanced   ", post("cap_1002", [d("provider_clearing", 5000), c("seller_payable", 4400), c("fee_revenue", 500)]));
    console.log("provider fee ", post("fee_1001", [d("processing_fee_expense", 175), c("provider_clearing", 175)]));
    console.log("refund 1000  ", post("ref_2001", [d("seller_payable", 900), d("fee_revenue", 100), c("provider_clearing", 1000)]));
    console.log("payout       ", post("pay_3001", [d("seller_payable", 3600), c("provider_clearing", 3600)]));
    
    console.log("--- balances (debits minus credits) ---");
    for (const a of ["provider_clearing", "seller_payable", "fee_revenue", "processing_fee_expense"]) {
      console.log(a.padEnd(24), String(balance(a)).padStart(6));
    }
    
    const providerReport = [
      { id: "cap_1001", amount: 5000 }, { id: "fee_1001", amount: -175 },
      { id: "ref_2001", amount: -1000 }, { id: "pay_3001", amount: -3600 },
      { id: "dsp_4001", amount: -1500 },
    ];
    const known = new Set(seen.keys());
    const providerNet = providerReport.reduce((s, r) => s + r.amount, 0);
    console.log("--- reconciliation against the provider report ---");
    console.log("provider net", providerNet, "| ledger provider_clearing", balance("provider_clearing"));
    console.log("not in ledger:", JSON.stringify(providerReport.filter((r) => !known.has(r.id))));
    console.log("not at provider:", JSON.stringify([...known].filter((id) => !providerReport.some((r) => r.id === id))));

    Output of that script, run with Node 26.13.1 on 2026-12-02:

    capture       posted as tx 1
    same webhook  duplicate of tx 1
    unbalanced    rejected, USD unbalanced by 100
    provider fee  posted as tx 2
    refund 1000   posted as tx 3
    payout        posted as tx 4
    --- balances (debits minus credits) ---
    provider_clearing           225
    seller_payable                0
    fee_revenue                -400
    processing_fee_expense      175
    --- reconciliation against the provider report ---
    provider net -1275 | ledger provider_clearing 225
    not in ledger: [{"id":"dsp_4001","amount":-1500}]
    not at provider: []

    Read it. The duplicate webhook posted nothing, and the unbalanced attempt was refused by 100 minor units. After the refund and payout, seller_payable is exactly zero (4,500 - 900 - 3,600): the seller has been paid what they were owed. fee_revenue shows -400 because credits are negative in this convention, a net 400 earned (500 - 100). provider_clearing holds 225: the 175 fee was recorded as an expense paid out of clearing, so the rest is money the provider still holds for the platform, the 400 fee revenue less the 175 fee. The ledger and the provider report disagree only on the last item, found in the next section.

    Pending, available and payouts

    Providers hold funds in states. Stripe's balances documentation says funds are pending until settlement, then available at each balance transaction's available_on time, and that refunds and disputes are deducted from the payments balance. Settlement time varies by country and payment method. A ledger can mirror this with separate accounts (provider_pending, provider_available) and a transfer entry when funds settle, so "what we may pay out today" is a balance, not a guess. The seller payout is a movement from seller_payable to clearing, exactly as in the script.

    Reconciliation

    Reconciliation compares your ledger with an outside record and turns every difference into a named item. Stripe's payout reconciliation report, for example, matches each payout with the batch of transactions it settles, and its documentation says to match rows by payout id rather than by assuming report dates equal bank-arrival dates. Instant payouts need your own reconciliation because the provider cannot say which transactions each includes.

    Four kinds of break, each with a different cause:

    Break Likely cause Action
    At provider, not in ledger Missed or unsubscribed event Post it, then fix the subscription
    In ledger, not at provider Posted before confirmation, or wrong id Reverse it, find the source
    Both, different amount Rounding, fee or currency rule Fix the rule; reverse and repost
    Timing only Settlement not yet available Wait; show as expected

    In the script, the report has dsp_4001 for -1,500 that the ledger never saw: a dispute. The difference between provider net and ledger clearing is exactly that item, which is what makes a break actionable.

    flowchart TD accTitle: Reconciliation decision for one provider item accDescr: For each item in the provider report, look up its id in the ledger. If absent, it is missing in the ledger and must be posted. If present, compare amounts. A mismatch is investigated. A match is reconciled. Items in the ledger that are absent from the report are checked next, and timing differences are tolerated until a deadline. A["Provider item"] --> B{"In ledger by id?"} B -->|no| C["Missing in ledger: post and investigate"] B -->|yes| D{"Same amount?"} D -->|no| E["Mismatch: investigate"] D -->|yes| F["Reconciled"]

    Figure 3. Match by id, then by amount. How to read this: the source id is the join key. Without a stable id on both sides, reconciliation becomes guessing from amounts and dates.

    Trade-offs

    Choice Gain Cost Wrong when
    Separate payment state and ledger Retries never corrupt money records Two models to keep consistent A single internal wallet with no provider
    Immutable entries with reversals Full history, auditable More rows; no quick fix by edit Entries are scratch data
    Derived balances Rebuildable, always consistent Reads cost more; a cache is needed Balances are read millions of times a second
    DB-enforced balance Bugs cannot unbalance the ledger Triggers or constraints to maintain Throughput needs outweigh safety (rare)
    Daily reconciliation Breaks found in a day Needs provider reports and ids Volume is tiny

    Build it

    There is no lab. The script above is the executable model, and the only thing it shows as run is its own output. It is not a production ledger: there is no database, concurrency control or persistence.

    In practice: a marketplace that takes a fee

    This is a realistic scenario, not a case history.

    The situation

    A marketplace like ShopStream (the shared illustrative figure is 500,000 orders per day) charges buyers, keeps a fee, and pays sellers later. Today an orders table has a paid flag and a seller_balance column updated in place. Refunds edit the balance. Finance cannot explain last month's difference with the provider's statement.

    Starting architecture

    Starting architecture: balances edited in placePayment provider to Order service (event); Order service to Orders DB (update in place)Order service: sets paid flagOrder servicesets paid flagOrders DB: balance editedOrders DBbalance editedPayment provider: webhooksPaymentproviderwebhookseventupdate in place

    Figure 4. Truth overwritten. How to read this: a webhook updates a balance directly, so a duplicate double-credits and a refund erases history.

    Options considered

    Option Gain Cost Wrong when
    A. Add more checks to the update Small change Still no history or reconciliation Audit matters
    B. Append-only table of movements, one account per seller Simple, history No balance invariant across accounts Fees and clearing must tie out
    C. Double-entry ledger in its own database, idempotent posting by provider id, daily reconciliation Invariant, history, found breaks New component to run Volume is trivial

    The decision

    Option C. The order service keeps the payment state machine. A worker consumes verified, deduplicated webhook events and posts balanced transactions keyed by the provider's id. Balances are derived; the old seller_balance becomes a cache rebuilt from entries. A daily job compares the ledger with the provider's report. Compensation in the order saga (distributed transactions) means posting reversals, never deleting rows. Legal and accounting questions, such as how long to retain records, go to the finance and legal owners.

    Rollout and verification

    Run the ledger in shadow mode first: post every event, keep the old balance as the source of truth, and compare daily. Verify that replaying the same webhook twice changes nothing, that a deliberately unbalanced post is refused, and that rebuilding balances from entries matches the cache. Switch reads once reconciliation is clean for an agreed period.

    The 2 a.m. failure

    The daily reconciliation pages: "provider net differs from ledger by -1,500". A dispute event was never recorded because the webhook endpoint was not subscribed to that event type.

    First checks: list provider items missing from the ledger (one, a dispute), confirm the event types subscribed, and check no other type is missing. Mitigation: post the dispute as a balanced transaction (debit a disputes account, credit clearing) using its provider id, subscribe the endpoint, and replay recent events; idempotent posting makes the replay safe. Follow-up: a test that every event type the business depends on is subscribed, and an alert on any non-zero reconciliation difference older than the expected settlement window.

    Architect's notes

    • Keep the ledger boring: few account types, integer amounts, no business logic beyond balance.
    • Use the provider's id as the source id wherever one exists.
    • Post at capture, not at authorization.
    • Reverse, never edit. If an operator needs "fix it", give them a reversing transaction tool with a reason and an audit trail.
    • Reconcile on a schedule and alert on any unexplained difference.
    • Name the legal questions and send them to the people who own them.

    Common mistakes

    • Floating-point money.
    • Updating a balance in place instead of appending entries.
    • Trusting the first webhook or assuming events arrive once and in order.
    • Treating an authorization as money.
    • No unique source id, so a retry posts twice.
    • Reconciling by amount and date with no shared id.

    Key takeaways

    • Keep payment state (provider-driven, retried) apart from the ledger (balanced, immutable facts).
    • Make retries safe at both ends: idempotency keys out, event-id deduplication in.
    • Store integer minor units with a currency; never floats.
    • Every ledger transaction balances per currency and is never edited; reverse instead.
    • Derive balances; mirror provider states such as pending and available with accounts.
    • Reconcile against the provider by stable id and treat every difference as an item to explain.

    Practice exercises

    Exercise 1 (30 min). Add a transaction for the dispute dsp_4001 to the script (debit disputes_expense, credit provider_clearing, 1,500). Does the reconciliation line then report no differences?

    Exercise 2 (1 hour). Add a currency mismatch test: a transaction with a USD debit and an EUR credit of the same number. What does post do, and why is that right?

    Exercise 3 (2 hours). Design the unique constraint and the trigger or check that makes a database refuse an unbalanced transaction, without reading the ShopStream lesson's SQL first. Then compare.

    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