A payment system like Stripe accepts a merchant's request to charge a card, moves the request through card networks and banks, and records every cent in a ledger that must balance forever. Throughput is modest compared with a social feed, but the correctness bar is absolute: charging a customer twice, losing a refund or miscounting a payout is a real financial and legal failure. The design is built from idempotency at every hop, an explicit payment state machine, a double-entry ledger and daily reconciliation against what the banks say actually happened.
Think of it like
A careful bank teller
A good teller asks for your ticket number before doing anything, so pressing the button twice never pays twice. Every transfer is written in a carbon-copy book with two lines, one taking money from somewhere and one putting it somewhere else, so the columns always add up. When the phone line to head office drops mid-transfer, the teller does not guess: they call back and ask what happened. And at closing time they count the drawer against the bank's statement and investigate every difference.
1. Requirements
Functional
- Merchants create and confirm payments for card transactions
- Authorize now and capture later (or both at once); cancel uncaptured payments
- Full and partial refunds; handle disputes (chargebacks)
- Pay out merchant balances to their bank accounts
- Notify merchants of every state change by webhook
- Support many currencies
Non-functional
- Correctness above all: never double charge, never lose a transaction, ledger always balances
- Strong consistency for payment state and balances
- High availability for checkout (downtime is lost sales), p99 dominated by the bank round trip (~1–3 s)
- Full auditability: immutable history of every change
- Security and compliance: PCI DSS, strong customer authentication where required
| In scope | Out of scope |
|---|---|
| Card payments through external processors (PSPs and acquirers) | Becoming a card network or issuing bank |
| Payment lifecycle, idempotency, ledger, reconciliation | Tax calculation, invoicing and subscriptions logic |
| Refunds, disputes, payouts, webhooks | Lending, crypto, bank transfer rails in depth (mention ACH and SEPA as variants) |
| Fraud checks and PCI scope at a high level | Building the fraud ML models themselves |
2. Back-of-the-envelope estimation
Assume 10 million payments per day with an average of $50, about 5 API calls and 3 webhook events per payment, and roughly 10 ledger entries per payment over its life (capture, settlement, fees, payout). See Back-of-the-Envelope Estimation.
Peak payments
~1,200 /s
10× the daily average
Ledger growth
~7 TB /yr
kept for many years
Daily volume
$500M
10M × $50
Cost of 0.01% error
$50k /day
why reconciliation exists
3. How a card payment actually moves
Card payments happen in two phases with very different timing. Authorization is a real-time question to the cardholder's bank ("is this card good for $50?") that places a hold. Clearing and settlement move the money later, in batches, usually over one to a few business days. Press play to follow each phase.
- PSP (payment service provider)
- A company that connects merchants to the card networks and banks (Stripe, Adyen, Braintree). Our platform either is one or sits on top of several.
- Acquirer
- The bank (or processor) that holds the merchant relationship with the card networks and receives settlement funds.
- Issuer
- The cardholder's bank. It approves authorizations and carries the credit risk.
- Authorization and capture
- Authorization reserves funds; capture claims them. Capturing immediately is a "sale"; capturing later suits shipped goods and hotels.
- Chargeback
- A cardholder disputes a charge through their issuer; the funds are pulled back from the merchant unless the merchant wins the dispute with evidence.
4. API design
POST /v1/payment_intents HTTP/1.1
Authorization: Bearer sk_live_...
Idempotency-Key: order-81723-attempt-1
Content-Type: application/json
{
"amount": 5000,
"currency": "usd",
"payment_method": "pm_tok_9fK2",
"capture_method": "manual",
"metadata": { "order_id": "81723" }
}
HTTP/1.1 200 OK
{
"id": "pi_3Nq",
"status": "requires_capture",
"amount": 5000,
"amount_capturable": 5000,
"currency": "usd"
}POST /v1/payment_intents/pi_3Nq/capture
Idempotency-Key: order-81723-capture
{ "amount_to_capture": 4500 } -> 200 { "status": "succeeded" }
POST /v1/refunds
Idempotency-Key: order-81723-refund-1
{ "payment_intent": "pi_3Nq", "amount": 1500 } -> 200 { "id": "re_7Tb", "status": "pending" }
GET /v1/payment_intents/pi_3Nq -> 200 { "status": "succeeded", "amount_refunded": 1500 }- Amounts are integers in minor units (
5000= $50.00) with an explicit currency. Never send50.00as a float. - Every mutating call takes an
Idempotency-Key. A retry with the same key returns the original result instead of charging again; the same key with different parameters is rejected. - A payment is an object with a status, not a one-shot RPC. Clients can always ask "what happened to
pi_3Nq?", which is how timeouts get resolved. - The design follows Stripe's PaymentIntent API closely; see API Design: REST, GraphQL & gRPC for general principles.
5. Data model
CREATE TABLE payment_intents (
id TEXT PRIMARY KEY, -- 'pi_3Nq'
merchant_id BIGINT NOT NULL,
amount BIGINT NOT NULL CHECK (amount > 0), -- minor units
currency CHAR(3) NOT NULL, -- ISO 4217, e.g. 'USD'
status TEXT NOT NULL, -- see the state machine
amount_captured BIGINT NOT NULL DEFAULT 0,
amount_refunded BIGINT NOT NULL DEFAULT 0,
version INT NOT NULL DEFAULT 0, -- optimistic concurrency
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
CHECK (amount_refunded <= amount_captured AND amount_captured <= amount)
);
-- One row per call to a processor; the id is also the processor-side idempotency key.
CREATE TABLE payment_attempts (
id TEXT PRIMARY KEY,
intent_id TEXT NOT NULL REFERENCES payment_intents(id),
operation TEXT NOT NULL, -- 'authorize' | 'capture' | 'refund'
psp TEXT NOT NULL,
psp_reference TEXT, -- the processor's id, once known
status TEXT NOT NULL, -- 'pending' | 'succeeded' | 'failed' | 'unknown'
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE idempotency_keys (
merchant_id BIGINT NOT NULL,
key TEXT NOT NULL,
request_hash TEXT NOT NULL, -- detects reuse with different parameters
status TEXT NOT NULL, -- 'in_progress' | 'completed'
response_code INT,
response_body JSONB,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (merchant_id, key)
);
-- Transactional outbox: written in the same transaction as the state change.
CREATE TABLE outbox_events (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
merchant_id BIGINT NOT NULL,
type TEXT NOT NULL, -- 'payment_intent.succeeded', ...
payload JSONB NOT NULL,
published_at TIMESTAMPTZ
);6. High-level architecture
Card numbers go straight from the customer's browser to a tokenization vault, so the rest of the system only handles tokens. The payment service owns the state machine and talks to processors through an adapter; the ledger service records money movement; an outbox feeds webhooks; and a reconciliation job compares everything with the processors' settlement reports. Press play on a flow.
7. Deep dive: the payment state machine
A payment is a long-lived object that moves through explicit states. Every transition is a guarded, atomic update, so two workers (say, a capture request and an expiry job) can never both act on the same state. The statuses below are modeled on Stripe's PaymentIntent.
requires_payment_method --confirm-------------------------> processing
processing --needs 3-D Secure-----------------> requires_action
requires_action --authenticated--------------------> processing
requires_action --failed or abandoned--------------> requires_payment_method
processing --declined-------------------------> requires_payment_method (try another card)
processing --approved, capture_method=manual--> requires_capture
processing --approved, capture_method=auto----> succeeded
requires_capture --capture (full or partial)--------> succeeded
requires_capture --cancel or authorization expiry---> canceled
requires_payment_method --cancel---------------------------> canceled
succeeded --refund---------------------------> succeeded (amount_refunded grows)| Transition | Guard | Side effects in the same transaction |
|---|---|---|
| confirm: requires_payment_method → processing | status matches; risk check passed | attempt row (pending), idempotency key in progress |
| approved: processing → requires_capture | attempt succeeded | ledger entries for the hold (memo) if tracked, outbox event |
| capture: requires_capture → succeeded | amount ≤ capturable; not expired | capture attempt, ledger entries (receivable, merchant payable, fee), outbox event |
| cancel or expire: requires_capture → canceled | no capture in flight | void attempt to release the hold, outbox event |
| refund (on succeeded) | amount_refunded + amount ≤ amount_captured | refund object, ledger reversal entries, outbox event |
-- Only one actor can win: the WHERE clause checks the current state and version.
UPDATE payment_intents
SET status = 'succeeded',
amount_captured = 4500,
version = version + 1
WHERE id = 'pi_3Nq'
AND status = 'requires_capture'
AND version = 3;
-- 0 rows updated: someone else changed it first (or it expired). Re-read and decide; never blindly retry.8. Deep dive: idempotency at every hop
Networks give at-least-once delivery, so duplicates will arrive at every boundary. Exactly-once effects come from making each hop idempotent and then proving it with reconciliation. See Idempotency & Delivery Guarantees for the general theory.
| Hop | Duplicate source | Guard |
|---|---|---|
| Merchant → our API | Merchant retries after a timeout | Idempotency-Key stored with a unique constraint, request hash and saved response |
| Our service → processor | Our retry after an unknown outcome | Attempt id sent as the processor's idempotency key or merchant reference |
| Processor → us (webhooks) | Processor redelivers status events | Dedupe by processor event id; state transitions are guarded |
| Payment → ledger | Retried posting after a crash | UNIQUE (source_type, source_id) on ledger transactions |
| Us → merchant (webhooks) | Our retries | Stable event ids the merchant dedupes on |
- 1
Claim the key
INSERT ... ON CONFLICT DO NOTHINGintoidempotency_keyswith statusin_progressand a hash of the request body. Exactly one concurrent request wins. - 2
Handle the losers
Same key, different hash:
422(a client bug). Same key, still in progress:409, retry later. Same key, completed: replay the stored status code and body byte for byte. - 3
Do the work, then store the result
Final outcomes (approved, declined, validation error) are saved with the key. A definite retryable failure (the processor rejected the request before doing anything) releases the key so the client can retry.
- 4
Leave unknowns in progress
If the outcome is unknown, the key stays
in_progressand the intentprocessing. A recovery worker resolves it and completes the key, so the client's later retry replays the real answer.
9. Deep dive: the double-entry ledger
The ledger is the source of truth for who owes whom. Every movement is a transaction of two or more entries whose amounts sum to zero: money always comes from one account and goes to another. Balances are never stored as editable numbers; they are the sum of immutable entries.
CREATE TABLE accounts (
account_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name TEXT NOT NULL, -- 'psp_receivable', 'merchant_payable:m_1', 'fee_revenue'
type TEXT NOT NULL CHECK (type IN ('asset', 'liability', 'revenue', 'expense', 'equity')),
currency CHAR(3) NOT NULL,
UNIQUE (name, currency)
);
CREATE TABLE ledger_transactions (
txn_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
source_type TEXT NOT NULL, -- 'capture', 'refund', 'settlement', 'payout'
source_id TEXT NOT NULL, -- e.g. the attempt or settlement line id
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE (source_type, source_id) -- the same event can never be posted twice
);
CREATE TABLE ledger_entries (
entry_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
txn_id BIGINT NOT NULL REFERENCES ledger_transactions(txn_id),
account_id BIGINT NOT NULL REFERENCES accounts(account_id),
amount BIGINT NOT NULL CHECK (amount <> 0), -- minor units: debit > 0, credit < 0
currency CHAR(3) NOT NULL
);
-- Invariant enforced when posting: for each txn_id and currency, SUM(amount) = 0.
-- Entries are append-only; a mistake is corrected by a new, reversing transaction.| Event | Account | Debit | Credit |
|---|---|---|---|
| Capture $100.00 (illustrative fee: 2.9% + 30¢ = $3.20) | psp_receivable (asset) | 10,000 | |
merchant_payable:m_1 (liability) | 9,680 | ||
fee_revenue (revenue) | 320 | ||
| Processor settles, keeping $2.50 | bank_cash (asset) | 9,750 | |
processing_fees (expense) | 250 | ||
psp_receivable (asset) | 10,000 | ||
| Payout to merchant | merchant_payable:m_1 (liability) | 9,680 | |
bank_cash (asset) | 9,680 |
- One currency per account. A conversion is its own transaction with balanced entries in each currency through an FX account (recording the rate, its source and timestamp), never a USD debit against a EUR credit. Currency gains and losses then show up explicitly instead of hiding in rounding.
- Balances are derived. Compute them by summing entries, and cache running balances or periodic snapshots for speed; the entries remain the truth.
- Invariants are checkable. The sum of every entry ever written is zero; any non-zero total means a bug, and it can be detected automatically.
- Holds can be tracked too: many ledgers record pending authorizations in separate pending accounts, so available and pending balances are both visible.
10. Deep dive: reconciliation and webhooks
Idempotency prevents most errors; reconciliation catches the rest, including bugs in processors and banks. It compares three independent records: our ledger, the processor's settlement reports, and the actual bank statements.
| Mismatch | Likely cause | Resolution |
|---|---|---|
| In our ledger, not in the report | Capture never reached the processor, or arrives in tomorrow's file | Wait one cycle, then query the processor and repost or void |
| In the report, not in our ledger | We lost track after an unknown outcome | Resolve the attempt from the processor's record and post the missing entries |
| Amounts differ | Fees changed, partial capture, FX rounding | Post an adjustment transaction with the reason |
| Report total ≠ bank deposit | Reserves, chargebacks or bank fees netted out | Match against the processor's payout breakdown |
- Webhooks to merchants: outbox, then deliver. events are written in the same transaction as the state change and published by a relay, so no event is lost and none describe a rolled-back change. See Event-Driven Architecture, CQRS & Event Sourcing.
- Sign every payload: an HMAC over the timestamp and body, with a secret per endpoint, so merchants can verify origin and reject replays.
- Retry with backoff for a long time: Stripe documents retries for up to three days in live mode. Disable endpoints that fail persistently and alert the merchant.
- At-least-once and unordered: merchants must dedupe by event id and re-fetch the object if ordering matters. Webhooks are hints; the API is the truth.
import { createHmac, timingSafeEqual } from "node:crypto";
const TOLERANCE_S = 300; // reject events older than 5 minutes (replay protection)
export function verify(rawBody: string, header: string, secret: string, nowS = Date.now() / 1000): boolean {
// header format: "t=1731234567,v1=5257a869e7..."
const parts = Object.fromEntries(header.split(",").map((kv) => kv.split("=") as [string, string]));
const t = Number(parts.t);
if (!parts.v1 || !Number.isFinite(t) || Math.abs(nowS - t) > TOLERANCE_S) return false;
const expected = createHmac("sha256", secret).update(`${t}.${rawBody}`).digest();
const given = Buffer.from(parts.v1, "hex");
return given.length === expected.length && timingSafeEqual(given, expected); // constant time
}11. Refunds and disputes
Refunds
- A separate object with its own idempotency key and state (
pending→succeededorfailed) - Guard: total refunded never exceeds total captured (a check constraint plus a guarded update)
- Ledger: reversing entries, with policy deciding who bears fees
- The cardholder may see the credit only after several business days
Disputes (chargebacks)
- Initiated by the cardholder's issuer, not by the merchant or us
- Funds (plus a dispute fee) are debited from the merchant balance immediately
- The merchant submits evidence by a deadline; the issuer decides
- Ledger entries for the debit and, if won, for the reversal; high dispute rates trigger network monitoring programs
12. Currency handling
| Currency | Minor-unit exponent (ISO 4217) | Display | Stored as |
|---|---|---|---|
| USD | 2 | $12.34 | 1234 |
| EUR | 2 | €12.34 | 1234 |
| JPY | 0 | ¥1,234 | 1234 |
| KWD | 3 | 1.234 KWD | 1234 |
/** Split total (minor units, ≥ 0) by integer weights; leftover units go to the largest remainders. */
export function allocate(total: bigint, weights: bigint[]): bigint[] {
const sum = weights.reduce((a, b) => a + b, 0n);
const parts = weights.map((w) => (total * w) / sum); // floor
let leftover = total - parts.reduce((a, b) => a + b, 0n); // always < weights.length
const order = weights
.map((w, i) => ({ i, rem: (total * w) % sum }))
.sort((a, b) => (a.rem === b.rem ? a.i - b.i : a.rem > b.rem ? -1 : 1));
for (let k = 0; leftover > 0n; k++, leftover--) parts[order[k].i] += 1n;
return parts;
}
// allocate(1000n, [1n, 1n, 1n]) -> [334n, 333n, 333n] ($10.00 three ways)
// fee for $100.00 at 2.9% + 30¢: (10000n * 290n) / 10000n + 30n -> 320n13. Fraud, risk and PCI scope
Fraud and risk
- Synchronous scoring before authorization, within a budget of tens of milliseconds
- Rules (velocity per card, IP and device using counters, see Rate Limiting) plus ML models on network-wide signals
- Outcomes: allow, require 3-D Secure (shifts fraud liability to the issuer in many cases), review, or block
- Strong customer authentication is mandatory for many European payments under PSD2
- Feedback loop: disputes and confirmed fraud label training data
PCI scope and tokenization
- Any system that stores, processes or transmits card numbers is in PCI DSS scope
- Hosted fields or redirects send card data straight to the vault, so merchant servers only handle tokens
- That can reduce a merchant to the simplest self-assessment (such as SAQ A)
- Inside the platform, isolate the vault in its own network segment with strict access and encryption via an HSM-backed key hierarchy
- Network tokens from Visa and Mastercard can replace stored card numbers and survive card reissues
14. Scaling, bottlenecks and failure handling
- Shard by merchant once one primary is not enough; a payment, its attempts, its ledger entries and its outbox stay on one shard so they commit together. See Sharding & Partitioning.
- Hot accounts: a platform-wide account (like
fee_revenue) touched by every payment becomes a lock hotspot. Split it into sub-accounts and roll them up, or batch its entries. - Multiple processors: route by cost, country and health, with a circuit breaker per processor. Fail over only for attempts that definitely did not execute. See Resilience Patterns.
- Read replicas and an event stream serve dashboards and analytics so they never load the primary.
- Observability: authorization rate per processor and card type, unknown-outcome count, reconciliation exceptions, and ledger imbalance (which must always be zero). See Observability.
| Failure | Risk | Handling |
|---|---|---|
| Processor timeout | Double charge if retried with a new key | Attempt marked unknown; resolve with the same key or a status query |
| Crash after processor approval, before our commit | Customer charged, our record says processing | Recovery worker scans stale attempts and queries the processor; reconciliation is the backstop |
| Processor outage | Lost sales | Route new payments to a second processor; queue captures and refunds for later |
| Database primary failure | Writes unavailable | Synchronous replica promoted; no acknowledged transaction lost |
| Duplicate webhook from processor | Double state transition | Event id dedupe and guarded transitions |
| Bug posts wrong entries | Balances wrong | Imbalance alerts, reconciliation, reversing transactions; never edit history |
Implementation
Claims the key atomically, replays stored responses, and leaves unknown outcomes in progress for a recovery worker instead of guessing.
import hashlib
import json
from dataclasses import dataclass
from typing import Any, Callable, Literal, Optional, Protocol
@dataclass(frozen=True)
class Outcome:
kind: Literal["final", "retryable", "unknown"]
code: int = 0
body: Any = None
@dataclass(frozen=True)
class StoredKey:
request_hash: str
status: Literal["in_progress", "completed"]
response_code: Optional[int] = None
response_body: Any = None
class KeyStore(Protocol):
def claim(self, merchant_id: str, key: str, request_hash: str) -> bool: ...
def get(self, merchant_id: str, key: str) -> StoredKey: ...
def complete(self, merchant_id: str, key: str, code: int, body: Any) -> None: ...
def release(self, merchant_id: str, key: str) -> None: ...
def idempotent(merchant_id: str, key: str, body: dict, store: KeyStore,
work: Callable[[], Outcome]) -> tuple[int, Any]:
request_hash = hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest()
if not store.claim(merchant_id, key, request_hash):
existing = store.get(merchant_id, key)
if existing.request_hash != request_hash:
return 422, {"error": "idempotency key reused with different parameters"}
if existing.status == "in_progress":
return 409, {"error": "a request with this key is still being processed"}
return existing.response_code, existing.response_body # replay
try:
outcome = work()
except Exception:
outcome = Outcome("unknown") # a crash mid-flight is also an unknown outcome
if outcome.kind == "final":
store.complete(merchant_id, key, outcome.code, outcome.body)
return outcome.code, outcome.body
if outcome.kind == "retryable":
store.release(merchant_id, key)
return outcome.code, outcome.body
return 202, {"status": "processing"} # recovery worker completes the key laterKey takeaways
- Correctness, not throughput, is the hard part: design for exactly-once effects across systems you do not control.
- Make every hop idempotent (client keys, processor keys from attempt ids, event-id dedupe, unique ledger source ids) and treat unknown outcomes as a real state.
- Model a payment as a state machine with guarded, atomic transitions that also write ledger entries and outbox events.
- Use a double-entry, append-only ledger: every transaction sums to zero, balances are derived, mistakes are reversed, never edited.
- Reconcile daily against processor reports and bank statements; it is the safety net that catches what idempotency misses.
- Store money as integers in minor units with an explicit currency, and keep card data out of your systems with tokenization.
Common pitfalls
- Retrying a timed-out authorization with a new idempotency key, which can charge the customer twice.
- Using floats for amounts, or assuming every currency has two decimal places.
- Keeping balances in a mutable column updated in place, with no entry-level history to audit or reconcile.
- Sending webhooks directly from request handlers, so events are lost on crashes or sent for rolled-back changes.
- Letting raw card numbers touch application servers or logs, pulling the whole system into PCI scope.
Interview tips
- Start with the four-party card model and the authorize, capture, settle timeline; it shows you know the domain.
- Walk through the timeout scenario unprompted: unknown state, same idempotency key, recovery worker, reconciliation.
- Write one balanced ledger transaction on the whiteboard with real numbers.
- Keep the estimate short: QPS is small, so spend the time on correctness, not sharding.
Real-world applications
- Stripe popularized idempotency keys in a public payments API, models payments as PaymentIntents with explicit statuses, and documents signed webhooks retried for up to three days.
- Airbnb described avoiding double payments with an idempotency library (Orpheus) that splits each request into pre-RPC, RPC and post-RPC phases.
- Square described Books, an immutable double-entry accounting service used as a ledger of record.
- TigerBeetle is an open-source database built specifically for double-entry financial accounting at high throughput.
- Adyen, Braintree and other PSPs support idempotency keys or merchant references for safe retries, which is what makes the processor hop idempotent.
Test yourself
An authorization request to the processor times out. What should the payment service do?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.