The Problem#
A payment system moves money from a customer to a business, reliably, securely, and with a record that can be trusted years later. Think of Stripe, Adyen or PayPal: a business (the merchant) wants to accept card payments on its website without connecting to banks and card networks itself. The merchant sends the payment to the payment system, which talks to the financial networks, and reports back: succeeded, failed or pending.
On the surface, that is "call an API and get a yes or no". Underneath, it is one of the least forgiving problems in system design:
- Money must never be lost, duplicated or invented. A retry that charges a customer twice is a real-world harm, not just a bug.
- The outside world is slow, asynchronous and unreliable. Banks and card networks answer in hundreds of milliseconds to days. Some answers arrive late, some twice, and some never.
- Every movement must be auditable. Regulators, auditors and the merchants themselves need to reconstruct exactly what happened, and the books must balance to the cent.
- Card data is a prime target. Handling it brings strict security rules (PCI DSS), and a breach is existential.
- Scale is real: large processors handle thousands to tens of thousands of transactions per second at peak, such as Black Friday.
Analogy. Imagine a busy notary's office that handles property sales.
- A buyer and a seller come in. The notary opens a case file for the sale, numbered and unique. If the buyer's lawyer phones twice about "the sale of 12 Elm Street", the notary finds the same file instead of opening a second one. That is idempotency.
- The file moves through stamped stages: drafted, funds requested, funds received, completed, or cancelled. It can never jump backwards or skip a stage. That is the payment state machine.
- Money passes through the notary's escrow account. Every movement is written twice in the books, once as money out of one account and once as money into another, so the books always balance. That is the double-entry ledger.
- At the end of each day, a clerk compares the office's books line by line with the bank statement, and investigates any difference. That is reconciliation.
- When the sale completes, the notary posts a letter to each party, and resends it if the post office returns it. That is webhooks.
- The buyer's bank details are kept in a locked safe, and the clerks only ever handle reference numbers. That is tokenisation and PCI security.
Clarifying Questions#
| Question | Assumed answer |
|---|---|
| Are we the merchant, or the payment processor? | The processor: a Stripe-like platform serving many merchants. Merchants integrate through our API and client libraries. |
| Which payment methods? | Credit and debit cards first. Digital wallets (Apple Pay, Google Pay) arrive as card tokens. We also run a stored-value wallet: users hold a balance and pay or transfer from it. |
| Do we connect to card networks directly? | No. We go through acquiring banks or processors (and possibly several, for redundancy). We are a payment service provider (PSP). |
| What scale? | ~10,000 transactions per second (TPS) at peak, ~1,000 to 2,000 on average. Millions of merchants. |
| Which operations? | Create a payment, confirm it with a card, authorise, capture, cancel and refund. Merchants see status by API and webhooks. |
| Is consistency or availability more important? | Correctness of money movement comes first. We'd rather return "pending" or fail clearly than risk a double charge or a lost payment. |
| What about payouts, subscriptions and disputes? | Payouts to merchants and chargebacks are discussed briefly. Subscriptions and invoicing are out of scope. |
| Regulatory requirements? | PCI DSS compliance for card data, multi-year record retention, and auditable records of every change |
Requirements#
Functional#
- Merchants initiate payment requests: create a payment for an amount, currency and customer, and receive a payment id.
- Customers pay with credit or debit cards: card details are collected securely and the payment is authorised (and captured) through the card networks.
- Merchants see payment status: pending, succeeded, failed, refunded. They can query it via the API, and receive asynchronous webhook notifications.
- Refunds and captures: capture an authorised payment later, cancel (void) it, or refund a captured payment, fully or partially.
- Digital wallet: users can top up a balance, pay merchants from it, and transfer money to each other.
- Ledger and reconciliation: every money movement is recorded in a double-entry ledger, and reconciled daily with banks and processors.
Below the line: saved payment methods beyond basic tokens, subscriptions, invoicing, merchant onboarding (KYC), detailed reporting, alternative methods such as bank transfers (except as wallet top-ups), and full payout scheduling.
Non-Functional#
- Security: card data is protected end to end, PCI DSS scope is minimised, and every API call is authenticated.
- Durability and auditability: no transaction data is ever lost, even during failures. Every state change is traceable.
- Transaction safety (exactly-once effect): retries, timeouts and duplicate messages never cause a double charge, a lost payment or an unbalanced ledger, despite asynchronous external networks.
- Scalability: 10,000 TPS at peak, with headroom for growth.
- Availability: 99.99 percent or better for accepting payments. Every minute of downtime is lost revenue for every merchant.
- Latency: our own overhead well under 100 ms. End-to-end authorisation is typically 1 to 3 seconds, dominated by networks and issuers.
Capacity Estimation#
Transactions.
- Peak 10,000 TPS of payment confirmations. Average ~1,500 TPS, which is ~130 million payments per day, or ~47 billion per year. Those figures are illustrative for a large processor.
- Each payment produces several operations over its life: create, confirm, authorise, capture, possibly refund, plus webhooks. Call it ~5 API calls and ~10 internal state events per payment, so ~50,000 internal events per second at peak.
Ledger.
- Each money movement writes at least two ledger entries (a debit and a credit), and a typical payment involves several movements: authorisation hold, capture, fee and later payout. That is ~6 to 10 entries per payment, or ~100,000 entries per second at peak, and ~1 billion per day.
- At ~200 bytes per entry, that is ~200 GB per day, and ~70 TB per year before replication. Ledgers are append-only and kept for years (often 7 or more, depending on jurisdiction), so tiered storage matters.
Payment records. ~2 KB per payment, including metadata, attempts and state history. 130M per day × 2 KB ≈ 260 GB per day.
Webhooks. ~3 webhook events per payment, delivered to merchant endpoints, gives ~30,000 deliveries per second at peak. Retries for failing endpoints add more.
Latency budget for a card authorisation (typical):
| Step | Time |
|---|---|
| Client tokenisation call to our vault | 50 to 150 ms |
| Merchant server to our API | 20 to 80 ms |
| Our processing: idempotency, risk, routing, DB writes | 20 to 60 ms |
| Acquirer, card network, issuer and back | 300 ms to 2 s |
| 3-D Secure challenge, if triggered | 5 to 60 s of user time |
The external network dominates. Our job is to add little latency, and to stay correct when the external part is slow or silent.
Core Entities#
- Merchant: a business account, with API keys, webhook endpoints, settlement bank account and fee plan.
- Customer: the payer, optionally saved by the merchant.
- PaymentIntent (Payment): the merchant's intention to collect an amount in a currency. It has a lifecycle (the payment state machine) and may involve several attempts.
- PaymentAttempt (Charge): one attempt to move money with a specific payment method through a specific processor. A payment can have several, for example a declined card followed by a successful one.
- PaymentMethod: a token representing a card (or wallet) stored in the vault. Our services never see the raw card number.
- Refund: money returned against a captured payment.
- LedgerAccount and LedgerEntry: the double-entry books. Accounts include customer funds, merchant balances, fees, processor receivables and bank cash. Entries are grouped into balanced journal transactions.
- Wallet: a user's stored-value balance, which is itself a ledger account.
- WebhookEvent and WebhookDelivery: a record of what happened (the event), and of each attempt to tell the merchant (the deliveries).
- IdempotencyRecord: a stored key, request fingerprint and response, so a retried request returns the original result.
API Design#
POST /v1/payment_intents # merchant server; Idempotency-Key header required
{ amount: 4999, currency: "usd", customer?, captureMethod: "automatic|manual", metadata }
-> { id: "pi_123", status: "requires_payment_method", clientSecret }
POST /v1/payment_intents/{id}/confirm # from the client SDK, or the merchant server
{ paymentMethod: "pm_tok_abc" } # token from the vault, never a raw card number
-> { id, status: "processing|requires_action|succeeded|failed", nextAction? }
POST /v1/payment_intents/{id}/capture { amountToCapture? } # for manual capture
POST /v1/payment_intents/{id}/cancel # void an authorisation
POST /v1/refunds { paymentIntent, amount? } # Idempotency-Key required
GET /v1/payment_intents/{id} # current status
POST /v1/tokens (to the vault domain) { cardNumber, expMonth, expYear, cvc }
-> { paymentMethod: "pm_tok_abc" }
POST /v1/wallets/{walletId}/transfers { toWallet, amount, currency } # Idempotency-Key
GET /v1/wallets/{walletId} -> { available, pending, currency }
Webhook to the merchant: POST https://merchant.example/webhooks
headers: Signature: t=..., v1=HMAC-SHA256(secret, t + "." + body)
body: { id: "evt_789", type: "payment_intent.succeeded", data: { ...payment } }
Design points:
- Amounts are integers in the smallest currency unit (cents), with an ISO currency code. Floating point never touches money.
- Every mutating call takes an
Idempotency-Key. The same key with the same body returns the original response. The same key with a different body is an error (Deep Dive 4). - The card number goes only to the vault endpoint, usually directly from the customer's browser through our hosted fields or SDK. The merchant's servers, and most of ours, only see tokens (Deep Dive 1).
- Asynchronous outcomes are first-class.
processingandrequires_action(for example a 3-D Secure challenge) are normal statuses. The merchant learns the final result by webhook or by polling.
High-Level Design#
1) Merchants can initiate payment requests#
The merchant's server calls POST /v1/payment_intents with an amount, a currency and an Idempotency-Key.
- The API gateway authenticates the merchant's secret API key, applies rate limits per merchant, and forwards the request (see API Gateway and Backend-for-Frontend).
- The Payment Service checks the idempotency store. If this key was already used, it returns the stored response. Otherwise it records the key as "in progress".
- It creates a
payment_intentrow with statusrequires_payment_method, writes the stored response for the idempotency key, and appends apayment_intent.createdevent to the outbox, all in one database transaction. - It returns the payment id and a client secret. The merchant passes the secret to its web page, so the customer's browser can confirm this specific payment without the merchant's secret key.
Nothing has touched a bank yet. Creating an intent is cheap, local and fully under our control.
2) Customers can pay with credit or debit cards#
Collect the card without touching it.
- The merchant's checkout page embeds our client SDK or hosted fields (iframes served from our domain). The customer types the card number into our iframe, which sends it straight to the Card Vault.
- The vault stores the card encrypted, and returns a token (
pm_tok_abc). The merchant's page and servers, and most of our own services, only ever see the token. That keeps them out of most of PCI DSS's scope (Deep Dive 1).
Confirm and authorise.
- The client (or the merchant's server) calls confirm with the token.
- The Payment Service moves the payment to
processing, creates a PaymentAttempt row, and calls Risk (fraud scoring) and Routing (which processor or acquirer to use, based on card brand, region, cost and health). - A Processor Adapter (one per acquirer or processor) asks the vault to detokenise the card inside the vault's secure zone, and sends the authorisation request through the acquirer to the card network (Visa, Mastercard and others) and on to the issuing bank.
- The issuer approves or declines, usually within 1 to 2 seconds. The response travels back: authorised (with an authorisation code), declined (with a reason code), or unknown, if it timed out.
- The Payment Service records the outcome on the attempt, transitions the payment (
succeeded, orrequires_capturefor manual capture, orfailed), and writes ledger entries plus an outbox event, in one transaction. - If the issuer demands 3-D Secure (an extra authentication step, such as a bank app confirmation), the status becomes
requires_action. The client SDK shows the challenge, and confirmation resumes afterwards.
Authorise versus capture. An authorisation asks the issuer to reserve funds on the card. A capture tells the networks to actually move them. Card-present and many online sales capture immediately ("automatic"). Merchants who ship later, such as hotels, rentals and marketplaces, authorise first and capture later ("manual"). Authorisations expire after a validity window set by the card network rules, which depends on the network, the merchant category and the transaction type. For typical online purchases it is a matter of days. Always check the current rules, because the networks revise them. Clearing and settlement (the networks exchanging transaction files, and banks moving funds) happen later in batches, typically within one or two business days. See the payment-network problem for the card rails in depth.
3) Merchants receive status updates#
Payments are asynchronous: some finish in a second, some wait on a 3-D Secure challenge, and some are resolved only later (a delayed issuer response, a bank transfer, a dispute). Merchants need to know reliably.
- Polling:
GET /v1/payment_intents/{id}always returns the current state from the payments database. It is simple, but merchants polling millions of payments is wasteful. - Webhooks (push): every state change writes an event to the outbox, in the same transaction as the change. A relay publishes it to Kafka. A Webhook Dispatcher delivers it to each merchant's registered endpoints with an HMAC signature, retrying with backoff for up to days, until the merchant's endpoint answers 2xx (Deep Dive 9).
- Client-side: the client SDK returns the immediate outcome to the checkout page, so the customer sees "Payment successful". The merchant's backend still relies on the webhook, or a server-side fetch, as the source of truth, because the browser can close at any moment.
4) Users can hold and transfer money in a digital wallet#
A wallet is a ledger account per user. Its balance is the sum of its ledger entries.
- Top-up: a card payment (as above) whose captured funds are credited to the user's wallet account rather than to a merchant.
- Pay or transfer from the wallet: a purely internal ledger transaction: debit the payer's wallet and credit the payee's wallet (or a merchant's balance). No external network is involved, so it can be atomic and immediate, as long as both accounts are in one ledger database, or a cross-shard protocol is used (Deep Dive 11).
- Withdraw: an internal debit, plus an external payout to the user's bank account via a bank transfer rail. The external part is asynchronous, so the withdrawal is pending until the bank confirms.
The key rule: the balance must never go negative (unless credit is allowed), and every transfer either fully happens or doesn't happen at all.
The full high-level design#
Components:
- API gateway: terminates TLS, authenticates merchants by API key (and optionally mutual TLS), enforces rate limits, and routes card-data calls to the vault and everything else to core services.
- Card Vault (PCI zone): receives raw card numbers, encrypts them with keys protected by hardware security modules (HSMs), and issues tokens. It is the only place where card numbers exist in usable form. It is isolated in its own network segment, with minimal code and access.
- Processor adapters (PCI zone): one per acquirer or processor. They translate our internal authorisation request into the processor's protocol (an ISO 8583 message or a REST API), detokenising the card in memory only for that call.
- Payment Service: owns payment intents and attempts. It runs the state machine, enforces idempotency, and orchestrates risk, routing, adapters and the ledger.
- Risk and fraud: scores each payment in tens of milliseconds, using rules and models over device, card, merchant and velocity signals, and can block a payment, require 3-D Secure, or allow it.
- Router: chooses an acquirer per payment, by cost, approval rate, region and health. It fails over to another acquirer when one degrades.
- Ledger Service: records every money movement as balanced double-entry journal transactions. It is append-only and immutable (Deep Dive 5).
- Wallet Service: user balances, top-ups, transfers and withdrawals, all built on the ledger.
- Payments and ledger databases: strongly consistent relational stores (or a distributed SQL store), sharded by merchant or payment id, with synchronous replication (Deep Dive 10).
- Kafka: the event backbone, fed exclusively by transactional outboxes, so an event exists if, and only if, the state change committed.
- Webhook Dispatcher: signs and delivers events to merchants, with retries, backoff and per-endpoint isolation.
- Reconciliation jobs: compare our ledger with processor reports and bank statements daily, and raise breaks for investigation (Deep Dive 7).
Key Flows#
Flow 1: a card payment, end to end#
- The browser tokenises the card in our hosted fields. The token is scoped to this merchant.
- Confirm arrives with the token. The Payment Service claims the idempotency key for this confirm request, writes an attempt in
PROCESSING, and commits before calling out. If we crash during the external call, the record of the attempt survives. - Risk approves. The router picks an acquirer. The adapter detokenises the card inside the PCI zone and sends the authorisation, with the attempt id as its unique reference (used later to query, reverse or reconcile).
- The issuer approves. The Payment Service writes the outcome, the ledger journal (for example, debit "processor receivable" and credit "merchant pending balance") and an outbox event, in one transaction.
- The client gets "succeeded". The merchant's backend gets the
payment_intent.succeededwebhook seconds later.
Flow 2: the authorisation times out#
The most important flow is the one where we don't know what happened.
- Never treat a timeout as a failure. The issuer may have approved, in which case the customer's funds are reserved. Retrying blindly with a new reference could create a second authorisation.
- The attempt goes to UNKNOWN. The merchant sees
processing. A recovery worker queries the acquirer by our reference, or retries with the same reference if the processor guarantees idempotency on it, until the outcome is known. - If the acquirer cannot say (it has no record of the request), the safest action depends on the rails. Usually we send a reversal for that reference, so any hidden authorisation is released, and then mark the attempt failed. The customer can retry, creating a new attempt.
- Settlement files the next day are the final word: reconciliation catches any remaining mismatch (Deep Dive 7).
Flow 3: a wallet-to-wallet transfer#
- Alice sends Bob $20 with an Idempotency-Key. The Wallet Service validates the request (same currency, Alice's account is active, limits respected).
- In one ledger transaction: lock Alice's balance row, check
available ≥ 20, insert a journal with two entries (debit Alice's wallet $20, credit Bob's wallet $20), and update both cached balances. - Commit. Both balances change together or not at all. The outbox emits
transfer.completed. Both users are notified. - If Alice's and Bob's accounts live on different shards, a single local transaction is impossible. Deep Dive 11 covers the options: a saga with a holding account, or a distributed transaction.
Data Model#
CREATE TABLE payment_intents (
id TEXT PRIMARY KEY, -- pi_... , random, unguessable
merchant_id BIGINT NOT NULL,
amount BIGINT NOT NULL CHECK (amount > 0), -- minor units (cents)
currency CHAR(3) NOT NULL,
status TEXT NOT NULL, -- see the state machine
capture_method TEXT NOT NULL,
amount_captured BIGINT NOT NULL DEFAULT 0,
amount_refunded BIGINT NOT NULL DEFAULT 0,
version BIGINT NOT NULL DEFAULT 0, -- optimistic concurrency on transitions
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
CHECK (amount_refunded <= amount_captured AND amount_captured <= amount)
);
CREATE TABLE idempotency_keys (
merchant_id BIGINT NOT NULL,
key TEXT NOT NULL,
request_hash BYTEA NOT NULL, -- fingerprint of method, path and body
status TEXT NOT NULL, -- IN_PROGRESS | COMPLETED
response JSONB, -- stored response to replay
locked_until TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (merchant_id, key)
);
CREATE TABLE ledger_entries ( -- append-only: no UPDATE, no DELETE
id BIGINT PRIMARY KEY,
txn_id BIGINT NOT NULL,
account_id BIGINT NOT NULL,
direction TEXT NOT NULL CHECK (direction IN ('DEBIT','CREDIT')),
amount BIGINT NOT NULL CHECK (amount > 0),
currency CHAR(3) NOT NULL,
posted_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX ledger_by_account ON ledger_entries (account_id, posted_at);Design notes.
- Payment ids are random and unguessable (for example 24+ random characters with a type prefix). They appear in URLs and client code, so sequential ids would leak volume and invite enumeration.
- The CHECK constraints encode business invariants. You cannot refund more than was captured, or capture more than was authorised. The database rejects a buggy update even if the application misses it.
versionguards state transitions:UPDATE ... SET status = 'SUCCEEDED', version = version + 1 WHERE id = ? AND status = 'PROCESSING' AND version = ?. A late or duplicate event finds the guard false, and changes nothing.- The ledger is append-only. Corrections are new, reversing entries, never edits. Grant the application role
INSERTandSELECTonly on ledger tables, so even a bug cannot rewrite history. - Balanced journals: a trigger, or the Ledger Service, checks that each
txn_id's debits equal its credits, per currency, before commit (Deep Dive 5). - Card data is absent. These tables hold tokens and processor references only. Card numbers live solely in the vault's separate, encrypted store.
Database choice. Money movement needs ACID transactions, constraints and strong consistency, so a relational database is the default: PostgreSQL or MySQL, sharded by merchant or payment id. A distributed SQL store (such as CockroachDB, Spanner or YugabyteDB) is an option when cross-shard transactions are frequent. Some companies build dedicated ledger databases. Eventually consistent stores are a poor fit for balances (see Choosing a Database: A Decision Guide and Relational Databases and SQL).
| Data | Store | Why |
|---|---|---|
| Payment intents, attempts, refunds, idempotency keys | Sharded PostgreSQL or MySQL, sync replicas | ACID transitions, constraints, transactional outbox |
| Ledger entries and balances | Ledger DB, relational or distributed SQL | Atomic balanced journals, append-only, auditable |
| Card data | Vault: encrypted store in the PCI zone, HSM-managed keys | Isolation, minimal scope, strict access |
| Events | Kafka, fed by outboxes | Fan-out to webhooks, ledger projections, analytics |
| Webhook delivery state | Partitioned queue plus a delivery table | Per-endpoint retries and backoff |
| Settlement files, reports, audit archive | Object storage (immutable, WORM-style retention) | Cheap long-term retention, regulatory evidence |
| Analytics and reconciliation workspace | Data warehouse | Large joins across our records and external files |
Deep Dives#
1. How do we make the system highly secure?#
A payment system is attacked from every side: stolen card numbers, stolen API keys, forged webhooks, insiders and fraudsters. Security is layered.
Card data and PCI DSS. The Payment Card Industry Data Security Standard (PCI DSS) is the card industry's security standard for anyone who stores, processes or transmits cardholder data. Its requirements cover network segmentation, encryption, access control, logging, vulnerability management and regular audits. The single most effective strategy is to shrink the scope: the fewer systems that touch card numbers, the fewer systems the strictest controls apply to.
- Hosted fields and client-side tokenisation: the card number goes from the customer's browser straight to our vault, in an iframe served from our domain. The merchant's page never sees it, so merchants qualify for a much lighter compliance burden (a simpler self-assessment).
- The vault is the cardholder data environment (CDE). A small, separate network segment holding the encrypted card store, the tokenisation service and the processor adapters. It has minimal code, minimal people with access, and heavy monitoring.
- Tokens everywhere else. Payment, risk and ledger services handle tokens (
pm_tok_abc), which are worthless to a thief outside our system.
Encryption and keys.
- In transit: TLS 1.2 or higher on every hop, including internal ones. Mutual TLS between services in the PCI zone.
- At rest: card numbers are encrypted with data encryption keys (DEKs), which are themselves encrypted with key encryption keys (KEKs) held in HSMs: tamper-resistant hardware that performs cryptographic operations without exposing keys. This is envelope encryption, and it lets keys be rotated without re-encrypting everything at once.
- Network tokens: card networks also issue their own tokens (network tokenisation), which replace the card number with a network-issued token bound to the merchant or device. Wallets such as Apple Pay and Google Pay use this (Deep Dive 12).
- Never store the CVC after authorisation. PCI DSS forbids storing sensitive authentication data after authorisation.
Authenticating merchants and requests.
- Secret API keys for server-to-server calls, scoped (test or live, restricted permissions), rotatable, and stored hashed on our side. Publishable keys for client-side calls, which can only tokenise cards and confirm intents via the client secret.
- Client secrets bind a browser to one payment intent, so a customer can confirm their payment without holding the merchant's secret key.
- Optional IP allowlists and mutual TLS for large merchants.
Authenticating customers: 3-D Secure. 3-D Secure (3DS) adds an issuer-run authentication step: a bank app approval, a one-time code or biometrics. In Europe, Strong Customer Authentication under the PSD2 regulation requires such authentication for many online payments, with exemptions (low value, low risk, merchant-initiated). Our risk engine decides when to request 3DS. A successful 3DS authentication generally shifts fraud liability from the merchant to the issuer.
Webhook authenticity. Each webhook is signed with an HMAC of the timestamp and the body, using a per-endpoint secret. Merchants verify the signature and reject timestamps older than a few minutes, which prevents forged and replayed webhooks.
Fraud. Risk scoring on every payment: rules (velocity of attempts per card, country mismatches, known bad devices) plus machine-learning models trained on historical fraud and chargebacks. Actions are allow, require 3DS, review or block. Card testing (bots trying thousands of stolen card numbers with small amounts) is detected by velocity and decline-rate patterns per merchant, IP and device, and stopped with rate limits and challenges.
Insiders and operations. Least-privilege access, just-in-time access grants with approval, every access to the PCI zone logged and reviewed, separation of duties (no single engineer can both change code and deploy to production in the CDE), and regular penetration tests (see Security Fundamentals for System Design and Authentication and Authorization).
2. How do we guarantee durability and auditability, so that no transaction data is ever lost?#
What "never lost" means. Once we tell anyone (customer, merchant or bank) that something happened, the record must survive any single failure: disk, machine, zone, or a buggy deploy. And we must be able to show, years later, exactly how every cent moved.
Durable commits.
- Synchronous replication of the payments and ledger databases to at least one replica in another availability zone, before acknowledging a commit. A primary failure loses nothing that was acknowledged (see Database Replication).
- Write before you call out. Record the attempt (
PROCESSING, with our reference) before sending anything to an acquirer. If we crash mid-call, the record tells recovery what to look for. A payment that reached a bank but has no row in our database is the worst possible failure. "Write first" prevents it. - Kafka for events, with replication factor 3,
acks=allandmin.insync.replicas=2, so an acknowledged event survives a broker loss (see Apache Kafka in Practice). - Backups and point-in-time recovery, tested regularly by restoring, plus cross-region copies for disaster recovery (see Disaster Recovery and Backups).
Auditability: history, not just current state.
- State transitions are recorded, not overwritten. Each change to a payment is also appended to a
payment_eventstable (or an event-sourced log) with the before and after states, the cause (API call, processor response, webhook) and the actor. Thepayment_intentsrow is the current-state projection. The event history is the audit trail (see Event Sourcing and CQRS). - The ledger is immutable. Mistakes are corrected by reversing entries, so the books show both the error and its correction.
- Raw external messages are archived. Every request to and response from a processor (with card data masked) and every settlement file goes to immutable object storage, with retention locks (write once, read many). They are the evidence in disputes and audits.
- Tamper evidence. For extra assurance, chain ledger batches with cryptographic hashes (each batch includes the hash of the previous one), so silent modification of history is detectable. Some institutions also publish periodic digests to a separate system.
Change data capture from the payments and ledger databases feeds the warehouse and the audit store, so analytics never query the production primaries (see Change Data Capture and the Outbox Pattern).
3. How do we keep transactions safe when external networks are asynchronous?#
Inside our databases, we have transactions. Outside, we have messages to other companies' systems that can be slow, lost, duplicated or delayed by days. No distributed transaction spans our database and a bank's mainframe. Safety comes from four techniques used together.
1. Explicit intermediate states. Model the uncertainty in the data. An attempt is PROCESSING from the moment we send a request, and UNKNOWN when a call times out. It becomes AUTHORISED or DECLINED only on evidence. The merchant sees processing, which is honest, rather than a guess.
2. Unique references end to end. Every external request carries our unique id (the attempt id), so we can later ask "what happened to att_9?", send a reversal for exactly that request, and match it in settlement files. Many processors also support idempotency keys on their APIs. Pass ours through, and a retry of the same request is a no-op on their side.
3. Resolution workers. Anything in UNKNOWN (or stuck in PROCESSING past a deadline) is picked up by a recovery worker that:
- queries the processor's status endpoint with our reference;
- if the processor has the request and an outcome, applies it through the normal state machine transition;
- if the processor has no record, retries with the same reference where that is safe, or sends a reversal (void) for the reference to release any hidden authorisation, and then fails the attempt;
- escalates to a manual queue after N attempts. Humans resolve the rare residue.
4. Reconciliation as the final net. The next day's settlement files list what the networks actually processed. Reconciliation compares them with our ledger and catches anything the first three steps missed (Deep Dive 7).
Ordering and races with asynchronous results. The processor might send a webhook ("authorisation approved") at the same moment our recovery worker learns the same outcome by polling, or a late "declined" might arrive after we had already applied "approved". The state machine resolves all of these: each transition is a guarded update (WHERE status IN (allowed prior states) AND version = ?), so the first valid transition wins, and duplicates or impossible transitions are ignored and logged (Deep Dive 6).
Compensation for multi-step flows. A marketplace payment might authorise the card, debit the customer, credit a seller and take a fee. If a later step fails, earlier steps are compensated (void the authorisation, reverse the entries) rather than rolled back. That is a saga (see Distributed Transactions: 2PC, Sagas and Outbox and Pattern: Multi-Step Processes and Workflows). Workflow engines such as Temporal fit this well. Durable timers and retries are built in, and each step's result is persisted (see Temporal and Workflow Engines).
4. How does idempotency work in practice?#
The problem. A merchant's server calls "create refund". The network times out. Did the refund happen? The merchant's only safe move is to retry, and the system must guarantee that a retry has no additional effect. The same applies to every mutating call: create payment, confirm, capture and transfer (see Idempotency and Safe Retries).
The mechanism: idempotency keys.
- The client generates a unique key (a UUID) per logical operation, and sends it in
Idempotency-Key. Retries of that operation reuse the key. - On receipt, the server atomically claims the key:
INSERT INTO idempotency_keys (merchant_id, key, request_hash, status) VALUES (...). The primary key makes the insert fail if the key exists. - Key is new: process the request. Store the final response (status code and body) with the key, marked COMPLETED, ideally in the same transaction as the business change.
- Key exists and is COMPLETED: compare the request fingerprint. If it matches, return the stored response unchanged. If it differs, return an error ("key reused with different parameters"). That catches client bugs.
- Key exists and is IN_PROGRESS: another request with this key is running right now (a concurrent retry). Return 409 "in progress, retry later", rather than running it twice. A
locked_untillease lets a crashed request's key be recovered after a timeout.
Atomic phases. If a request includes an external call (authorise with the acquirer), it cannot be in one database transaction. Split it into atomic phases, each committed with a recovery point recorded on the idempotency record: "started", "attempt created", "processor called", "finished". A retry after a crash resumes from the last recovery point instead of starting over. The external call itself is protected by passing the attempt id as the processor's own idempotency key. Brandur Leach, then an engineer at Stripe, described this "atomic phases and recovery points" design in a widely read 2017 article on implementing Stripe-like idempotency keys in PostgreSQL. Stripe's public API accepts an Idempotency-Key header on mutating requests.
Retention. Keep keys long enough to cover any realistic retry window. 24 hours is a common choice for API keys. Business-level uniqueness (for example, one payout per invoice id) is enforced permanently with unique constraints, not by expiring keys.
Idempotency is needed at every hop:
- client → our API: Idempotency-Key;
- our services → each other: request ids carried through, deduplicated at the receiver;
- us → processors: attempt id as the reference or idempotency key;
- Kafka consumers: deduplicated by event id, or made naturally idempotent with guarded state transitions;
- webhooks → merchants: event ids, so merchants can deduplicate.
Airbnb described a similar end-to-end discipline, built around an idempotency library for its payments services, in a 2019 engineering post on avoiding double payments.
5. Why a double-entry ledger, and how does it work?#
The idea. Double-entry bookkeeping has been used by accountants for more than five centuries (Luca Pacioli described it in print in 1494). Every movement of money is recorded as at least two entries: a debit to one account and a credit to another, of equal total. Money is never created or destroyed by a transaction. It only moves between accounts. So the sum of all debits always equals the sum of all credits, and any discrepancy reveals a bug instantly.
Why not just a balance column? UPDATE accounts SET balance = balance - 20 records the result and forgets the cause. You cannot answer "why is this balance $480?". You cannot prove that money was not created by a bug, and you cannot rebuild a balance after corruption. A ledger answers all three: the balance is derived from the entries, and every entry points to the business event that caused it.
Accounts in a payment processor (illustrative chart of accounts):
processor_receivable:acquirer_X: money the acquirer owes us for captured payments, not yet settled;merchant_balance:M(pending and available): what we owe merchant M;fees_revenue: our fees;bank_cash:operating: money actually in our bank account;customer_wallet:U: stored-value balances;refunds_payable,chargebacks,fx_clearingand so on.
Worked example. A customer pays merchant M $100.00. Our fee is 2.9 percent + $0.30 = $3.20.
| Event | Debit | Credit | Amount |
|---|---|---|---|
| Capture succeeds | processor_receivable:acq_X | merchant_balance_pending:M | $100.00 |
| Fee taken | merchant_balance_pending:M | fees_revenue | $3.20 |
| Acquirer settles to our bank (T+1) | bank_cash:operating | processor_receivable:acq_X | $100.00 (less interchange, simplified here) |
| Funds become available to M | merchant_balance_pending:M | merchant_balance_available:M | $96.80 |
| Payout to M's bank | merchant_balance_available:M | bank_cash:operating | $96.80 |
After all five, processor_receivable is back to 0 (settled), the merchant has received $96.80, we hold $3.20 of revenue, and every journal balanced. A refund of $100 later is new entries, never edits. Whether the fee is returned is a policy choice, and it is recorded explicitly either way.
Debit and credit conventions. In accounting, debits increase asset and expense accounts, and credits increase liability, equity and revenue accounts. Engineers often find this confusing. A common implementation simplification is to store signed amounts with the rule "entries in a journal sum to zero", and to apply the accounting labels only in reports. Either way, the invariant is the same: every journal balances.
Implementation rules:
- Append-only, immutable entries. No updates or deletes, enforced by database permissions. Corrections are reversing journals.
- Atomic journals. All entries of a journal commit in one transaction, together with the business state change that caused them (the payment row's transition). That is why the ledger often lives in the same database as payments, or why the payment state change and the ledger posting share an outbox-driven exactly-once pipeline.
- Balanced check before commit. Per journal and per currency: Σ debits = Σ credits. Reject anything else.
- Balances as projections. Computing a balance by summing millions of entries is slow. Maintain a
balancesrow per account, updated in the same transaction as each entry, and verify it periodically against the sum of entries. For a balance check before a debit (wallets), lock that balance row (SELECT ... FOR UPDATE) or use a guarded update (WHERE available >= amount). - Multi-currency: never mix currencies in one account. Currency conversion is two journals through an FX clearing account, at a recorded rate.
- Time: record both posted_at (when we wrote it) and effective_at (the business time it applies to, such as the settlement date), so reports can be reproduced "as of" any date.
Hot accounts. Some accounts are touched by almost every payment: fees_revenue, or a big merchant's balance. If every journal locks the same balance row, that row becomes a contention hot spot, the same problem as in the flash-sale case. Fixes:
- split the hot account into N sub-accounts (
fees_revenue:shard_17), and sum them for reporting; - batch postings to it (aggregate fees every second into one journal);
- don't maintain a running balance for accounts that never need a pre-debit balance check (revenue accounts only grow).
Purpose-built ledger databases exist for this workload. TigerBeetle, for example, is an open-source financial transactions database designed around double-entry transfers with very high throughput. Large payment companies have also described building their own ledger services.
6. What does the payment state machine look like?#
A payment's lifecycle is a finite state machine: a fixed set of states, and allowed transitions between them. Encoding it explicitly is the single best defence against the class of bugs where "a late message moved the payment somewhere impossible".
Rules:
- Every transition is a guarded update:
UPDATE payment_intents SET status = :to, version = version + 1 WHERE id = :id AND status = ANY(:allowedFrom) AND version = :v. Zero rows updated means the transition is invalid or stale. The caller re-reads and decides. - Transitions have side effects that commit atomically: the ledger journal, the outbox event and the audit record are all written in the same transaction as the status change.
- Attempts have their own machine: CREATED → SENT → AUTHORISED, DECLINED or UNKNOWN; and AUTHORISED → CAPTURED or VOIDED. A payment is
REQUIRES_PMagain after a decline, so the customer can try another card. Each try is a new attempt, so history is kept. - Terminal states are final. A capture message for a CANCELED payment is rejected and alerted on, never applied.
- Timeouts are transitions too: REQUIRES_CAPTURE moves to CANCELED when the authorisation is about to expire, by a scheduled job, with a void sent to the acquirer.
Keep the machine in one place (a table of allowed transitions, used by all code paths). Scattered if status == ... checks drift apart, and that drift is where double captures come from.
7. How does reconciliation prove that the books are right?#
The problem. Our ledger says what we believe happened. The acquirer's settlement file says what they believe happened. Our bank statement says what actually arrived. These three disagree more often than beginners expect: timeouts that succeeded on the far side, fees that differ from the contract, refunds processed twice, currency rounding, settlements that land a day late, and chargebacks that appear only in the processor's report. Reconciliation is the daily process that matches these views and flags every difference, called a break.
Analogy. Reconciliation is checking your bank statement against your receipts at the end of the month. Most lines match. The interesting ones are the receipt with no statement line (did the payment go through?) and the statement line with no receipt (who charged me?).
The three-way match:
- Internal ↔ processor. Every captured attempt in our database should appear in the acquirer's settlement file (usually delivered daily, often by SFTP, as CSV or a fixed-width format), with the same amount, currency and reference. Match on the unique reference we sent (the attempt id), never on amount and time alone.
- Processor ↔ bank. The net amount the settlement file says will be paid (gross captures minus refunds, chargebacks, interchange and scheme fees) should equal the deposit that arrives in our bank account, usually reported in a bank statement file (formats such as BAI2 in the US, or ISO 20022 camt.053 elsewhere).
- Internal ledger ↔ both.
processor_receivable:acq_Xshould fall to zero for every settled day. A non-zero residue is unexplained money.
Types of breaks and what to do:
- In theirs, not in ours (or ours says FAILED or UNKNOWN): usually a timeout that succeeded. Advance the attempt to CAPTURED, post the ledger journal and notify the merchant, or refund it if the order was abandoned. This is the safety net behind Deep Dive 3.
- In ours, not in theirs: the capture never reached them, or appears in tomorrow's file (cut-off timing). Wait one cycle, then investigate.
- Amount mismatch: often FX conversion, partial capture or fee differences. Fee mismatches against the contract are worth money: a processor charging the wrong rate is found only here.
- Duplicates: two captures for one order. Refund one, and find the idempotency gap that allowed it.
Engineering notes. Treat settlement files as an untrusted input: validate schemas, store the raw file immutably, and make the job idempotent per file (re-running a file must not double-count). Matching is a join on large tables: millions of rows a day per processor. A batch engine (Spark, or SQL on a warehouse) is a good fit. Break aging is the key metric: a break older than a few days usually means real money is lost or owed. Reconciliation runs T+1 (the day after) for most card flows, but a near-real-time variant that compares live webhooks from processors to our state catches problems hours earlier.
8. How do retries give an exactly-once effect?#
Networks deliver messages at least once in practice: a sender that did not see an acknowledgement must retry, and the receiver may then see the message twice. "Exactly-once delivery" across a network is not achievable in general, but an exactly-once effect is: at-least-once delivery + idempotent processing.
Where retries happen in this system:
- client → our API (protected by Idempotency-Key, Deep Dive 4);
- our service → acquirer (protected by the attempt id as the processor's idempotency key, and by status queries before retrying);
- outbox → Kafka (the relay may publish twice after a crash; consumers deduplicate by event id);
- Kafka → consumers (a consumer that crashes after processing but before committing its offset sees the message again);
- us → merchant webhooks (merchants must deduplicate by event id).
Retry policy:
- Exponential backoff with jitter. Wait base × 2^attempt, randomised: for example 1 s, 2 s, 4 s, up to a cap, each multiplied by a random factor between 0.5 and 1.5. Without jitter, thousands of clients that failed together retry together and knock the recovering service down again (a thundering herd).
- Retry only retryable errors. Timeouts, 5xx responses and connection resets are retryable. A decline ("insufficient funds") or a validation error is not, and retrying it may trip issuer fraud rules.
- Retry budgets and circuit breakers. Limit retries to a share of traffic (for example 10 percent extra load). When an acquirer's error rate spikes, open the circuit and route new payments to a backup acquirer, if the merchant has one.
- Dead-letter queue (DLQ). After N failed tries, park the message with its error for investigation and manual replay. Never drop payment messages silently.
Idempotent consumers. Each consumer records the event ids it has applied, in the same transaction as the effect:
BEGIN;
INSERT INTO processed_events (consumer, event_id) VALUES ('ledger', :eid)
ON CONFLICT DO NOTHING; -- 0 rows inserted means a duplicate: stop
-- only if 1 row was inserted:
INSERT INTO ledger_entries (...) VALUES (...);
COMMIT;Where an effect is naturally idempotent (setting a status to SUCCEEDED with a guarded update), the dedup table is unnecessary. The combination of the transactional outbox on the producer side and idempotent consumers on the receiving side is the standard way to get an exactly-once effect end to end without distributed transactions. Kafka's own exactly-once semantics (idempotent producers and transactions) help only within Kafka; once a side effect leaves Kafka, it needs its own idempotency.
9. How do webhooks work reliably?#
Merchants need to know when a payment succeeds, especially for asynchronous outcomes: 3DS challenges, bank transfers that clear days later, disputes. We push events to an HTTPS endpoint the merchant registers. This is the bonus deep dive the problem statement expects, and it is a small distributed system of its own.
Delivery pipeline: outbox → Kafka payment-events → webhook dispatcher → per-endpoint delivery queue → HTTP POST to the merchant.
Rules for robust webhooks:
- Sign every request. Compute HMAC-SHA256 over a timestamp plus the raw body, using a per-endpoint secret, and send it in a header. The merchant recomputes and compares in constant time, and rejects timestamps older than a few minutes to stop replay. Stripe's
Stripe-Signatureheader works on this principle. - At-least-once, with long retries. Retry with exponential backoff for up to about three days (Stripe documents retrying for up to three days in live mode). Mark the endpoint as failing, and email the merchant, after repeated failures.
- Event ids for deduplication. Every event has a unique
evt_id. Merchants should store processed ids and ignore repeats. - No ordering guarantee. Retries and parallelism mean
payment.succeededcan arrive beforepayment.processing. Tell merchants to treat webhooks as hints, and to either compare a version or timestamp, or fetch the latest object from the API before acting. Thin events ("something changed, here is the id") make this the default. - Per-endpoint isolation. One merchant's slow or dead endpoint must not delay everyone else. Give each endpoint its own queue or rate budget, use short timeouts (around 10–30 seconds), and cap concurrency per endpoint. This is the noisy-neighbour problem again.
- Respond fast. Merchants should return 2xx immediately and process asynchronously. Our dispatcher counts only 2xx as success.
- Replay and inspection. Keep a delivery log (attempts, status codes, latency), and let merchants see failures and re-send events from a dashboard, or list missed events through an
eventsAPI. This turns "we lost a webhook" into "fetch everything since event X". - Security for us too: resolve the merchant's URL and block private and internal IP ranges, or the dispatcher can be used for server-side request forgery (SSRF) against our own network.
For more on the push mechanics, see Polling, Long Polling, SSE, WebSockets and Webhooks.
10. How do we scale to 10,000 payments per second?#
10k TPS sounds large, but it is a modest number for each component if the design partitions cleanly. The traps are hidden global contention points: one ledger account, one sequence, one lock.
Servers. The payment API and orchestrator are stateless. At roughly 1,000–2,000 requests per second per instance for this kind of I/O-bound work, about 10–20 instances handle peak, and we run 2–3 times that across availability zones for headroom and failover. The real limit is not CPU but the acquirer's latency (200 ms–2 s per authorisation). At 10k TPS × 1 s average, about 10,000 authorisation calls are in flight at once, so the services must use non-blocking I/O or large connection pools, and acquirer connection limits must be negotiated in advance.
Kafka. Each payment produces roughly 3–6 events. At peak that is 30k–60k messages per second of about 1 KB: tens of MB/s, comfortable for a small cluster. Partition by payment id (or merchant id where per-merchant order matters), so all events for a payment stay in order on one partition. Use acks=all and min.insync.replicas=2 with replication factor 3, so an acknowledged event survives a broker loss. Plan for 50–100 partitions, so consumer groups can scale out. More detail is in Apache Kafka in Practice.
Database. At peak, each payment needs several writes: intent, attempt, transitions, idempotency record, outbox row and 6–10 ledger entries. That is roughly 100k–150k row writes per second, which is too much for one primary. Options:
- Shard by merchant id. All of a merchant's intents, attempts and ledger accounts are on one shard, so most transactions stay single-shard. The risk is that one huge merchant creates a hot shard. Mitigation: split large merchants across shards by sub-key, or give them a dedicated shard.
- Shard by payment id. This gives an even spread, but merchant-level queries (list my payments) need a secondary index service, or a separate read store fed by CDC.
- Distributed SQL (CockroachDB, Google Spanner, YugabyteDB) gives automatic range sharding with serialisable transactions. It costs more per write, and cross-region consensus adds latency, but it removes the manual sharding work.
Whichever is chosen, keep a payment and its ledger journal on the same shard, so the state change and the ledger posting commit atomically. See Partitioning and Sharding.
Hot ledger accounts. fees_revenue and the platform's cash accounts are touched by every payment. Use the fixes from Deep Dive 5: N sub-accounts, batched postings, or no running balance on accounts that never need a pre-debit check.
Reads. Merchant dashboards and list queries go to read replicas or to a separate search/analytics store fed by CDC. They must never hit the primary on the payment path. A payment status read immediately after a write should go to the primary, or carry a version, to avoid stale reads; see Database Replication.
Multi-region. Most processors run active-passive per region, or partition merchants by home region, because synchronous cross-region commits add 50–150 ms to each write. For a disaster, the RPO target for committed payments is zero (synchronous replication to a second zone in region, asynchronous to a second region with reconciliation as the backstop). See Multi-Region and Global Data.
Load test the edge cases. Run peak traffic with injected acquirer latency of 5 seconds, broker failover and database primary failover, and check that the UNKNOWN recovery and reconciliation paths keep up. See Capacity Planning and Load Testing.
11. How does a digital wallet work?#
A wallet holds a stored-value balance per user (for example PayPal, Venmo, Alipay, or in-app credits). Payments between wallets are internal transfers: no card network is involved, so they are instant and cheap, but we are now responsible for the balance being right.
Core rules:
- Balances are ledger accounts (
customer_wallet:U), and every transfer is a balanced journal: debit the sender, credit the receiver. - No negative balances. The debit must check and reserve the funds atomically:
UPDATE wallet_balances SET available = available - :amt WHERE account_id = :a AND available >= :amt. Zero rows updated means insufficient funds. Doing a separate read and then a write (check then act) is a race. - Top-ups come in from a card or bank (an external payment, through the normal flow). Withdrawals go out through a payout to a bank account, which is slow and can fail, so funds move to a
pending_withdrawalaccount first. - Regulation: in many places, holding customer funds requires an e-money or money-transmitter licence, and customer funds must be safeguarded in segregated accounts.
Transfers across shards. If sender and receiver live on different shards, one local transaction cannot debit both. Options:
- Saga through a holding account: (a) on shard A, debit the sender and credit
in_transit:A→B, with a transfer id; (b) on shard B, idempotently credit the receiver and debitin_transit. If step (b) keeps failing, a compensating journal returns the money to the sender. Money is never created or lost, because it sits visibly in transit in the meantime. This is the common choice. - Two-phase commit across the two shards gives atomicity, but at the cost of blocking during coordinator failures and extra latency.
- Distributed SQL handles the cross-shard transaction internally, which is simplest for the engineer but has a performance cost.
See Distributed Transactions: 2PC, Sagas and Outbox for the trade-offs.
Banks vs blockchain wallets. A bank or fintech wallet is an entry in a ledger the institution controls: the company can reverse errors, freeze accounts and comply with anti-money-laundering rules, and transfers are fast because they are one database. A blockchain wallet is a private key controlling balances on a public, replicated ledger. There is no central operator to reverse a transfer, settlement depends on block confirmation (from seconds to many minutes, depending on the chain), and losing the key means losing the funds. Custodial crypto exchanges are, internally, ordinary ledgers in the first sense, with an on-chain wallet behind them.
12. How do card networks, banks and other rails fit together?#
A payment system sits inside a larger ecosystem. Knowing the players explains the latencies, the fees and the failure modes.
The four-party card model:
- Cardholder and issuer (the cardholder's bank, which approves or declines and later bills the cardholder);
- Merchant and acquirer (the merchant's bank, which receives the money for the merchant);
- the card network (Visa, Mastercard) in the middle, which routes messages and runs clearing between banks;
- processors and gateways (and payment service providers such as Stripe or Adyen) sit between the merchant and the acquirer, or act as the acquirer themselves.
Three phases:
- Authorisation (in real time, about 1–3 seconds end to end): the issuer checks funds and fraud signals and places a hold.
- Clearing (batch, typically daily): the acquirer submits captured transactions through the network, and the issuer posts them to the cardholder's statement.
- Settlement (usually T+1 to T+2): money moves from issuers to acquirers through the network's settlement banks, net of fees, and then to the merchant.
Who earns what. Of a card payment, most of the merchant discount goes to the issuer as interchange (set by the networks, varying by card type and region; the EU caps consumer interchange at 0.2 percent for debit and 0.3 percent for credit). The network charges scheme fees to both banks, and the acquirer or processor adds its own margin. The networks themselves earn from these per-transaction and volume-based fees, not from lending.
Other rails:
- ACH (US): batch bank transfers, cheap, settled the same day or the next. Returns (for example for insufficient funds) can arrive days later, so "submitted" is not "final".
- SWIFT: a messaging network between banks for cross-border transfers. SWIFT sends instructions. Money moves through correspondent banks holding accounts with each other, which is why international transfers can take days and lose fees at each hop.
- Real-time payment systems: India's UPI, Brazil's Pix and the EU's SEPA Instant settle bank-to-bank in seconds, typically addressed by a phone number or virtual payment address, and are often started by scanning a QR code. A merchant-presented QR encodes the payee and amount. The payer's app scans it, the customer authenticates with their bank, and the bank pushes the money. There is no card number, so no PCI data is involved.
- Apple Pay and Google Pay: the device stores a network token (a device-specific stand-in for the card number) in a secure element or a cloud-based equivalent. Each payment carries a one-time cryptogram. The merchant never sees the real card number, and a stolen token is useless elsewhere.
- FX (cross-currency) payments: a customer pays in one currency, and the merchant settles in another. Someone takes FX risk between authorisation and settlement. Processors quote a rate with a markup, lock it for a period, and post through FX clearing accounts in the ledger.
How a network like Visa routes authorisations, and how clearing and settlement work inside it, is the subject of the payment-network problem. Here, these rails appear as adapters behind the processor gateway: each with its own latency, finality rules and reconciliation file format.
Bottlenecks and Failure Modes#
| Failure / hotspot | Impact | Mitigation |
|---|---|---|
| Acquirer timeout after it actually authorised | Customer charged, our status says failed. The customer retries and is charged twice | UNKNOWN state, status query by reference, recovery worker, never retry blindly with a new reference, reconciliation as backstop |
| Client retries the confirm call | Double charge | Idempotency-Key claimed atomically, fingerprint check, attempt id passed as processor idempotency key |
| Service crashes between the processor call and the database write | Lost success, money taken without a record | Write the attempt as SENT before calling, recovery points, sweeper re-queries stuck attempts |
| Hot ledger account (fees, a big merchant) | Lock contention, rising p99, timeouts | Sub-accounts, batched postings, no running balance on credit-only accounts |
| Hot merchant shard during a big sale | One shard saturates while others idle | Split large merchants by sub-key, dedicated shard, admission control per merchant |
| Kafka broker or partition leader loss | Event delay, possible duplicate publishes | Replication factor 3, acks=all, min ISR 2, outbox relay retries, idempotent consumers |
| Outbox relay falls behind | Webhooks and ledger projections delayed | Monitor outbox age, scale relays per shard, CDC-based relay |
| Merchant webhook endpoint down or slow | Retries pile up, can delay other merchants | Per-endpoint queues and concurrency caps, short timeouts, backoff up to 3 days, events API for catch-up |
| Database primary failover | Seconds of write unavailability, risk of lost commits | Synchronous replica in another zone, RPO 0, clients retry safely with idempotency keys |
| Card-testing attack | Thousands of small authorisations, fees, issuer complaints | Rate limits per IP, card and merchant, CAPTCHA, ML fraud scoring, block on decline-rate spikes |
| Settlement file late, malformed or duplicated | Breaks, wrong merchant balances | Schema validation, raw file stored immutably, idempotent load per file, alert on missing file |
| Secret or key compromise (API keys, webhook secrets, KMS) | Fraudulent refunds or payouts, data exposure | HSM-backed KMS, key rotation, scoped and restricted keys, anomaly alerts on refunds and payouts |
What Interviewers Expect#
Mid-level. A clear API (create, confirm, status), a payments service that calls a PSP or acquirer, a database for payment records and a sensible status field. Mentions idempotency keys to avoid double charges and webhooks for status updates. Understands why card numbers should be tokenised and not stored. May need prompting on timeouts and reconciliation.
Senior. Separates the PCI-scoped vault from the rest of the system. Defines an explicit state machine with guarded transitions. Handles the timeout-after-success problem with an UNKNOWN state, status queries and reconciliation. Uses a transactional outbox to publish events, and idempotent consumers. Introduces a double-entry ledger with immutable entries and explains why. Gets the capacity math right and sizes Kafka and the database for 10k TPS. Designs webhooks with signing, retries and deduplication.
Staff and above. Drives the conversation by money correctness: names the invariants (every journal balances, no payment without a ledger journal, no external effect without an idempotency reference) and shows how each component preserves them. Discusses sharding and hot accounts, cross-shard transfers via sagas through holding accounts, multi-region RPO, and multi-acquirer routing with circuit breakers. Knows the ecosystem (authorisation, clearing, settlement, interchange, network tokens, 3DS and SCA) and how it drives latency, fee and failure behaviour. Raises operations: reconciliation break aging, key rotation, audit, and rollout safety for code that moves money.
Deep Dive: an idempotency middleware for the confirm endpointShow
TypeScript-style pseudo-code. The key is claimed in its own short transaction, so concurrent duplicates collide on the primary key. Recovery points let a retry resume rather than restart.
async function confirmWithIdempotency(req: Req, merchantId: string): Promise<Res> {
const key = req.header("Idempotency-Key");
if (!key) return confirm(req, merchantId); // allowed, but not safe to retry
const fp = sha256(canonicalJson(req.body));
const claimed = await db.tx(t => t.oneOrNone(
`INSERT INTO idempotency_keys (merchant_id, key, fingerprint, state, recovery_point, locked_at)
VALUES ($1,$2,$3,'IN_PROGRESS','started',now())
ON CONFLICT (merchant_id, key) DO NOTHING RETURNING *`, [merchantId, key, fp]));
const rec = claimed ?? await db.one(
`SELECT * FROM idempotency_keys WHERE merchant_id=$1 AND key=$2`, [merchantId, key]);
if (rec.fingerprint !== fp) return res(422, "key reused with different parameters");
if (rec.state === "DONE") return res(rec.response_code, rec.response_body); // replay
if (!claimed) {
const stale = Date.now() - rec.locked_at.getTime() > 60_000;
if (!stale) return res(409, "request in progress, retry later");
await db.none(`UPDATE idempotency_keys SET locked_at=now()
WHERE merchant_id=$1 AND key=$2 AND locked_at=$3`,
[merchantId, key, rec.locked_at]); // take over a crashed run
}
let point = rec.recovery_point;
if (point === "started") { // phase 1: create the attempt, local only
await db.tx(t => createAttempt(t, req, rec, "attempt_created"));
point = "attempt_created";
}
if (point === "attempt_created") { // phase 2: external call, keyed by attempt id
const out = await gateway.authorise(rec.attempt_id, { idempotencyKey: rec.attempt_id });
await db.tx(t => applyOutcome(t, rec, out, "finished")); // status, ledger, outbox, response
}
const done = await db.one(`SELECT response_code, response_body FROM idempotency_keys
WHERE merchant_id=$1 AND key=$2`, [merchantId, key]);
return res(done.response_code, done.response_body);
}Notes:
- Phase boundaries are exactly where an external side effect happens. Everything between two boundaries is one local transaction, so a crash leaves the record at a known recovery point.
- The external call is made safe to repeat by its own idempotency key, the attempt id. If the processor does not support idempotency keys, phase 2 must first query by reference before re-sending.
- The stale-lock takeover uses a compare-and-set on
locked_at, so two retries cannot both take over a crashed run. applyOutcomestores the final HTTP response with the key, so the replay is byte-for-byte identical to the first answer.- A real implementation would also bound the retention of keys (24 hours is common), and run a sweeper that completes or fails records stuck in an intermediate point.
Deep Dive: the ledger in SQL, with a balanced-journal checkShow
A minimal relational ledger. Amounts are signed integers in minor units: positive means debit, negative means credit, and every journal must sum to zero per currency.
CREATE TABLE ledger_accounts (
id BIGSERIAL PRIMARY KEY,
code TEXT NOT NULL UNIQUE, -- 'merchant_pending:m_42'
currency CHAR(3) NOT NULL,
normal_side TEXT NOT NULL CHECK (normal_side IN ('debit','credit')),
allow_negative BOOLEAN NOT NULL DEFAULT false
);
CREATE TABLE ledger_txns (
id BIGSERIAL PRIMARY KEY,
external_ref TEXT NOT NULL UNIQUE, -- 'capture:att_9' makes posting idempotent
effective_at TIMESTAMPTZ NOT NULL,
posted_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE ledger_entries (
txn_id BIGINT NOT NULL REFERENCES ledger_txns(id),
account_id BIGINT NOT NULL REFERENCES ledger_accounts(id),
amount BIGINT NOT NULL CHECK (amount <> 0),
currency CHAR(3) NOT NULL
);
CREATE TABLE account_balances (
account_id BIGINT PRIMARY KEY REFERENCES ledger_accounts(id),
balance BIGINT NOT NULL,
version BIGINT NOT NULL
);
-- Balanced check, run at COMMIT (a deferred constraint trigger in PostgreSQL):
-- SELECT currency, SUM(amount) FROM ledger_entries
-- WHERE txn_id = NEW.txn_id GROUP BY currency HAVING SUM(amount) <> 0;
-- any row returned raises an exception and the whole journal rolls back.Posting the $100 capture with a $3.20 fee is one transaction: insert the ledger_txns row with external_ref = 'capture:att_9' (a duplicate posting fails on the unique constraint, so the posting is idempotent), insert four entries (+10,000 to processor_receivable and −10,000 to merchant_pending for the capture; +320 to merchant_pending and −320 to fees_revenue for the fee), update account_balances for each touched account, and commit. The deferred trigger checks that +10,000 − 10,000 + 320 − 320 = 0.
Lock order. Update balance rows in ascending account_id order. Two journals that touch the same two accounts in opposite orders would otherwise deadlock.
Balance "as of" a date, for audits and statements:
SELECT SUM(e.amount) FROM ledger_entries e JOIN ledger_txns t ON t.id = e.txn_id
WHERE e.account_id = :acct AND t.effective_at < :as_of;This scan is fine for occasional audits. For hot paths, read account_balances, and keep daily balance snapshots so an "as of" query sums only entries since the last snapshot.
Nightly invariant checks: (1) every journal sums to zero; (2) every account_balances.balance equals the sum of its entries; (3) every succeeded payment has a capture journal and every capture journal has a payment; (4) no account with allow_negative = false is negative. Any failure pages an engineer. These checks are what turns "we think the money is right" into "we can show it".
Deep Dive: six failure walkthroughs, step by stepShow
Interviewers like to say "now this crashes here". Here is what the design does in each case.
1. Our server crashes after sending the authorisation, before the reply. The attempt row is already SENT (written before the call). The idempotency record is at recovery point attempt_created. Two things can happen next. If the client retries with the same key, the retry takes over the stale record, sees attempt_created, and re-calls the processor with the same attempt id as the idempotency key. The processor returns the original result rather than charging again. If the client does not retry, the sweeper finds the attempt stuck in SENT for over a minute, queries the processor by reference, and applies the outcome. Either way: one charge, one record.
2. The acquirer times out, but the issuer approved. The attempt moves to UNKNOWN, and the API returns processing to the client, not failed. The recovery worker queries by reference with backoff (for example at 5 s, 30 s, 2 min and 10 min). If the query says approved, the attempt becomes AUTHORISED, the ledger is posted and a webhook is sent. If the acquirer never knows, the safe default is to void or reverse with the same reference, and to let reconciliation the next day confirm that nothing settled.
3. The database commits, but the outbox relay dies. The payment is SUCCEEDED in the database, and the outbox row is unpublished. When the relay restarts, it reads unpublished rows in order and publishes them. Consumers may see an event twice if the relay crashed after publishing but before marking the row, and they deduplicate by event id. The merchant's webhook is late by the relay's downtime, never lost.
4. A late "declined" message arrives after "captured". The guarded transition WHERE status IN ('PROCESSING') updates zero rows, because the payment is already SUCCEEDED. The message is logged and alerted on, not applied. Without the guard, a successful paid order would flip to failed, and the merchant would not ship goods the customer paid for.
5. The merchant's server receives the same webhook twice and ships twice. This is the merchant's bug, but a good platform prevents it by design: a stable evt_ id, documentation that says "deduplicate by event id", and thin events that encourage fetching the current object. Our delivery log shows both attempts, which helps the merchant debug.
6. A whole availability zone fails. The database fails over to the synchronous replica in another zone (seconds of write unavailability, no lost commits). Kafka keeps going with two of three replicas. Stateless services in the surviving zones absorb traffic. In-flight requests fail with 5xx, and clients retry with the same idempotency keys, which makes the retries safe. Attempts left in SENT are cleaned up by the sweeper. The customer sees, at worst, a slow checkout.
The pattern is the same in every case: record intent before acting, make every external action idempotent by reference, guard every transition, and have a recovery process that converges to the truth.
Deep Dive: principles for resilient payment systemsShow
Engineering teams at payment companies (Shopify has published a well-known list of tips on this) keep coming back to a small set of rules. Here is a list in our own words, with the reason for each.
- Use short timeouts, and set them deliberately. A default 60-second timeout on an acquirer call ties up threads and connections during an incident. Measure the p99 latency of each dependency and set the timeout a little above it. Then plan what happens on timeout (the UNKNOWN state), because it will happen.
- Install circuit breakers on every external dependency. When an acquirer's error rate crosses a threshold, stop calling it for a short window and fail fast or reroute, instead of queuing everyone behind a dead service.
- Make every money-moving call idempotent. Generate the key on the client, pass it through every hop, and keep it long enough to cover the longest retry window.
- Retry with exponential backoff and jitter, and only on retryable errors. Never retry a hard decline.
- Store intent before acting. The database row saying "about to authorise attempt X" is what lets recovery work after a crash.
- Reconcile everything against external records, every day. Trust, but verify. The ledger is our belief, and the bank statement is the truth.
- Monitor business metrics, not just system metrics. Authorisation rate per acquirer, card brand and country catches problems that CPU graphs never show. A drop from 92 percent to 85 percent is an incident.
- Load test the failure paths. Test peak traffic with a slow acquirer, not just peak traffic with healthy dependencies.
- Roll out changes slowly. Feature flags and percentage rollouts for code that touches money. A bug at 1 percent of traffic for 10 minutes is a bad afternoon. At 100 percent for an hour, it is a crisis.
- Practise incidents. Game days, where an acquirer or a zone is deliberately broken in a controlled way, find the gaps in runbooks before a real outage does.
Two more that come from the ledger side: never delete or update money records (only append reversing entries), and represent money as integers in minor units, never as floating point.
Deep Dive: observability for a payment systemShow
Business metrics (the most important):
- authorisation rate (approved / attempted), by acquirer, card brand, issuer country, merchant category and 3DS outcome;
- decline-code distribution, where a sudden rise of one code (for example "do not honour" from one issuer) points at the cause;
- payments stuck in PROCESSING or UNKNOWN, by age;
- refund and dispute rates per merchant (a risk signal);
- reconciliation breaks, by type and age;
- webhook delivery success rate and lag, per endpoint.
System metrics: p50, p95 and p99 latency per endpoint and per acquirer; error rates; circuit-breaker state; database commit latency and lock waits on hot ledger rows; outbox age (now minus the oldest unpublished row); Kafka consumer lag per group; idempotency-key conflict rate (a spike means a client bug or an attack).
Tracing. Propagate one trace id from the merchant's API request through the orchestrator, gateway, ledger and webhook dispatch. Attach the payment id and attempt id as span attributes, so "what happened to pi_123?" is one search.
Logging rules. Never log card numbers, CVCs, full tokens or secrets. Scrub them at the logging library level with pattern detectors (a 13–19 digit number that passes the Luhn check is very likely a card number). PCI DSS forbids storing sensitive authentication data, and logs are storage.
Alerting. Alert on symptoms that matter to merchants: the authorisation rate drops beyond its normal band, p99 checkout latency rises, UNKNOWN attempts exceed a threshold, or the outbox age goes over a minute. Use anomaly detection per segment, because a 3 percent global drop can hide a 40 percent drop in one country. See Observability: Logs, Metrics and Traces.
Deep Dive: refunds, chargebacks and disputesShow
Refunds are initiated by the merchant. A refund is its own object with its own state machine (PENDING → SUCCEEDED or FAILED) and its own idempotency key, because a refund is also a money movement that can time out.
- Before capture, there is nothing to refund: the authorisation is voided, and the hold on the customer's card is released (often within minutes, but some issuers take days to release it).
- After capture, a refund is a new transaction sent to the acquirer. The money takes several business days to appear on the customer's statement.
- Partial refunds are allowed up to the captured amount. Enforce
SUM(refunds) <= capturedwith a guarded update on the payment row (refunded_cents + :amt <= captured_cents). A check outside the transaction races with a concurrent refund. - Ledger: debit
merchant_balance, creditrefunds_payable, and when the acquirer confirms, debitrefunds_payable, creditprocessor_receivable(or cash). If the merchant's balance is too low, the platform fronts the money and records a negative merchant balance to recover from future payments, which is an explicit credit risk.
Chargebacks are initiated by the cardholder through their issuer ("I did not make this purchase" or "the goods never arrived"). The issuer takes the money back through the network, and the merchant must respond with evidence by a deadline. Typical timelines are long: cardholders often have around 120 days to dispute, but the exact rules vary by network and reason code.
Design points:
- The dispute is a separate object linked to the payment, with its own state machine (NEEDS_RESPONSE → UNDER_REVIEW → WON or LOST) and deadlines enforced by scheduled jobs.
- The ledger moves the disputed amount plus a dispute fee out of the merchant's balance immediately, and back if the dispute is won.
- Dispute rate is a risk signal. Networks run monitoring programmes for merchants whose chargeback ratio is high (thresholds around 1 percent are commonly cited), with fines and possibly termination. The platform should watch each merchant's ratio and act early.
- Friendly fraud (a real customer disputing a real purchase) is common. 3DS authentication can shift liability for fraud-type chargebacks from the merchant to the issuer, which is one reason merchants accept the extra friction.
Deep Dive: multi-acquirer routing and authorisation-rate optimisationShow
Large processors and large merchants connect to several acquirers (and local acquirers in each region). This brings resilience (fail over when one is down) and money (route to the acquirer with the best approval rate and price for this card).
Routing decision per attempt, using inputs such as card brand, issuer country (from the card's BIN, its first 6–8 digits), currency, amount, merchant category, each acquirer's live health and recent approval rate, and cost:
- Local acquiring: an issuer is more likely to approve a payment acquired in its own country, and cross-border fees are avoided. Route a French card to a French acquirer where possible.
- Health-based failover: a circuit breaker per acquirer. When one breaks, new attempts go to the next one. Never fail over an attempt that may already be in flight (UNKNOWN): resolve it first, or the customer may be charged twice by two acquirers.
- Cost-based routing: among healthy acquirers with similar approval rates, pick the cheapest. US debit routing rules can also allow choosing between networks for debit cards.
Bank and gateway downtime is the normal case. In markets with many banks and payment methods (UPI, net banking, cards, wallets in India), some bank or gateway is degraded almost all the time. Razorpay detects downtime from live success-rate signals per bank, method and gateway, rather than waiting for a bank to announce it, and routes new attempts around degraded paths; it also tells customers at checkout when their bank is having trouble so they can pick another method. Swiggy, as a large merchant, routes between several payment gateways with a model that predicts success for each attempt. Both show the same rule: routing decisions need fresh health signals, a fallback when the model or signal is missing, and care never to re-send an attempt whose outcome is still unknown. See Razorpay's engineering lessons and Swiggy's.
Retrying soft declines. Some decline codes are "soft" (for example "try again later" or "issuer unavailable"). A retry after a delay, or through another acquirer, may succeed. "Hard" declines (stolen card, closed account) must never be retried, and the networks penalise excessive retries on them. Keep a table mapping decline codes to actions.
Card lifecycle tools that raise approvals: network tokens stay valid when a card is reissued with a new number or expiry. Account updater services from the networks provide new card details for saved cards. Both cut declines for recurring payments.
The abstraction: each acquirer is an adapter behind a common gateway interface (authorise, capture, void, refund, status query), with its own message format (often ISO 8583-based, or a REST API), timeouts and decline-code mapping. The orchestrator never knows which acquirer it talks to. The reconciliation job has a parser per acquirer's settlement file.
Deep Dive: saved payment methods and subscriptionsShow
Saved methods. The vault stores the card once, and returns a token (pm_…) attached to a customer object. Later payments reference the token. Rules:
- the first payment is customer-initiated (CIT), with the customer present and authenticated (3DS where required), and it records the customer's consent to future charges;
- later charges without the customer present are merchant-initiated (MIT), and they reference the original authorisation's network transaction id. Under PSD2 in Europe, correctly flagged MITs are generally out of scope for strong customer authentication, which is why the flag matters;
- tokens are scoped to a merchant (or a platform), so a leaked token is useless elsewhere.
Subscriptions add a billing scheduler on top of payments:
- a subscription has a plan, a billing anchor date and a state (TRIALING, ACTIVE, PAST_DUE, CANCELED);
- each period, the scheduler creates an invoice and a payment for it, with an idempotency key derived from the subscription id and the period (
sub_9:2026-12), so a scheduler that runs twice cannot bill twice; - dunning handles failures: retry on a schedule (for example after 1, 3, 5 and 7 days), email the customer to update their card, and finally cancel or pause;
- proration on upgrades and downgrades is ledger arithmetic: credit the unused part of the old plan, and charge the new plan for the rest of the period.
Scale. Billing is bursty: many subscriptions renew on the 1st of the month or at midnight UTC. Spread the work across hours by sharding the scheduler by subscription id, and rate-limit it so a renewal wave does not crowd out live checkout traffic. This is a job-scheduling problem, as in the job-scheduler case.
Deep Dive: marketplaces, split payments and payoutsShow
Marketplaces (ride-hailing, e-commerce platforms, booking sites) take money from buyers and pay many sellers, keeping a commission.
Split payments in the ledger. A $100 ride: debit processor_receivable $100; credit driver_balance:D $75; credit platform_revenue $22; credit payment_fees $3. One balanced journal, and every party's share is visible.
Payouts move balances to sellers' bank accounts:
- A payout scheduler runs daily or weekly per seller, computes the available balance (after a holding period for refund and chargeback risk), and creates a payout object with an idempotency key (seller id + payout date).
- Bank rails are slow and can fail late. ACH returns can arrive days after submission (for example an invalid account). Funds move
available → payout_in_transit → bank_cashand are reversed back toavailableon a return. - Batching: payouts are submitted as bank files or batch API calls, and the confirmation comes from the bank statement, so payouts are reconciled like settlements.
- KYC and compliance: sellers who receive money must be identity-verified before payouts (know your customer, sanctions screening). Unverified sellers accumulate a balance but cannot withdraw it.
Negative balances. If a seller's sale is refunded after they were paid out, their balance goes negative. The platform recovers it from future earnings, or debits their bank account where authorised. This is credit risk, and it is why payout holding periods exist.
Instant payouts (paying out to a debit card in minutes through card push-to-card rails, such as Visa Direct, or real-time bank rails) cost more, and the platform usually charges a fee for them.
Deep Dive: representing money correctlyShow
Never use floating point for money. In binary floating point, 0.1 + 0.2 = 0.30000000000000004. Over millions of fee calculations, these errors add up to real cents that the ledger cannot explain.
Use integers in the currency's minor unit, and store the currency next to every amount. The number of decimal places comes from ISO 4217 and is not always 2:
- USD and EUR have 2 decimals: $12.34 is stored as 1234;
- JPY and KRW have 0 decimals: ¥500 is stored as 500;
- some currencies, such as BHD, KWD and JOD, have 3 decimals: 1.250 BHD is stored as 1250.
A 64-bit integer holds about 9.2 × 10^18 minor units, which is enough for any realistic amount. Where exact decimal arithmetic is needed (FX rates with 6–8 decimal places), use a decimal type (NUMERIC in SQL, a decimal library in code), and convert to integer minor units at a defined, recorded rounding step.
Rounding fees. 2.9 percent of $10.01 is 29.029 cents. Is the fee 29 or 30 cents? Decide a rule (round half up, or banker's rounding, which is round half to even and avoids a systematic upward bias), apply it in one function, and record the inputs. Reconciliation against a processor often fails on exactly this: their rounding differs from yours by one cent on many transactions.
Allocation of remainders. Splitting $100 three ways gives 3,333 + 3,333 + 3,334 cents, not 3,333.33 each. Use a deterministic largest-remainder allocation, so the parts always add up to the whole and the ledger journal balances.
Currency conversion is a journal pair through an FX account, with the rate, its source and its timestamp stored on the journal. Never convert inside a single entry.
Deep Dive: fraud checks and 3DS in the payment pathShow
Risk scoring runs before authorisation, inside the latency budget (target under about 100 ms):
- Rules: velocity (more than N attempts per card, IP or device per minute), blocklists, amount thresholds, mismatches between the card's country and the IP's country.
- Machine-learning score: a model trained on past fraud and chargebacks, using features such as device fingerprint, email age, the card's history across many merchants (a big advantage of large processors), and behaviour on the checkout page.
- Decision: allow, block, or step up to 3DS.
Features need fast lookups, so velocity counters live in an in-memory store (Redis with time-windowed counters), and heavier aggregates are precomputed in a feature store. The model runs as a low-latency service. If it times out, fall back to the rules only. Never block checkout because the fraud model is down, but do alert on it.
3DS (3-D Secure 2) lets the issuer authenticate the cardholder:
- The merchant's page collects device data and sends an authentication request through a 3DS server to the card network's directory server and then the issuer's access control server.
- The issuer either approves without friction (most 3DS2 authentications, based on risk data), or issues a challenge (a code by SMS, or approval in the banking app).
- In our state machine, this is
PROCESSING → REQUIRES_ACTION: the API returns anext_actionwith a redirect or SDK payload. The client completes it, and the payment resumes. Because the customer may abandon the challenge, REQUIRES_ACTION needs a timeout. - A successful 3DS authentication result is then included in the authorisation, and generally shifts liability for fraud chargebacks to the issuer.
Card-testing attacks (bots trying stolen card numbers with small amounts) show up as a burst of declines on one merchant. Defend with per-merchant and per-IP rate limits, CAPTCHA on unusual patterns, and requiring a client secret for confirmation. See Rate Limiting and Throttling.
Deep Dive: testing and shipping code that moves moneyShow
Bugs in payment code cost money directly, so the delivery process carries more of the safety load than usual.
- Property-based tests on invariants. Generate random sequences of operations (capture, partial refund, dispute, payout, retries, duplicate messages), and assert after each one that every journal balances, that no balance is negative unless allowed, and that
SUM(refunds) <= captured. These tests find ordering bugs that example tests miss. - Simulated processors. A fake acquirer that can be scripted to time out, reply twice, reply late, approve after a timeout, or send a settlement file with breaks. Every recovery path should have a test that drives it.
- Shadow mode. Run a new ledger or routing engine alongside the old one on live traffic, compare outputs, and switch over only when the differences are understood.
- Gradual rollout with kill switches. Feature flags per merchant and per percentage of traffic, plus automatic rollback when business metrics (authorisation rate, UNKNOWN count) move outside their band.
- Backfills and migrations of money data are done as new journals (for example "reclassify fee from account A to B"), never as in-place updates, so the audit trail explains them.
- Four-eyes principle for manual adjustments: an operator's correction journal needs a second person's approval, and both identities are recorded.
Deep Dive: a 45-minute interview planShow
| Minutes | What to do |
|---|---|
| 0–5 | Clarify: a PSP like Stripe, or a merchant integrating one? Cards only or wallets too? Scale (10k TPS peak)? Refunds and payouts in scope? |
| 5–10 | Functional and non-functional requirements. Stress correctness over availability for money, plus security (PCI), durability and auditability |
| 10–13 | Quick capacity: TPS, events per second, ledger rows per second, storage per year |
| 13–17 | Entities and API: payment intent, attempt, refund, ledger; create, confirm, capture, refund, with idempotency keys |
| 17–27 | High-level design: API, orchestrator, vault/tokenisation in a PCI zone, gateway to acquirers, database, outbox, Kafka, ledger, webhooks |
| 27–40 | Deep dives the interviewer picks: timeouts and UNKNOWN, idempotency, the double-entry ledger, reconciliation, scaling, webhooks |
| 40–45 | Failure modes, monitoring, and what you would do next (multi-acquirer, multi-region) |
Phrases that signal seniority: "the money is right before it is fast", "record intent before acting", "a timeout is not a failure", "the ledger is append-only", and "reconciliation is the backstop for everything else".
Deep Dive: real-world notesShow
These are publicly described approaches, summarised briefly. Details change over time, so treat them as illustrations, not specifications.
- Stripe exposes
Idempotency-Keyon its API, a PaymentIntent object whose status follows a state machine much like the one in Deep Dive 6, signed webhooks with retries, and an events API for catching up. Its engineers have written publicly about idempotency-key design in PostgreSQL. - Airbnb described its approach to avoiding double payments in a 2019 engineering post, built around an idempotency library and clear separation of pre-RPC, RPC and post-RPC phases, which is close to the atomic-phases idea.
- Shopify has published guidance on resilient payment systems that stresses timeouts, circuit breakers, idempotency, reconciliation and load testing, the themes of the principles DeepDive above.
- Purpose-built ledgers: several fintech companies have described building internal double-entry ledger services, and open-source ledger databases such as TigerBeetle target this workload directly.
- Real-time rails: India's UPI processes billions of transactions a month (NPCI publishes monthly volumes), which shows that account-to-account rails with QR codes can reach card-network scale.
Deep Dive: asynchronous payment methods and delayed finalityShow
Cards give an answer in seconds. Many other methods do not, and the design must handle a payment whose outcome is known hours or days later.
| Method | How it works | When the outcome is final |
|---|---|---|
| Card | Real-time authorisation, then capture | Authorised in seconds. Chargebacks remain possible for months |
| SEPA Direct Debit (EU), ACH debit (US) | The merchant pulls from the customer's bank account under a mandate | Submitted the same day. Returns can arrive days later, and some unauthorised-debit claims much later |
| Bank transfer or real-time rails (UPI, Pix, SEPA Instant) | The customer pushes money from their bank | Seconds on instant rails. Hours to days on classic transfers |
| Vouchers (for example Boleto in Brazil, OXXO in Mexico) | The customer pays cash at a shop or bank with a reference | Hours to days, and many vouchers are never paid |
| Buy now, pay later | A third-party lender pays the merchant and collects from the customer | Approval in seconds. The lender carries the credit risk |
| Wallets (PayPal, Alipay) | Redirect to the wallet, then a callback | Usually seconds, with a callback or webhook to confirm |
Design consequences:
- The state machine needs a long-lived PROCESSING state with a timeout per method (a voucher may expire after 3 days). The merchant gets
payment.processingimmediately andpayment.succeededorpayment.failedlater, by webhook. - Do not release goods on "submitted" for methods that can be returned. Many merchants ship on PROCESSING for low-risk debits and accept the return risk. That is a business decision the API must expose clearly, not hide.
- Late returns are reversing journals. An ACH return three days after SUCCEEDED moves the payment to FAILED (or a RETURNED sub-state), posts a reversal, and fires a webhook. The guarded-transition table must allow this specific late transition, and nothing else.
- Each method is an adapter with its own reconciliation file and finality rules, behind the same intent API. A merchant integrates once, and new methods appear as configuration.
Deep Dive: consistency choices, and what happens during a partitionShow
The CAP theorem says that, during a network partition, a replicated system must give up either consistency or availability. PACELC adds that even without a partition, there is a trade-off between latency and consistency. A payment system makes different choices for different data:
- Payment state, idempotency records and the ledger: consistency (CP). If the database primary cannot reach its synchronous replica, it should stop accepting writes rather than risk two divergent histories of money. A few seconds of "please retry" is far cheaper than a double charge or a phantom balance. Clients retry with the same idempotency key, so the retry is safe.
- Merchant dashboards, reports and search: availability (AP). These are read models fed by CDC. They can lag by seconds, and they show a "data as of" time.
- Fraud velocity counters: available, approximately correct. If the Redis counter is briefly unavailable or slightly stale, fall back to rules. A missed count is a small risk. Blocking all checkouts is a large one.
- Webhooks: at-least-once, eventually delivered. Ordering is not guaranteed. Correctness comes from the merchant fetching the current object.
Read-your-writes. After confirm returns SUCCEEDED, a merchant who immediately calls GET /payment_intents/{id} must not see processing from a lagging replica. Route reads of a just-written object to the primary, or have the client pass the version it saw, and wait for (or redirect away from) replicas older than that version.
Linearisable money checks. Wallet debits must see the latest balance. A balance check against a replica allows overspending. This is why the balance check and the debit are one guarded update on the primary.
See Consistency Models and CAP Theorem and PACELC.
Deep Dive: inside the card vaultShow
The vault is the most security-sensitive component: the only place where full card numbers (PANs) exist in readable form, and then only briefly.
Scope and PCI DSS. The Payment Card Industry Data Security Standard applies to every system that stores, processes or transmits card data, or that can affect the security of systems that do (the cardholder data environment). Keeping the vault small and isolated keeps the audited scope small. A merchant using hosted fields or a hosted payment page never touches PANs, so its own compliance burden is much lighter (a short self-assessment questionnaire instead of a full on-site assessment).
Architecture:
- A separate network segment, separate cloud accounts or projects, and separate deploy pipelines, with access only from the tokenisation endpoint (inbound PANs from client SDKs) and the processor gateway (outbound detokenisation).
- Tokenisation: on receiving a PAN, the vault generates a random token (no mathematical relationship to the PAN), encrypts the PAN, and stores
token → ciphertext. It may also store a keyed hash of the PAN (an HMAC with a secret key, not a plain hash, because the PAN space is small enough to brute-force) to detect duplicate cards without decrypting. - Detokenisation is allowed only for the gateway, for a specific attempt, and every call is logged. The gateway puts the PAN into the acquirer message and does not persist it.
- Encryption with a key hierarchy: each record or batch is encrypted with a data-encryption key (DEK). DEKs are encrypted ("wrapped") by key-encryption keys held in an HSM or a cloud KMS backed by one. Key rotation re-wraps DEKs under a new master key, which is fast, and re-encrypts data lazily or in a background job.
- Never store the CVC or full track or chip data after authorisation. PCI DSS prohibits keeping this sensitive authentication data, even encrypted.
Availability. The vault is on the critical path of every payment, so it is replicated across zones. Its throughput needs are modest (one tokenisation per new card, one detokenisation per authorisation), so 10k TPS is well within a small cluster's capacity.
Network tokens (issued by Visa and Mastercard) reduce the vault's role further: the token itself is accepted by the network, is bound to the merchant, and is updated automatically when the card is reissued.
Deep Dive: payment history, reporting and data retentionShow
Payment history for customers and merchants. The payment path writes to the primary database. History and search ("all payments for customer X in November", "failed payments over $500 last week") are served from read models built by CDC or from the event stream:
- a search index (for example Elasticsearch) for merchant dashboards with filters and full-text search on descriptions and emails (see Elasticsearch and Search Systems);
- a columnar warehouse for analytics, revenue reports and finance;
- precomputed daily balance and payout reports per merchant.
These lag the primary by seconds. Pagination uses a cursor (created_at, id), not offsets, because the data grows continuously.
Retention. Financial records must be kept for years for tax, audit and anti-money-laundering rules (often 5–10 years, depending on the jurisdiction). The capacity estimate gave about 70 TB a year of ledger entries before replication, so tiering matters:
- the last few months in the hot transactional database;
- older partitions (by month) moved to cheaper storage, or to compressed columnar files in object storage, still queryable for audits;
- raw processor messages and settlement files in object storage with retention locks.
Privacy versus retention. Privacy laws (such as GDPR) give people a right to erasure, but financial-record laws require keeping transaction records. The usual resolution: keep the financial record, minimise personal data in it (tokens and ids, not names and addresses), and keep personal data in a separate store that can be erased or pseudonymised. Deleting a customer then removes the link from ids to the person, while the ledger still balances.
Deep Dive: orchestrating the payment flow, state table or workflow engineShow
There are two common ways to implement the orchestrator.
1. Database state machine plus workers (the design above). The payment row holds the state. Each step is a guarded transition plus an outbox event. Workers and sweepers advance stuck payments. Pros: simple to reason about, everything in one database, very high throughput. Cons: timers, retries and multi-step compensation are hand-built, and the logic for one flow is spread across several workers.
2. Durable workflow engine (Temporal, AWS Step Functions, or similar). The flow is written as ordinary code: authorise → (3DS?) → capture → post ledger → notify. The engine persists each step's result, retries activities with policies, and resumes the workflow on another worker after a crash. Pros: long, branching flows (disputes with 7-day deadlines, payouts with returns, subscription dunning) read like a script, and durable timers come free. Cons: another critical system to run, and an extra hop and history writes per step, which adds latency and cost at 10k TPS.
A common split: keep the hot, short card-payment path as a database state machine, and use a workflow engine for the long-running flows (disputes, payouts, onboarding, dunning), where clarity matters more than raw throughput. Both still need idempotent activities, because a workflow engine retries activities at least once.
Deep Dive: the capacity numbers, worked through with Little's lawShow
Little's law says that the average number of requests in a system equals the arrival rate times the average time each spends inside: L = λ × W. It turns throughput targets into concurrency and pool sizes.
- In-flight acquirer calls: λ = 10,000 per second at peak, W ≈ 0.8 s average authorisation latency, so L ≈ 8,000 concurrent calls. With 20 gateway instances, that is about 400 open calls each. Blocking one thread per call would need 400 threads per instance, while an async HTTP client handles it with a few event-loop threads. At p99 (say 3 s), concurrency briefly reaches 30,000, which is why per-acquirer connection limits must be agreed in advance.
- Database connections: each payment holds a connection for roughly 3 short transactions of about 5 ms each, never across the external call. At 10k TPS, that is 10,000 × 3 × 0.005 s = 150 busy connections on average across the fleet. Spread over 8 shards, that is about 20 per shard, and a pool of 50 per shard gives headroom. If a developer accidentally holds the transaction open across the acquirer call (W ≈ 0.8 s instead of 5 ms), the need jumps to 8,000 connections, and the database falls over. This is the most common way a payment service melts down under load.
- Ledger writes: 10k payments per second × about 8 entries = 80k entry rows per second, plus balance-row updates. Across 8 shards, that is 10k rows per second per shard, comfortable for a well-tuned PostgreSQL primary on fast NVMe storage, with batching of commits (group commit).
- Kafka: about 50k events per second × 1 KB = 50 MB/s in, and several consumer groups reading it, so a few hundred MB/s out. A 6-broker cluster handles this with room to spare.
- Storage per year: at about 130M payments a day, with roughly 2 KB per payment across intent, attempts, events and idempotency rows, that is about 260 GB a day, or about 95 TB a year. Together with the ledger's ~70 TB a year, and three-way replication, it is around 500 TB a year. That is why hot data is kept for months and older partitions are tiered.
These numbers are illustrative orders of magnitude. The point in an interview is the method: rate × time gives concurrency, and concurrency shows where the limits are.
Deep Dive: a cross-shard wallet transfer, step by stepShow
Alice (on shard A) sends $50 to Bob (on shard B). The transfer is a saga through an in-transit account, coordinated by a transfer record.
Why it is safe:
- Txn 1 is local to shard A and includes the balance check (
available >= 5000), so Alice cannot overspend, even with concurrent transfers. - Between Txn 1 and Txn 2, the $50 sits visibly in
in_transit_A. After Txn 2,in_transit_A(credited) andin_transit_B(debited) offset each other, and a periodic job checks that the in-transit accounts across all shards net to zero for completed transfers. The sum of all balances, including in-transit accounts, is unchanged, so global invariants still hold. - Txn 2 is idempotent, by a unique constraint on the transfer id in shard B's processed-transfers table. A redelivered event is a no-op.
- If Bob's account is closed or frozen, Txn 2 fails permanently, and a compensating event makes shard A debit
in_transitand credit Alice back. The transfer ends as FAILED, with a full audit trail. - A sweeper alerts on transfers in PENDING for longer than a threshold (for example 1 minute), which is the transfer equivalent of the UNKNOWN payment sweeper.
The client sees "pending" for a few hundred milliseconds. Most apps show the transfer as sent immediately, and the receiver's balance updates a moment later.
Deep Dive: cross-border payments and FX in more depthShow
When a customer in Japan pays a US merchant, several currencies may be involved: the presentment currency the customer sees (JPY or USD), the card's billing currency (JPY), and the merchant's settlement currency (USD).
- Network conversion: the merchant charges in USD, and the card network converts to JPY for the issuer at the network's daily rate. The issuer usually adds a foreign-transaction fee. The customer sees a JPY amount only on the statement.
- Multi-currency pricing by the processor: the merchant shows prices in JPY. The processor authorises in JPY and converts to USD for the merchant at its own rate plus a markup. The processor now carries FX risk between authorisation and settlement, so it quotes a rate that is valid for a fixed window and hedges the aggregate exposure.
- Dynamic currency conversion (DCC) at terminals offers the cardholder a choice to pay in their home currency at the point of sale. It is often more expensive for the cardholder than network conversion, and regulators in some regions require clear disclosure.
In the ledger: an FX conversion is two balanced journals, one per currency, joined through an fx_clearing account per currency pair, with the rate, the source and the timestamp stored on the journals. The FX clearing accounts' residual balances are the realised FX gain or loss, which finance reviews daily.
Refunds in a foreign currency raise a policy question: refund the original JPY amount (the customer is made whole, and the merchant takes the rate change), or the original USD amount (the reverse). The system must record the choice explicitly, because the two answers differ by real money.
Deep Dive: common follow-up questions, with short answersShow
"Why not use a distributed transaction (2PC) with the acquirer?" External networks do not take part in our transactions. They expose request and response messages, sometimes with idempotency, and later settlement files. The only tools available are idempotent references, status queries, compensation (void or refund) and reconciliation.
"Can we make the confirm call synchronous end to end?" For cards, yes, mostly. The client waits 1–3 seconds for the authorisation. But the API must still be able to return processing (on timeout or for asynchronous methods), and clients must handle it. Designing only for the happy path is the most common interview mistake.
"What if Kafka is down?" Payments still commit, because events are written to the outbox in the database. Webhooks and projections are delayed until Kafka recovers and the relay catches up. Nothing is lost, which is why the outbox exists.
"What if the ledger service is down?" If the ledger is in the same database as payments, it is not a separate failure. If it is a separate service, payments can continue with ledger postings queued durably through the outbox, and balances that gate decisions (wallet debits, payouts) must wait for the postings to catch up. Never let a payout run on a stale balance.
"How do you prevent a merchant's refund bug from draining their balance?" Per-merchant refund rate limits, alerts on unusual refund volume, a cap of total refunds at the captured amount per payment (a guarded update), and restricted API keys that cannot refund unless granted that permission.
"How would you support a second currency or country?" New ledger accounts per currency, a local acquirer adapter, local payment methods as adapters, local compliance (SCA in Europe, data-residency rules in some countries), and settlement in the merchant's currency through FX journals.
Production reference. See Stripe's engineering lessons for idempotency, the ledger and reconciliation, and Razorpay's for bank downtime detection, routing, the outbox and payment peaks.
Key Takeaways#
- Correctness first. A payment system may be slow or briefly unavailable, but it must never lose, create or duplicate money. Choose strong consistency on the payment path.
- Shrink PCI scope. Card data goes straight from the client to a small vault. Everything else handles tokens.
- A timeout is not a failure. Use an UNKNOWN state, query by reference, resolve with recovery workers, and let reconciliation be the backstop.
- Idempotency everywhere. Idempotency keys from client to API, attempt ids to acquirers, event ids to consumers and merchants. At-least-once delivery plus idempotent processing gives an exactly-once effect.
- Explicit state machines with guarded transitions stop late or duplicate messages from moving payments into impossible states.
- A double-entry, append-only ledger makes every cent explainable: balanced journals, reversing entries instead of edits, balances as projections, and nightly invariant checks.
- The outbox pattern ties database commits to events without distributed transactions, and feeds webhooks, ledger projections and analytics.
- Reconcile daily against processor settlement files and bank statements, and treat break aging as a key metric.
- Scale by partitioning: stateless services, Kafka keyed by payment id, database sharded so a payment and its journal share a shard, and hot ledger accounts split into sub-accounts.
- Know the ecosystem: issuers, acquirers, networks, authorisation, clearing and settlement, plus ACH, SWIFT, UPI, wallets and network tokens. Each rail has its own latency and finality, which the design must respect.