Course contents

17. Real-World System Design Lesson 8 of 20

Payment System

Design a payment system: idempotency keys, double-entry ledger, PSP timeouts and safe retries, outbox events, PSP failover and daily reconciliation.

25 minAdvanced9 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • A timeout is an unknown outcome; retrying it blindly can charge twice.
  • One idempotency key per payment, stored before the charge and passed to the PSP, makes retries safe.
  • The ledger is double-entry and append-only: balanced transactions, corrections as new entries.
  • Ledger entries and the outgoing event commit together via an outbox.
  • A second PSP removes a single point of failure; fail over only on definite errors.
  • Daily reconciliation against settlement reports catches whatever slipped through.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

A payment system takes money from a customer and credits it to a merchant. It talks to one or more payment service providers (PSPs: card processors, acquirers, wallets, bank transfer rails) that actually move money, and keeps its own ledger that records every movement. Around those sit checkout, refunds, payouts, notifications and reconciliation.

Why it exists

Money is unforgiving: a double charge or a lost payment is a support case, a refund, sometimes a regulatory problem. The PSP is a remote system you cannot roll back, reached over a network that times out, and it reports results asynchronously (webhooks, daily files). A payment system exists to turn this unreliable path into effects that happen exactly once and records that can be proven correct.

How it works

Requirements. Functional: pay, refund, query status, notify downstream services. Non-functional: no double charges, no lost payments, exact amounts (integers in minor units with an explicit currency), a full audit trail, and availability during peaks. Throughput is rarely the hard part.

Estimates (illustrative). 2 million payments a day is about 23 per second on average and a few hundred per second during a big sale. Each payment writes a handful of ledger rows. A relational database handles this comfortably; the design effort goes into correctness.

Idempotency keys. The client generates a key per payment attempt and sends it with every retry. The payment service inserts the key (unique constraint) with status pending before calling the PSP, so a concurrent or later retry finds it and either waits for or returns the stored result. The same key goes to the PSP: major PSP APIs accept idempotency keys and return the original result for a repeated key.

Timeouts are unknowns. If the PSP call times out, the charge may or may not exist. Retry with the same key, query the PSP for the payment status, or wait for the webhook. Never retry with a new key and never switch to another provider for an unknown outcome.

Double-entry ledger. Each business event is a transaction of entries across accounts whose amounts sum to zero (debit customer funds, credit merchant payable). Entries are immutable; refunds, chargebacks and fixes are new transactions. Balances are derived from entries (often cached in balance rows updated in the same transaction).

Outbox. The ledger transaction also inserts a PaymentSucceeded row into an outbox table. A relay publishes outbox rows to a broker and marks them sent; consumers deduplicate by payment id because delivery is at least once.

PSP routing and failover. A router can spread traffic over several PSPs (for cost, approval rates and redundancy) and health-check them. A request that failed definitely (connection refused, or an error the PSP documents as "not processed") may be retried on another PSP; a request with an unknown outcome may not.

Reconciliation. PSPs publish settlement reports listing what they captured and paid out. A daily job matches them against the ledger, payment by payment, and resolves differences: missing captures, amount mismatches, fees, chargebacks.

When to use it

Whenever your product moves money on behalf of customers or merchants: e-commerce checkouts, marketplaces, subscriptions, wallets, payouts. Even if a PSP's hosted checkout does most of the work, you still need idempotent calls, a ledger of what you believe happened and reconciliation.

When not to

  • A single merchant with a hosted checkout page and no internal balances: the PSP's dashboard and webhooks may be enough; a full ledger is overhead.
  • Do not build card processing itself unless you are a PSP: holding raw card data brings full PCI DSS scope. Tokenise through the PSP instead.

Trade-offs

Choice You gain You pay
Authorise now, capture later Can cancel without a refund; capture on shipment Authorisations expire; two steps to track
Several PSPs No single point of failure, cost and approval-rate routing Integration and reconciliation per PSP, harder failover rules
Strongly consistent relational ledger Simple invariants, transactions Write throughput limits; partition by account at very large scale
Synchronous charge in checkout Immediate answer to the shopper Checkout latency and availability tied to the PSP
Aggressive client retries Fewer visible failures Load amplification during outages; must be idempotent

Alternatives

  • Asynchronous payments: accept the order, charge in the background and notify the customer; better availability, worse immediacy.
  • Saga across order, payment and inventory with compensations (refund, release stock) instead of one synchronous flow.
  • Payment orchestration platforms that provide routing, retries and reconciliation across PSPs as a service.

Failure modes

  • Double charge from retries without an idempotency key, or from failing over to another PSP after a timeout.
  • Lost payment: charged at the PSP, never recorded (crash after the call). The pending idempotency record plus status queries and reconciliation recover it.
  • Lost event: ledger committed, event never published. The outbox prevents it.
  • PSP outage or slowness: health checks catch dead providers, not slow ones; watch latency and error rate per PSP and drain slow ones.
  • Retry storms during an outage: cap attempts, back off with jitter, open a circuit breaker.
  • Floating-point money: rounding errors. Use integer minor units or decimal types.

In production

Monitor authorisation rate, error rate and latency per PSP and per payment method, the age of pending payments, outbox lag, and reconciliation mismatches. Keep webhooks idempotent too (PSPs retry them). Expire idempotency keys after a documented window (often 24 hours or more). Separate the ledger's accounts by currency. Keep card data out of your systems with PSP tokenisation to minimise PCI DSS scope. Run reconciliation daily and alert on unresolved differences.

Common misconceptions

  • "Retries make payments reliable." Only idempotent retries do; otherwise they make duplicates.
  • "A timeout means the payment failed." It means unknown.
  • "Exactly-once delivery solves it." No network delivery is exactly once; exactly-once effects come from idempotency on the receiving side.
  • "Failing over to another PSP is always safe." Only for definite failures.
  • "The PSP's dashboard is our ledger." You need your own record to reconcile against theirs.

Interview angle

Start with requirements that emphasise correctness, then draw checkout → payment service → ledger and PSP. Interviewers probe: what happens if the PSP times out (unknown, idempotency key, status query), how you avoid double charges on client retries, how the ledger is structured (double-entry, append-only, minor units), how other services learn about payments (outbox), what happens when a PSP is down or slow, and how you know the books are right (reconciliation). Saying "a timeout is an unknown, not a failure" early sets the tone.

Model assumptions

The simulated steps are a simplified model, not a benchmark. Checkout starts 20 payments per second (Poisson) with a 1.5 s timeout and one retry after a random delay of up to 200 ms; every attempt that fails is retried, whether the failure was definite or not. The payment service writes to the ledger (about 8 ms) and then calls the PSP, an external server with about 300 ms per call (lognormal, cv 0.3); the slow PSP runs six times slower. A PSP that answers successfully is counted as one charge, so a payment whose original and retried attempts both reach the PSP is counted as charged twice. The PSP router health-checks every 500 ms and ejects a PSP after two failed checks; health checks do not detect slowness. Idempotency keys, ledger transactions, the outbox and reconciliation are scripted illustrations; the engine does not model idempotency, transactions or settlement files. Numbers show behaviour and orders of magnitude only.

The lesson as textEvery step of the simulation, written out.
  1. 1. Correctness first, throughput second

    Checkout calls a payment service, which records the payment in a ledger and asks a payment service provider (PSP: a card processor or acquirer) to charge the card. Here 20 payments per second all succeed; most of the latency is the PSP call.

    Requirements: never charge twice, never lose a payment, amounts exact (integers in minor units, never floats), every movement auditable. Illustrative estimate: 2 million payments a day is about 23 per second on average and a few hundred at a sales peak. The load is modest. What makes payments hard is that the PSP is a remote system you cannot roll back, reached over a network that can fail at any moment.

    Scene: Checkout sends 20 payments per second to the Payment Service, which writes to the Ledger DB and calls PSP A. Every payment succeeds in roughly half a second.

    Key idea: In payments, the hard requirements are exactly-once effects and auditability across a system you do not control, not throughput.

  2. 2. A slow PSP and an innocent retry

    One second in, the PSP slows down to almost two seconds per call. Checkout gives up after 1.5 s and retries. But the first call was not cancelled: the PSP is still working on it and, a moment later, charges the card. Then the retry arrives and charges it again.

    Watch the retries counter: in this run many payments are charged twice, and most shoppers still see an error. A timeout tells you nothing about whether the charge happened. Retrying a non-idempotent call after a timeout is how double charges are made.

    Scene: PSP A slows to about 1.8 s per call. Checkout times out and retries; the PSP completes both the original and the retried charge, so cards are charged twice while shoppers see errors.

    Key idea: A timeout means “unknown”, not “failed”. Blind retries on unknown outcomes duplicate side effects.

  3. 3. One key, one charge

    Checkout now creates an idempotency key per payment attempt (K1) and sends it with every retry. The payment service stores K1 in the ledger database before calling the PSP, and passes the same key to the PSP, which most PSP APIs accept.

    The first call is slow, the shopper retries with K1. The payment service finds K1 already in progress and forwards the same key; the PSP recognises K1 and returns the original charge ch_1 instead of making a new one. The ledger records one payment and the shopper gets one answer. This step is a scripted illustration; the engine does not model idempotency.

    Scene: Checkout retries a slow payment with the same idempotency key. The payment service finds the key in the ledger, forwards it to the PSP, and the PSP returns the original charge for both calls. One payment is recorded and the shopper gets one answer. Scripted illustration.

    Key idea: Same key ⇒ same result. Store the key before the side effect and propagate it to every downstream that can charge.

  4. 4. A double-entry, append-only ledger

    The ledger records every money movement as a transaction of balanced entries: a 49.99 payment debits the customer-funds account and credits the merchant-payable account, and the entries of each transaction sum to zero. Both are written in one database transaction, so money is never created or lost by a half-written update.

    Entries are never updated or deleted. A refund is a new transaction with the opposite entries, after its own PSP call. Balances are sums of entries, and the full history explains every balance: that is what auditors and reconciliation need. Scripted illustration.

    Scene: The payment service writes a balanced payment transaction to the ledger. Later a refund goes to the PSP and is recorded as a second, reversed transaction; nothing is updated in place. Scripted illustration.

    Key idea: Debits equal credits in every transaction, and history is append-only: corrections are new entries, never edits.

  5. 5. Tell the rest of the company, reliably

    Orders, emails and analytics must learn that a payment succeeded. Publishing to a broker after the ledger commit is a dual write: a crash in between loses the event. So the payment service writes the ledger entries and a PaymentSucceeded row into an outbox table in the same transaction.

    A separate relay reads new outbox rows, publishes them to the broker and marks them sent. If the relay crashes it publishes again, so consumers see each event at least once and deduplicate by payment id. Scripted illustration; the transactional-outbox lesson simulates the pattern in depth.

    Scene: The payment service commits ledger entries and an outbox row together. The relay reads the row, publishes PaymentSucceeded to the broker, which delivers it to Orders, and marks the row as sent. Scripted illustration.

    Key idea: Money and the news about money are committed together; a relay delivers the news at least once.

  6. 6. The only PSP goes down

    Traffic is back at 20 payments per second. One second in, PSP A goes down completely: connections are refused. Unlike a timeout, a refused connection is a definite failure: no charge can have happened, so retrying is safe.

    But there is nowhere to retry. The retry hits the same dead PSP and every payment fails from then on. The shop is up, the payment service is up, and nobody can pay. With a single external dependency on the critical path, its availability caps yours.

    Scene: PSP A goes offline. Payments fail immediately, retries hit the same dead PSP, and from then on every payment fails.

    Key idea: A single PSP is a single point of failure you do not operate. Classify failures: definite ones can be retried elsewhere, unknown ones cannot.

  7. 7. Route around a dead PSP

    The payment service now calls a PSP router that spreads payments over PSP A and PSP B and health-checks both every 500 ms. PSP A goes down again one second in. For about a second, payments routed to A fail; some succeed anyway because their retry (safe here: connection refused is definite) lands on B.

    After two failed health checks the router ejects PSP A and everything goes to B: errors stop. The rule that keeps this safe: fail over on definite errors only. After a timeout, the charge may exist at A; sending it to B could charge the card twice with two different providers, which no idempotency key can prevent. Unknown outcomes go to a status check or reconciliation instead.

    Scene: A PSP router sends payments to PSP A and PSP B. PSP A goes down; a few payments fail until health checks eject it about a second later, then PSP B handles everything and errors stop.

    Key idea: Multiple PSPs remove the single point of failure, as long as only definite failures are retried on the other provider.

  8. 8. Reconcile against the PSP’s records

    Some outcomes stay unknown: a timeout during the outage, a webhook that never arrived. Every day each PSP publishes a settlement report of what it actually captured. A reconciliation job loads the report and compares it, payment by payment, with the ledger.

    Here it finds one mismatch: pay_812 is “unknown” in the ledger but “captured” at the PSP. The job records the missing transaction as new ledger entries and flags the case if amounts differ. Reconciliation is the safety net that turns “we think” into “we know”, and it is how a payment system proves it is correct. Scripted illustration.

    Scene: PSP A drops its daily settlement file into storage. The reconciler reads it, compares it with the ledger, finds one payment the ledger did not know was captured, and writes correcting entries. Scripted illustration.

    Key idea: Your ledger and the PSP will disagree sometimes. Daily reconciliation finds every difference and fixes it with new entries.

  9. 9. The design and its trade-offs

    The finished design: idempotency keys from checkout to PSP; a double-entry, append-only ledger as the source of truth; an outbox that publishes payment events at least once; a PSP router with health checks over two providers; and daily reconciliation against settlement reports. Payments are flowing again through both PSPs.

    Trade-offs to discuss: synchronous charge versus authorise-now-capture-later; a second PSP adds integration work, fees and reconciliation per provider; retries need limits and backoff so an outage is not amplified; strong consistency in the ledger costs write throughput, usually fine at payment volumes; and PCI DSS scope shrinks dramatically when card data goes straight to the PSP via tokenisation and never touches your servers.

    Scene: The complete payment system: checkout, payment service, ledger with outbox relay and broker, PSP router over PSP A and PSP B, settlement files and the reconciler. Payments succeed through both PSPs.

    Key idea: Idempotency stops duplicates, the ledger makes money traceable, the outbox makes events reliable, and reconciliation catches whatever slipped through.