Design: payment system
Record the payment intent, call the PSP with an idempotency key, and post the outcome as balanced double-entry ledger entries; webhooks and daily reconciliation against PSP reports catch whatever the synchronous path missed.
Fundamentals you'll use
How it works
- Card data goes straight to the PSP through hosted fields; you store only tokens, keeping PCI scope small.
- Persist the payment before calling the PSP, and reuse one idempotency key for every retry.
- The ledger is append-only double-entry: each transaction sums to zero; fix mistakes with reversing entries.
- A timeout is unknown, not failed: retry with the same key or ask the PSP before deciding.
- Daily reconciliation against PSP and bank reports catches what webhooks and retries missed.
Check yourself
Answer to mark it learned; your answers aren't scored.
The PSP charge call times out after 30 s. A teammate proposes marking the payment FAILED and showing "Payment failed, try again". What should the system do?
Go deeper
Full explanation
Requirements
Functional: charge a customer's card through a payment service provider (PSP) such as Stripe or Adyen, support refunds and payouts to sellers, report balances. Non-functional: never charge twice or lose a charge, every cent auditable, card numbers never touch our servers. Assume 10M payments/day ≈ ~115/s average, ~10× at peak.
Questions I'd ask: marketplace with payouts? Which currencies and payment methods? Do we keep cards on file? What does finance need for settlement and reporting?
High-level design
The browser enters card details in PSP-hosted fields and we receive a token, which keeps PCI scope small. POST /payments carries an Idempotency-Key; the payment service stores a payment row (PENDING) before any external call, then calls the PSP with the same key. The outcome moves a state machine (PENDING → SUCCEEDED or FAILED) and is posted to the ledger: append-only, double-entry, where each transaction's entries sum to zero. Balances are sums of entries; mistakes are fixed with new reversing entries, never edits. Amounts are integers in minor units (cents). PSP webhooks settle anything still pending.
The hard parts
Exactly-once is an illusion. With retries, delivery is at least once; you get effectively once from idempotency at every hop. The client key dedups our API, the same key dedups the PSP call, processed event IDs dedup webhooks, and state changes are conditional (PENDING → SUCCEEDED happens once). A timeout means unknown, not failed: retry with the same key or ask the PSP; never start a fresh attempt.
Reconciliation. Daily, match every ledger entry against the PSP settlement report and the bank statement. Mismatches, such as a charge with no ledger entry, an amount that differs or a payment stuck in PENDING, go to a queue for automatic fixes or finance review.
Code Idempotent charge and a balanced ledger posting
# Amounts are integers in minor units (cents); UNIQUE(idem_key) on payments.
def create_payment(db, psp, key: str, order_id: str, amount: int, token: str) -> dict:
with db.tx():
found = db.one("SELECT id, state FROM payments WHERE idem_key = %s", key)
if found:
return found # client retry: same answer, no new charge
pay = db.one("INSERT INTO payments (idem_key, order_id, amount, state) "
"VALUES (%s, %s, %s, 'PENDING') RETURNING id, state", key, order_id, amount)
try:
res = psp.charge(amount, token, idempotency_key=key) # same key on every retry
except TimeoutError:
return pay # unknown, not failed: webhook or poll settles it
return settle(db, pay["id"], res)
def settle(db, pay_id: int, res) -> dict:
with db.tx():
state = "SUCCEEDED" if res.ok else "FAILED"
n = db.run("UPDATE payments SET state = %s WHERE id = %s AND state = 'PENDING'",
state, pay_id)
if n == 1 and res.ok: # first writer wins: API reply or webhook
commission = res.amount // 10 # assumed 10% marketplace take
post(db, pay_id, [ # debits +, credits -
("psp_receivable", res.amount - res.fee),
("psp_fee_expense", res.fee),
("seller_payable", -(res.amount - commission)),
("platform_revenue", -commission),
])
return db.one("SELECT id, state FROM payments WHERE id = %s", pay_id)
def post(db, pay_id: int, entries: list[tuple[str, int]]) -> None:
assert sum(amount for _, amount in entries) == 0, "unbalanced journal entry"
for account, amount in entries:
db.run("INSERT INTO ledger_entries (payment_id, account, amount) "
"VALUES (%s, %s, %s)", pay_id, account, amount)Real example
A $100 order on a marketplace that takes 10%, with an assumed PSP fee of $3.20. The customer double-clicks Pay: both requests carry key chk_8812, and the second gets the same PENDING payment back. The PSP call times out, so the payment stays PENDING. Two minutes later the success webhook flips it to SUCCEEDED and posts four entries: PSP receivable +$96.80, fee expense +$3.20, seller payable −$90.00, revenue −$10.00, which sum to zero. The webhook arrives again; its event ID is already processed, so it's ignored. Next morning, reconciliation matches $96.80 in the PSP settlement report.
Trade-offs +3 · −3
+ You gain
- Idempotency at every hop makes retries safe, so the system can retry aggressively.
- An append-only double-entry ledger makes every cent traceable and unbalanced bugs visible.
- Hosted fields keep card data, and most PCI controls, out of your systems.
− You pay
- Asynchronous outcomes (3-D Secure, webhooks) force a state machine and a pending UX.
- Reconciliation is permanent operational work with finance in the loop.
- Ledger writes need strong consistency per account, which caps throughput on hot accounts.
Use it when
Any product that moves money: checkout, marketplaces with payouts, subscriptions, wallets.
Avoid it when
A simple single-merchant store: use the PSP's hosted checkout and dashboard. Build your own ledger when you hold funds, split payments or need audit-grade reporting.
Numbers to know 5
- Assume 10M payments/day ≈ ~115/s average; plan ~10× for peak sales events.
- Stripe API v1 (Nov 2026): idempotency keys up to 255 chars, prunable after ≥ 24 h.
- Stripe retries webhooks for up to 3 days in live mode, with no ordering guarantee (Nov 2026).
- Handling raw card numbers can mean 300+ PCI DSS security controls (Stripe's guide, Nov 2026).
- Ledger volume: 10M payments × ~4 entries ≈ 40M rows/day, ~15B/year (assumption).
Common pitfalls 4
- Floats for money: 0.1 + 0.2 ≠ 0.3. Use integer minor units plus a currency code.
- A new idempotency key per retry: every retry becomes a new charge.
- Treating a PSP timeout as a failure and letting the customer pay again.
- Updating balances in place with no entries: no audit trail, and no way to find the bug.
Interview questions 3
Answer out loud first, then reveal.
How do you guarantee a customer is never charged twice?Show answer
I can't get exactly-once delivery, so I make every effect idempotent. The client sends one key per checkout attempt; my API stores it under a unique constraint and replays the stored result. I pass the same key to the PSP, so its retries collapse too. Webhooks dedup on event ID, and the PENDING → SUCCEEDED transition is conditional, so it happens once. Reconciliation then catches anything that slipped through.
Why a double-entry ledger instead of a balance column?Show answer
A balance column tells you the number, not why. In double-entry, every movement is two or more entries that sum to zero, so a bug can't create or lose money unnoticed: unbalanced postings are rejected. Balances are derived from entries, which gives a full audit trail, and corrections are new reversing entries. It also maps line by line to PSP and bank reports, which makes reconciliation possible.
The PSP is down for 20 minutes. What happens?Show answer
Calls fail fast behind a circuit breaker, and affected payments stay PENDING, not FAILED. If I have a second PSP, I route new payments there, but never re-route one whose first attempt might have succeeded until its status is known. Where the business allows, I accept the order and charge when the PSP recovers. Afterwards, reconciliation confirms every PENDING payment ended in exactly one final state.
Deep dive 3
Idempotency end to end
The client generates one key per checkout attempt (a UUID) and reuses it on every retry. The server stores it with a UNIQUE constraint and a hash of the request, and replays the stored result; same key with different parameters is an error, as in Stripe's API. The same key goes to the PSP: Stripe's v1 API saves the first response for a key, including 500 errors, and may prune keys after 24 h, so your own table keeps them longer. Webhooks can repeat and arrive out of order: store processed event IDs and never infer order from timestamps.
The double-entry ledger
Accounts model where money sits: PSP receivable, seller payable, fee expense, platform revenue. A journal entry moves money between at least two accounts and must sum to zero, so a bug can't create or destroy money silently. Entries are append-only: Square's Books service fixes mistakes by writing a new correcting entry, never by editing. Balances are derived sums, cached per account with a version for fast reads. Store amounts as integers in minor units with a currency: Stripe takes 1099 for $10.99 and 500 for ¥500, since JPY has no decimals.
Reconciliation and the unknown state
Run a three-way match daily: ledger versus PSP settlement report versus bank statement. Each mismatch type has a playbook: charged at the PSP but missing here (a lost webhook) is posted from PSP data; recorded here but unknown to the PSP is voided; amounts that differ point to fees or FX; PENDING older than a threshold triggers a status query. Hold seller payouts until their payments reconcile. Track the unreconciled amount as a metric with an alert; it is the system's real correctness SLO.