Design Payments
Design a Stripe-like payment system in a 45-minute interview: idempotency keys end to end, a payment state machine, a double-entry ledger, retries, reconciliation and PCI scope.
On this page
How to use this page
This page follows the order of a real system design interview. At each step there is a Your turn box: write your own answer first, then open ours and compare. Payments is the classic "correctness, not scale" interview: the traffic is modest, and almost every question is some form of "what happens if this call fails halfway?"
| Phase | Time in a 45-min interview | What you produce |
|---|---|---|
| 1. Clarify requirements | 5 min | What money moves where, what is out of scope, the correctness targets |
| 2. Estimate | 3–5 min | Payments/s at peak, money per day, ledger growth |
| 3. API | 5 min | Create, read, refund, webhooks, and the idempotency key |
| 4. Data model | 5 min | Payments, ledger, idempotency keys, vault, outbox |
| 5. High-level design | 10 min | Boxes and arrows, and the charge flow traced through them |
| 6. Deep dives | 10–15 min | Double charges, crashes mid-call, the ledger, reconciliation, PCI |
| 7. Wrap up | 2–3 min | Bottlenecks, failures, what you would monitor |
Merchants call our API to charge a customer’s card, refund it, and get notified of the result. We talk to external payment processors and keep accurate records, and pay merchants out daily. Skip fraud models in detail, subscriptions and invoicing, and becoming a bank ourselves.
1. Clarify the requirements
The interviewer says: "Design a payment system like Stripe." Write down the questions you would ask, 4–6 functional requirements, 4–6 non-functional requirements with a target, and what you would leave out.
Compare with our answer
The questions that matter most: Are we the merchant (one shop) or the platform that serves many merchants? Cards only, or bank transfers and wallets too? Do we hold money and pay merchants out? One currency or many? Do we build fraud detection? Then agree the list below.
A strong answer mentions: create and refund payments · notify merchants of results · a ledger of every money movement · payouts and reconciliation · "no double charge, no lost record" as the top requirement · fraud and subscriptions out of scope.
Functional: what it must do
- Create a payment: Charge a card for an amount and currency
- Refunds: Full or partial
- Payment status and webhooks: Merchants notified of success or failure
- Ledger: Every movement of money recorded
- Payouts: Merchants paid daily, minus fees
- Reconciliation: Match our records with the bank’s
Out of scope
Detailed fraud modelsSubscriptions and invoicingBeing a bank
Non-functional: how well it must work
| Quality | Target | Why |
|---|---|---|
| Correctness | No double charges; balances always add up | Money mistakes are unacceptable |
| Durability | No payment record ever lost | |
| Availability | 99.99%+ for the API | Checkouts everywhere depend on it |
| Latency | A few seconds per charge is fine | External networks dominate |
| Security | Card numbers never stored raw (PCI DSS) | Tokenise; isolate the card vault |
| Auditability | Every change traceable forever | Regulators and disputes |
Two terms you will use all interview. A PSP (payment service provider, or processor) is the company that connects us to the card networks (Visa, Mastercard) and the banks; we never talk to a card network directly in this design. Authorisation asks the customer's bank to reserve the money; capture asks for it to be actually moved, and settlement is the money arriving, usually one or two days later in a batch file.
2. Back-of-the-envelope estimates
Assume 100 million payments a day, a peak of 5× the average, an average payment of $50, and 4 ledger entries of 200 bytes per payment. Work out peak payments per second, money moved per day and ledger growth per year. What do the numbers tell you about where the design effort should go?
Compare with our answer
- Average: 100 M ÷ 86,400 ≈ 1,160/s. Peak at 5×: ≈ 5,800/s.
- Money: 100 M × $50 = $5 B a day. A 0.01% error rate is $500 K a day.
- Ledger: 100 M × 4 × 200 bytes = 80 GB/day, ≈ 30 TB a year, kept for many years.
A strong answer mentions: thousands per second, which a sharded SQL database handles · the money figure, which is why correctness dominates · the ledger growing forever (append-only, so partition by time) · external calls taking hundreds of milliseconds to seconds, which sizes concurrency rather than CPU.
Assumptions: payments per day 100 M; peak vs average 5; average payment ($) 50; ledger entries per payment 4; ledger entry size 200 B.
| Number | Estimate | Why it matters |
|---|---|---|
| Payments per second (peak) | 5.79 K / s | ≈ 5,800/s at peak: not huge, but each must be exact. |
| Money moved per day ($) | 5 B | $5 B a day: a 0.01% error is $500 K. |
| Ledger growth per year | 29.2 TB | ≈ 30 TB a year, kept forever (append-only). |
- Throughput is modest; correctness, durability and auditability are the real challenges.
- The ledger is append-only: never update or delete money records, only add correcting entries.
The lesson of the numbers: this is not a scale problem. 5,800 writes a second fits a handful of sharded Postgres or MySQL primaries. The hard part is that each of those writes involves an external call that can hang, fail, or succeed without telling us.
3. API
Which calls does a merchant need? Which of them move money, and what must every money-moving call carry?
Compare with our answer
A strong answer mentions: POST /payments with an Idempotency-Key header · a refund call, also with a key · GET for status · webhooks pushed to the merchant, with an event id they can de-duplicate · card details tokenised by our own JavaScript or SDK so they never pass through the merchant's servers.
| Call | Request | Response | Notes |
|---|---|---|---|
POST /v1/payments | { amount, currency, paymentMethod (token), merchantId } + Idempotency-Key header | 201 { paymentId, status } | Retrying with the same key returns the same payment |
GET /v1/payments/{id} | – | { status, amount, events[] } | |
POST /v1/payments/{id}/refunds | { amount } + Idempotency-Key | 201 { refundId } | Partial refunds allowed |
POST {merchant webhook URL} | { type: payment.succeeded, data } | 2xx | We retry webhooks with backoff until acknowledged |
POST /v1/tokens | card details (from our JS/SDK, never via merchant servers) | { token } | Keeps merchants out of PCI scope |
The API is HTTP and synchronous for the merchant, but the payment itself is a small state machine: created → processing → succeeded | failed, then possibly refunded (fully or in part). Real card flows often split succeeded into authorised and captured (a hotel authorises at check-in and captures at check-out); mention it, then keep the simpler model unless asked.
4. Data model
What tables do you need? Which ones must be strongly consistent, which are append-only, and where do card numbers live?
Compare with our answer
A strong answer mentions: payments as a state machine in a relational database · a unique constraint on (merchant, idempotency key) · an append-only double-entry ledger · a separate, encrypted card vault · an outbox table for webhooks · sharding by merchant so one merchant's data and keys live together.
payments Strongly consistent SQL (sharded by merchant)
payment_id, merchant_id, amount, currencystatus, psp_referenceidempotency_key (unique per merchant)created_at, updated_at
A state machine: created → processing → succeeded / failed → refunded. Transactions and conditional transitions.
ledger Append-only, double-entry (SQL)
entry_id, txn_idaccount (customer_funds, merchant_balance, fees, …)amount (+/−), currency, created_at
Every movement is two entries that sum to zero: debit one account, credit another. Balances are derived, never edited.
idempotency keys SQL (same transaction as payment) or Redis + DB
merchant_id + key → payment_id, response, request_hash
Store key → request hash and response, so retries return the original result.
card vault Isolated, encrypted store (HSM-backed)
token → encrypted PAN, expiry
Raw card numbers live only here, in a tightly audited PCI zone; everything else uses tokens.
webhook outbox SQL table + retry scheduler
event_id, merchant_id, payload, attempts, next_attempt_at
Notifications must eventually reach merchants, even if their server is down for hours.
Three design decisions shape this model:
- The idempotency key and the payment row are written in one database transaction. If they lived in different stores, a crash between the two writes would leave a key with no payment (retry blocked) or a payment with no key (retry charges again). A unique index on
(merchant_id, idempotency_key)makes the database itself reject the duplicate. - The ledger is append-only. Rows are never updated or deleted; mistakes are fixed with new, correcting entries. Balances are computed from entries, never stored as the only copy.
- The vault is a separate system. Raw card numbers (the PAN, primary account number) exist only there, encrypted with keys held in an HSM (hardware security module, a tamper-resistant device that holds keys and never reveals them). Everything else stores a token such as
tok_42.
5. High-level design
Sketch the boxes for a card charge: where is the key checked, when is the payment row written relative to the processor call, where does the card number come from, and how does the merchant learn the result?
Compare with our answer
Compare with the figure. The things people most often miss: writing the payment as processing before calling out, the vault sitting between us and the processor, and an outbox for webhooks instead of an HTTP call inside the request.
The architecture, then a charge traced through it
- The architecture: an API gateway in front of a payment service that owns the payment state machine. It uses an idempotency store, an isolated card vault, and talks to external processors. Every money movement goes into a double-entry ledger, webhooks go out through an outbox, and reconciliation and payouts run against the ledger.
- A charge: the gateway checks the idempotency key, the payment row is created in “processing”, and the vault swaps the card token for the real card number and sends it to the processor. When the result comes back, the payment is updated and ledger entries are written in the same transaction, then a webhook is queued.
| Component | What it does |
|---|---|
| API gateway | Auth, rate limits, request validation |
| Payment service | State machine; calls processors; writes payment + ledger atomically |
| Idempotency store | Key → original response |
| Card vault | PCI zone; tokens in, raw cards never leave |
| PSP / card network | Visa/Mastercard via acquirers and processors |
| Ledger | Append-only double-entry records; balances derived |
| Webhook sender | Outbox + retries with backoff |
| Reconciliation | Matches our records with external settlement files |
| Payouts | Pays merchants from ledger balances |
Trace the charge out loud:
- The merchant calls
POST /v1/paymentswith keyK. The gateway authenticates and rate-limits. - The payment service inserts the payment as
processingand the keyKin one transaction. If the insert hits the unique index, this is a retry: go to the replay path. - It asks the vault to authorise
tok_42for $50. The vault decrypts the PAN inside the PCI zone and calls the PSP, passing our payment id as the PSP's idempotency reference. - The PSP answers "approved". In one transaction the service moves the payment to
succeeded, writes the ledger entries, stores the response againstK, and adds apayment.succeededrow to the outbox. - The webhook sender delivers the outbox event to the merchant, retrying until it gets a 2xx.
6. Deep dives
Two or three sentences each: how do you make sure a merchant's retry never charges twice? What do you do if you crash after sending the authorisation but before saving the answer? How do you prove that every cent is accounted for?
Compare with our answer
A strong answer mentions:
- An idempotency key stored atomically with the payment, a request fingerprint to catch key reuse, and our own key towards the PSP.
- Saving state before every external call, so an unknown outcome is visible and a recovery job can ask the PSP.
- A double-entry, append-only ledger and nightly reconciliation against settlement files.
- Exactly-once is an effect we build from retries plus de-duplication at every hop, not something the network gives us.
Double charges: idempotency keys end to end
A merchant's request times out after we charged the card. They retry. Without protection, the customer pays twice.
| Option | How | Catch |
|---|---|---|
| Tell merchants not to retry | Document it | Timeouts are normal, and a merchant that doesn't retry loses sales |
| Match on amount and card | "Same card, same amount, last minute = duplicate" | Blocks genuine repeat purchases (two coffees) and misses retries after a minute |
| Idempotency key (chosen) | Merchant sends a unique key; we store it with the payment and replay the stored result | Keys must be stored atomically with the payment, and every hop needs its own key |
A merchant retries with the same key and gets the original result
- The merchant’s request times out and they retry with the same key. We find the key, see the original payment, and return its result without calling the processor again. The customer is charged once.
The key alone is not enough. Three details make it safe:
- Two requests with the same key at the same time. The second one must not start a second charge while the first is still running. The unique index stops the second insert; return
409 Conflict("a request with this key is in progress") and let the merchant retry later. - Same key, different request. A buggy merchant reuses a key for a $70 payment. Store a hash of the request body with the key and return an error if a retry doesn't match, instead of silently replaying the $50 result.
- Every hop needs a key. Merchant → us uses the merchant's key. Us → PSP uses our payment id (or a derived id per attempt) as the PSP's idempotency reference. Us → merchant webhooks carry an event id. Payouts to banks carry a payout id. A chain is only as idempotent as its weakest hop.
The general pattern is covered in duplicates and idempotency.
Crashing mid-payment: the state machine and recovery
We sent the authorisation, then our server died before saving the answer. Did the customer pay? We don't know, and neither guess is safe: assuming "failed" invites a second charge on retry; assuming "succeeded" ships goods for free.
The record already says processing, so a recovery job asks the processor
- If we crash mid-payment, the record already says “processing”, and a recovery job asks the processor what really happened.
The rule is write state before every external call:
- Insert the payment as
processing(with our reference) and commit. - Call the PSP with a timeout (a few seconds to tens of seconds; card authorisations usually take one to three seconds).
- Update the state with a conditional write:
UPDATE payments SET status='succeeded' WHERE id=? AND status='processing'. If zero rows change, someone else already moved it, so do nothing.
A recovery job scans for payments stuck in processing for longer than a minute or two and asks the PSP "what happened to reference pay_123?" Then it continues the state machine. If the PSP never received the request, it is safe to retry with the same reference; if the PSP says "approved", we write the success and the ledger entries we missed.
| Outcome of the PSP call | What we know | What we do |
|---|---|---|
| Clear approve or decline | The truth | Conditional update, ledger, webhook |
| Error before sending (connection refused) | Nothing was sent | Retry with the same reference, with backoff |
| Timeout or connection reset after sending | Unknown | Leave as processing; recovery queries the PSP |
When the bank wants the customer: 3-D Secure and requires_action
In the EEA and the UK, strong customer authentication (SCA, a PSD2 rule) requires most customer-initiated online card payments to be confirmed with two of three factors: something the customer knows (a PIN), has (their phone) or is (a fingerprint). The card protocol for it is 3-D Secure (3DS2 today). We send risk data (device, amount, history) to the card issuer, the bank that issued the card, which either approves without bothering anyone (the frictionless flow) or demands a challenge: the customer confirms in their banking app or types a one-time code.
A challenge breaks the "one request in, one answer out" model, because the payment now waits on a human for seconds or minutes. So the state machine gains a state:
created → processing → requires_action → processing → succeeded | failed
- The authorisation attempt returns "challenge required". We save
requires_actionwith the 3DS session details and return it to the merchant, with a URL or client secret for our SDK to show the bank's screen. - The customer completes (or abandons) the challenge. The result reaches us by a redirect or a callback from the 3DS server.
- We move the payment back to
processingand send the authorisation with the authentication result attached, then finish as usual.
Details that matter:
- The recovery job must not treat
requires_actionas stuck. It is waiting on the customer; give it its own timeout (say 15 to 60 minutes) after which it becomesfailed(orcancelled) and the merchant gets a webhook. - Exemptions skip the challenge: low-value payments (under €30, with cumulative limits), merchant-initiated charges such as subscription renewals after the first payment was authenticated, and low-risk payments under transaction risk analysis. The issuer can still insist on a challenge.
- Liability shift: if a payment was authenticated with 3DS and later disputed as fraud, liability generally moves from the merchant to the issuer, which is why merchants accept the extra step.
- Merchants must handle
requires_actionfromPOST /paymentsand rely on the webhook for the final result. A merchant integration that only checks "succeeded or failed" silently loses European sales.
Authorise now, capture later: holds expire
The hotel example splits a payment into authorisation (the issuer reserves the amount on the customer's card, a hold) and capture (we ask for the money to actually move). A hold does not last for ever. For most online card payments the networks treat an authorisation as valid for roughly 7 days; it varies by network, by card-present or online, and by merchant category, and lodging and car rental can use special authorisation types valid for up to around 30 days. After that, the issuer releases the hold, and a late capture may be declined, cost a higher fee, or lose a chargeback dispute for "no valid authorisation".
So anyone who captures late needs a plan:
| Situation | Problem | What to do |
|---|---|---|
| Hotel, 10-night stay | Check-out is after the hold expires | Use the lodging authorisation type and incremental authorisations as the bill grows |
| Marketplace that ships in 2 to 14 days | Some orders ship after 7 days | Capture when shipped; for orders approaching expiry, re-authorise (a new hold, which may now decline) and void the old one, or capture up front and refund if unfulfilled |
| Rider or rental deposit | Final amount is unknown | Authorise an estimate, then capture the final amount (a partial capture releases the rest) |
In the design this means an auth_expires_at column per payment, a scheduler that acts a day or two before it, and voiding holds you won't use, so the customer's money isn't tied up for a week.
Currency: minor units, FX and rounding once
Amounts are stored as an integer number of minor units plus an ISO 4217 currency code: 5000 USD is $50.00. The number of decimals differs by currency: the yen has none (5000 JPY is ¥5,000), the dollar and euro have two, and the Kuwaiti dinar has three. Look the exponent up from a table; never assume two.
FX conversion (foreign exchange: changing one currency into another) happens when a customer pays €50.00 and the merchant settles in US dollars. Record it as an explicit ledger transaction through FX accounts, with the rate and its source and time: psp_receivable +5000 EUR, fx:EUR −5000 EUR, fx:USD +5416 USD, merchant −5416 USD at 1.0832 (fees left out, and this page's sign convention, so the merchant's negative is money owed to them). Entries must sum to zero per currency, never across currencies. The rate quoted to the customer is locked with the payment, and the gap between it and the rate at settlement is the platform's FX gain or loss, which reconciliation must explain.
Round once, at the edge. A 2.9% fee on $10.99 is 31.871 cents. Keep exact decimal arithmetic through the calculation and round to a minor unit exactly once, when the ledger entry is created, with a stated rule (half-up or half-even, as the contract says). Rounding at every intermediate step drifts by a cent here and there, and at 100 M payments a day those cents become reconciliation breaks. When splitting, allocate remainders so parts sum to the whole: $100.00 three ways is 3,333 + 3,333 + 3,334 cents.
Recording money: the double-entry ledger
(Convention used on this page: debits are positive and credits negative, so money the platform owes a merchant appears as a negative number, such as merchant −48.25.)
A balance column that you update (balance = balance + 48.25) is easy to corrupt: two concurrent updates can lose one, and once overwritten, the old value is gone. Accountants solved this centuries ago with double-entry bookkeeping: every movement of money is a transaction of two or more entries, debits and credits, that sum to zero.
A charge and a refund as ledger entries
Properties you get for free:
- Errors are visible. If the sum of all entries isn't zero, something wrote one side only. A nightly (or continuous) check catches it.
- History is never lost. A refund, chargeback or correction is a new transaction. You can answer "what was this merchant's balance on 3 March?" by summing entries up to that date.
- Balances are derived.
SELECT SUM(amount) FROM ledger WHERE account = 'merchant:m_9'(negative under this page's convention, meaning the platform owes the merchant that much). For speed, keep a balance snapshot per account (for example daily) and add only newer entries.
Use integers in the smallest currency unit (cents) or a decimal type, never floating point: 0.1 + 0.2 is not 0.3 in binary floating point.
A hot account
Every charge credits the platform's fee_revenue account. If you keep a running balance row for it, every payment updates the same row and they queue on its lock. Fixes: don't update balances inline at all (derive them from entries asynchronously), or split the hot account into N sub-accounts (fee_revenue:0 … fee_revenue:15) chosen at random and summed when read. This is the same trick as in hot keys and hot partitions.
Telling the merchant: reliable webhooks
The merchant's server is down for an hour when the payment succeeds. Sending the webhook once, from inside the request, loses it.
The fix is the transactional outbox: the payment.succeeded event is inserted into an outbox table in the same transaction as the state change, so the event exists if and only if the change does. A sender process reads the outbox and POSTs to the merchant, retrying with exponential backoff for up to a few days. Payloads are signed (an HMAC of the body with a per-merchant secret) so the merchant can reject forgeries, and carry an event id because delivery is at-least-once. Merchants can also list events through the API as a fallback. Per-merchant queues stop one slow endpoint from delaying everyone else.
Proving it: reconciliation
Our ledger says what we think happened. The PSP and the banks send settlement files (daily reports of what was actually captured, refunded, charged back and paid). Reconciliation matches them line by line against the ledger.
Nightly reconciliation against settlement files
- Every night, reconciliation compares our ledger with the settlement files from processors and banks. Anything that doesn’t match, a missing or extra charge, becomes a case for investigation and a correcting entry.
Every mismatch, called a break, is a case: a charge the PSP has but we don't (our crash recovery missed it), one we have but the PSP doesn't, or an amount that differs (fees, currency conversion). Breaks are fixed with correcting ledger entries, never edits, and payouts for affected merchants are held until resolved.
Card data and PCI scope
PCI DSS is the card industry's security standard; any system that stores, processes or transmits card numbers is "in scope" and must be audited against it. The goal is to make that scope as small as possible.
- The customer types the card into our JavaScript or mobile SDK (an iframe on the merchant's page), which sends it straight to our vault and returns a token. The merchant's servers never see the number, which keeps the merchant's own PCI burden small.
- The vault is a tiny, separately deployed, heavily audited service with HSM-held keys. The payment service, ledger and logs hold tokens only.
- Never log request bodies on the vault path, and scrub card-like numbers from logs everywhere else.
7. Bottlenecks, failures and monitoring
Scaling bottlenecks
| Bottleneck | Fix |
|---|---|
| Processor latency and outages | Multiple processors; circuit breakers; route by success rate |
| Ledger growth | Partition by time/account; it’s append-only so it shards well; snapshots of balances |
| Hot merchant (a big sale) | Shard by merchant; idempotency keys scoped per merchant |
| Webhook backlog | Per-merchant queues so one slow merchant doesn’t delay others |
When things fail
| Failure | What happens |
|---|---|
| Crash after calling the processor | Payment stays “processing”; recovery job queries the processor and completes it |
| Processor down | Fail over to another processor; or return a clear retryable error |
| Ledger imbalance detected | Alert; freeze affected payouts; fix with correcting entries, never edits |
| Merchant webhook endpoint down | Retries with backoff for up to several days |
What to monitor
Authorisation success rate per processorPayments stuck in processingLedger balance checks (must be zero-sum)Reconciliation mismatchesWebhook delivery lagDuplicate-key hits
Routing across several PSPs adds availability (fail over when one is down) but also means a payment's attempt history can span processors, so every attempt needs its own reference and the recovery job must query the right one. Circuit breakers stop a failing PSP from tying up all your threads; see circuit breakers and retries.
8. Follow-up questions
Answer in order. 1) The PSP times out on an authorisation and the merchant retries 5 seconds later with the same key. Walk through exactly what happens. 2) Finance says yesterday's ledger and the PSP's settlement file differ by $1,240. How do you find out why? 3) You must add a second PSP and route by success rate. What changes in the design?
Compare with our answer
A strong answer mentions:
- The payment is still
processing; the unique key finds it; we return 409 or the current "pending" status, not a new charge; recovery queries the PSP by our reference and finishes the state machine; the merchant learns the result by webhook or a later GET. - Match line by line by PSP reference; classify breaks (missing on our side, missing on theirs, amount differs); check fees, FX and timing (a charge just before midnight in a different cut-off); fix with correcting entries and hold affected payouts.
- Each attempt gets its own id and records which PSP it used; recovery and reconciliation are per PSP; a router with health and success-rate data plus circuit breakers; never retry the same attempt on a second PSP unless the first is known to have failed, or you risk two authorisations.
How would you add fraud checks?
A risk service scores each payment before authorisation (rules + ML); risky ones get 3-D Secure or are blocked.
How do multi-currency payments work?
Convert at a locked rate, record both currencies in the ledger with FX accounts, settle per currency.
Why not use one big distributed transaction with the bank?
You can’t: banks and card networks are external. Instead you use idempotency, state machines and reconciliation.
More senior follow-ups
- Payouts. A daily job computes each merchant's available balance from the ledger (minus a reserve for refunds and chargebacks), creates a payout with its own idempotent id, and records the transfer as ledger entries. The bank's confirmation file reconciles it.
- Chargebacks. The customer's bank reverses a payment weeks later. It arrives in a file or webhook from the PSP, becomes a new ledger transaction debiting the merchant, and a webhook tells the merchant.
- Multi-region. Keep each merchant's payments and ledger in one home region with synchronous replicas, so a failover doesn't lose a committed payment. Active-active writes for the same merchant make idempotency checks much harder.
- Sagas. A checkout that reserves stock, charges and ships is a saga with compensations (refund if shipping fails), not a distributed transaction.
- Numbers: 100 M payments/day ≈ 5,800/s at peak; $5 B/day; ledger ≈ 30 TB/year. Correctness, not scale.
- Idempotency key per merchant request, unique with the payment row in one transaction, plus a request hash; 409 for a concurrent duplicate.
- Every hop idempotent: merchant key → our payment id to the PSP → event id on webhooks → payout id to banks.
- State machine:
processingsaved before calling out; conditional updates; a recovery job asks the PSP about stuck payments. Never guess. - Timeouts are unknown outcomes, not failures.
- Double-entry ledger: entries sum to zero; append-only; balances derived, with snapshots; integer cents.
- Webhooks: transactional outbox, signed, retried for days, event ids for de-duplication.
- Reconciliation against settlement files is the final word; breaks become correcting entries.
- PCI scope: tokenise in our SDK, isolated vault with HSM keys, tokens everywhere else.
- SCA / 3-D Secure: a challenge puts the payment in
requires_action(its own timeout, not "stuck"); exemptions for low value and merchant-initiated charges. - Holds expire (~7 days for most online card payments): track
auth_expires_at, capture or re-authorise in time, void unused holds. - Currency: integer minor units + currency code (JPY 0, USD 2, KWD 3 decimals); FX as ledger entries that sum to zero per currency; round once.
1. A merchant's charge request times out after we approved it with the PSP. They retry with the same idempotency key while our first request is still finishing. What should the second request do?
The key is stored with the payment, so the duplicate is detected even mid-flight. Starting a second authorisation is exactly the double charge we are preventing.
2. A merchant reuses the same idempotency key for a $50 payment and, an hour later, a $70 payment. What is the right behaviour?
Replaying $50 silently hides a merchant bug and they believe $70 was charged. Storing a request fingerprint with the key lets you fail loudly.
3. We sent an authorisation to the PSP and the connection reset before any response. The payment row says processing. What next?
A reset after sending is an unknown outcome. Guessing either way is wrong; querying by our reference finds the truth, and a resend must reuse the same reference.
4. Why is a merchant's balance computed from ledger entries instead of stored in one column that each payment updates?
An append-only, double-entry ledger makes errors visible as imbalances and lets you rebuild any past balance. Snapshots keep reads fast.
5. A $50 charge with a $1.75 fee is recorded. Which set of entries is a valid double-entry transaction?
It is the only set that both sums to zero and records the fee where every cent went (an entry set that leaves the fee in a separate log can also sum to zero, but the books no longer explain the money). The fee belongs in the same transaction, not a separate log.
6. The webhook to a merchant is sent from inside the payment request, right after the database commit. What is wrong?
The transactional outbox stores the event in the same transaction as the state change, and a separate sender retries it until acknowledged.
7. Which change shrinks PCI DSS scope the most for both us and our merchants?
Scope is decided by where raw card numbers travel. If only the vault ever sees them, everything else, including merchant servers, handles tokens only.
8. A marketplace authorises cards at checkout and captures when sellers ship. Some sellers take 10 days. What goes wrong, and what is the fix?
Holds last roughly 7 days for most online card payments, after which a late capture may be declined or lost in a dispute. Track the expiry and capture, re-authorise or capture up front.
Score 60% or more and the lesson is marked complete.