Payment and Transaction Processing Systems Questions
Designing systems that move money correctly: idempotent payment flows, exactly-once semantics, reconciliation, ledgers, double-entry accounting, and fraud-detection architecture. Covers handling retries and partial failures without double-charging, and the consistency guarantees payments demand. Also covers protecting cardholder data through tokenization and PCI scope reduction, reconciling processor webhooks, and merchant and partner payouts. A high-stakes specialization of distributed transactions.
Design the payment processing portion of a booking marketplace that charges guests only after a reservation is confirmed. The system must handle payment authorization, capture, retries, webhook callbacks from a third-party processor, and avoid charging twice if requests are retried. How would you make the flow reliable and auditable?
Sample Answer
Direct answer
Make the booking's payment an explicit state machine stored in our own database, and make every call to the processor carry an idempotency key derived from the booking and the operation (for example booking-8841:capture), so a retry can only ever repeat the same operation, never create a new one. Place an authorization (a hold on the guest's card) when the guest requests the booking, capture (actually take the money) only when the host confirms, and treat the processor's webhooks (HTTP callbacks it sends when something changes) as signed, possibly duplicated, possibly out-of-order hints that move the state machine forward only. A reconciler compares our state to the processor's on a schedule, and every transition is appended to an immutable audit log.
Requirements and assumptions
- Guest requests a stay; the host has up to 24 hours to accept. The guest must be charged only after acceptance, and must never be charged twice.
- Card payments through a third-party processor (a PSP, payment service provider, such as Stripe or Adyen) that supports separate authorization and capture, idempotency keys and webhooks.
- Load (assumed): 300,000 bookings/day, about 3 processor API calls and 5 webhooks each. That is 300,000 x 5 / 86,400 = about 17 webhooks/second on average and about 170/second at a 10x peak. Throughput is modest; correctness under retries and partial failure is the real design problem.
Why authorize first, capture on confirmation
- Authorizing at request time proves the card works and reserves the funds before the host spends effort accepting; capturing only at acceptance satisfies "charge only after confirmation". Declining the booking releases the hold (cancel the authorization), so the guest is never charged.
- Authorizations expire. Stripe documents a 7-day validity window for customer-initiated online card payments (Visa's merchant-initiated window is shorter, just under 5 days). With a 24-hour acceptance window this fits comfortably.
- What would change it: if confirmation can take longer than the hold lasts (a request-to-book held for weeks, or charging close to check-in), do not rely on a hold. Instead, save the card at request time with the guest's consent and create a new charge off-session (while the guest is not present, a merchant-initiated transaction) at confirmation, handling the case where the bank asks for the guest to authenticate again.
State machine
stateDiagram-v2
[*] --> AUTH_PENDING
AUTH_PENDING --> AUTHORIZED: auth approved
AUTH_PENDING --> FAILED: declined
AUTHORIZED --> CAPTURE_PENDING: host accepts
AUTHORIZED --> VOIDED: host declines or timeout
CAPTURE_PENDING --> CAPTURED: capture confirmed
CAPTURE_PENDING --> NEEDS_REVIEW: capture failed or unknown
CAPTURED --> REFUNDED: cancellation refund
Rules that make it reliable:
- Transitions are compare-and-set (an update that succeeds only if the row is still in the state the caller last saw):
UPDATE payment SET state='CAPTURE_PENDING', version=version+1 WHERE booking_id=$1 AND state='AUTHORIZED' AND version=$2. If zero rows change, someone else already moved it; we read the current state instead of acting again. - One payment row per booking (unique constraint on
booking_id), so two concurrent "accept" clicks or two worker instances cannot open two payments. - States only move forward. A late webhook saying "authorized" after we recorded "captured" is ignored.
*_PENDINGstates are durable intent. We write the intent before calling the processor, so if the process crashes mid-call, a sweeper (a background job that periodically scans for stuck rows and resumes or resolves them) finds the pending row and resumes with the same idempotency key.
The flow
sequenceDiagram
participant G as Guest
participant B as Booking service
participant P as Payment service
participant X as Processor
G->>B: Request to book
B->>P: authorize(booking 8841)
P->>X: create auth, key booking-8841:auth
X-->>P: requires_capture (authorized, awaiting capture)
Note over B: Host accepts
B->>P: capture(booking 8841)
P->>X: capture, key booking-8841:capture
X--xP: timeout
P->>X: retry with same key
X-->>P: succeeded (replayed)
X->>P: webhook payment succeeded
P->>P: dedupe by event id, state already CAPTURED
Avoiding double charges
- Deterministic keys. The key for each processor call is
booking_id + operation(plus a refund ID for refunds), not a fresh random value per HTTP attempt. Stripe, for example, stores the first result for a key and replays it for later requests with the same key, and rejects reuse with different parameters; keys can be pruned after at least 24 hours, so a retry must happen well inside that window, and anything older is resolved by querying the processor instead of resending. - Retry only what is safe. Network timeouts and 5xx server errors mean "outcome unknown": retry with the same key, or look the payment up. A decline (a 4xx card error) is a final answer: do not retry it with a new key. Stripe also advises treating a 500 as indeterminate, which is exactly why the reconciler exists.
- Outbox for side effects. Writing "captured" and emitting "send receipt" or "credit host payout" happens in the same database transaction via an outbox table (rows a relay, a background process that polls this table and publishes each row to its destination with retries, publishes afterward), so the ledger and the notifications cannot diverge.
Webhook handling
- Verify the signature over the raw request body (HMAC, a keyed hash, with the endpoint's secret) and reject stale timestamps; Stripe's libraries default to a 5-minute tolerance.
- Persist, then acknowledge. Insert the raw event into an inbox table (a durable store of every event received, keyed by its ID, so a redelivered event can be recognized as a duplicate instead of reprocessed) keyed by the processor's event ID (
ON CONFLICT DO NOTHING) and return 2xx immediately; a worker processes it. Stripe retries undelivered webhooks for up to three days in live mode and does not guarantee order, so the handler must tolerate both duplicates and reordering. - Apply as a hint, confirm with a read. For a state-changing event the worker fetches the current object from the processor and applies it through the same forward-only transitions. That makes order irrelevant: whichever event arrives, we move to the latest truth.
Reliability and auditability
- Reconciler (every 5 to 15 minutes): finds payments stuck in a
*_PENDINGstate beyond a threshold and queries the processor; findsAUTHORIZEDbookings approaching the hold expiry and either captures (if accepted) or voids them; also surfaces every payment inNEEDS_REVIEWto a payments-operations queue, since a failed or ambiguous capture needs a human to check the processor's own record and manually move the row toCAPTURED,VOIDEDor a refund, rather than being auto-resolved. - Daily settlement reconciliation: matches every captured payment and refund against the processor's settlement report (what was paid out, minus fees). Unmatched lines become breaks for the payments-operations queue.
- Ledger: captures and refunds are posted as double-entry ledger lines (every movement has debits and credits summing to zero): guest cash in, host payable, platform fee revenue. The host's payout is released from the host-payable balance after check-in, which also leaves room for cancellations.
- Audit log: an append-only
payment_eventtable with every request (key, parameters, response code, processor object ID), every webhook (event ID, type, payload hash), every transition (from, to, actor, reason) and timestamps. It answers "why was this guest charged 412.00 at 14:02" without guesswork. - Monitoring: alert on the age of the oldest pending payment, webhook signature failures, reconciliation break counts, and the ratio of captures to accepted bookings (it should be 1.0).
Worked failure scenario
Host accepts booking 8841 at 14:02. Tracing the version counter from the start: the row was created at version 1 in AUTH_PENDING, moved to version 2 when the authorization was approved, and now moves AUTHORIZED -> CAPTURE_PENDING at version 2 to 3 as the host accepts; the capture call for 412.00 times out after 10 seconds. The worker retries at 14:02:11 with key booking-8841:capture; the processor had in fact captured the first time and replays the stored success. Row moves to CAPTURED. At 14:02:14 the succeeded webhook arrives for the first time; the inbox inserts it as a new event, since there is nothing to dedupe yet, and the worker fetches the payment, sees it is already CAPTURED from the earlier retried capture call, and records "no-op" because the state machine only moves forward. An hour later a duplicate delivery of that same event arrives and is this time dropped by the event-ID unique key before it ever reaches the worker. Result: one charge of 412.00, and an audit trail (two transitions, two capture requests, the webhook and its duplicate) that explains every step.
Trade-offs and pitfalls
- Charging immediately and refunding on decline is simpler but shows guests a charge and a refund, costs fees, and violates "charge only after confirmation". Authorize-then-capture is worth its extra state.
- Trusting the browser redirect as proof of payment is wrong: the guest can close the tab. The webhook plus a server-side read is the source of truth.
- Business logic inside the webhook HTTP handler causes timeouts, which cause processor retries, which cause load: persist and return fast.
- Random idempotency keys per attempt defeat the purpose; the key must identify the operation, not the HTTP request.
- Partial capture (capturing less than authorized, for example after a discount) is supported by many processors, but usually only once per authorization; design refunds, not second captures, for later adjustments.
Describe an architecture to handle temporary network outages between your payment service and external processors so customers can still attempt checkout safely and data is not lost. Include durable queueing, retry/backoff strategies, user messaging patterns, duplicate prevention, and how failed payments are surfaced and processed once connectivity is restored.
Sample Answer
Direct answer
The design hinges on separating two situations that look identical from the outside: a payment request that was never sent to the processor, and one that was sent but the answer never came back. Never-sent requests are safe to queue durably and retry later, even on a different processor. Sent-but-unknown requests must only ever be retried with the same idempotency key (a unique ID attached to one payment attempt, so a repeated send carrying it is recognised as that same attempt rather than charged again) against the same processor, or resolved by asking that processor for the payment's status, because the customer may already have been charged. Around that core: persist every payment attempt and its outbound message in one database transaction (a transactional outbox: a table in the same database that records what still needs to be sent, written in the same transaction as the payment row so the two can never disagree), have workers send with exponential backoff and jitter behind a circuit breaker, tell the customer honestly that payment is pending, and drain the backlog at a controlled rate when the processor comes back.
Architecture
flowchart TD
CO[Checkout] --> API[Payment service]
API -->|one DB transaction| DB[(Payments + outbox)]
DB --> W[Submitter workers]
W --> CB{Circuit breaker}
CB -->|closed| PSP[Processor]
CB -->|open| WAIT[Stay queued]
PSP -->|timeout| UNK[Status: unknown]
UNK --> INQ[Status inquiry job]
INQ --> PSP
W -->|attempts exhausted| DLQ[(Dead-letter queue)]
DLQ --> OPS[Ops console]
API --> NOTIFY[Customer notifications]
1. Durable intake: the transactional outbox
When the customer clicks Pay, the payment service writes, in one database transaction, the payment row (status = pending_submission, amount, currency, order) and an outbox row ("submit payment 881 with processor key pay_881_a1"). If the service crashes a millisecond later, both exist or neither does. A separate worker reads the outbox and makes the external call. This is what "data is not lost" means concretely: the source of truth is our database, not an in-memory queue and not the processor.
The processor idempotency key is generated once per attempt and stored on the payment row, before anything is sent. Every retry of that attempt reuses it.
2. Payment states
| State | Meaning | Allowed next action |
|---|---|---|
pending_submission | Durably recorded, not yet sent | Send; may route to a backup processor |
submitted | Request on the wire | Wait for response |
unknown | Sent, no answer (timeout, connection reset) | Status inquiry, or retry with the same key to the same processor |
authorized / failed | Definitive answer | Continue the order, or ask for another payment method |
needs_attention | Retries exhausted | Human review via the ops console |
The unknown state is the heart of duplicate prevention. It is never converted into failed by a timer, and never re-sent with a new key or to a second processor, because that is exactly the path that creates a second charge.
3. Retry and backoff
Transient faults are retried with exponential backoff (each wait double the last) capped at a maximum, with full jitter (each wait is a random value between zero and the computed delay) so that thousands of queued payments do not all retry in the same second when the processor recovers.
With a 1-second base, doubling, and a 5-minute cap, the maximum delays before each of the first 12 retries are 1, 2, 4, 8, 16, 32, 64, 128, 256, 300, 300, 300 seconds. The cumulative worst case after the 12th retry is 1,411 seconds, about 23.5 minutes. I cap automatic retries at that point for a customer-present checkout (the customer is watching the page in real time, as opposed to a payment being retried later by a background job with nobody waiting on it); after it the payment moves to needs_attention and the customer is told.
A circuit breaker sits in front of the processor. Its two main states borrow their names from an electrical circuit, which reads backwards to most people: closed means current (here, traffic) flows normally, and open means the circuit is broken and nothing gets through. So when the error rate over a sliding window (the failure rate measured over just the last minute or so, not since the service started, so an old problem cannot keep tripping the breaker forever) crosses a threshold, the breaker trips open and stops sending for a cooldown period, then lets a few probe requests through (a small number of real requests, sent on purpose to test whether the processor has actually recovered before trusting it with the full backlog). While open, work stays in the outbox instead of burning retries against a dead endpoint.
Retry only what is retryable: timeouts, connection errors, 5xx responses and explicit "try again" declines. A hard decline (insufficient funds, stolen card) is a definitive answer, not an outage.
4. User messaging
A customer cannot be told "paid" until there is an authorization. The pattern I use:
- For a short blip, the checkout waits a few seconds (a synchronous retry within the page's own timeout) and most customers never notice.
- Beyond that, the order is accepted as "Payment processing": inventory is reserved for a bounded time (say 30 minutes), the confirmation page says the order is received and that an email will confirm payment, and the Pay button is disabled for that order so the customer cannot start a second attempt.
- When the payment resolves, the customer gets a confirmation, or a link to try another payment method if it failed. If it never resolves within the reservation window, the reservation is released and the customer is told.
For high-risk or instantly delivered goods (gift cards, digital downloads) I do not accept the order pending payment; the customer sees "payment provider temporarily unavailable, please try again shortly", because delivering first and failing to collect is a direct loss.
5. Recovery and draining the backlog
When the circuit closes again, that is, the breaker judges the processor healthy and lets traffic flow normally once more, the backlog built up while it was open must drain without tripping the processor's rate limits or causing a second outage.
Worked example: a 30-minute outage at 50 payment attempts per second queues 50 × 1,800 = 90,000 payments. If the processor contract allows 200 TPS (transactions per second) and live traffic is 50 TPS, the drain can use 150 TPS: 90,000 ÷ 150 = 600 seconds, so the backlog clears in about 10 minutes. The drain order is: resolve every unknown first by status inquiry (those customers may already have been charged), then oldest pending_submission first, with live traffic always taking priority over backlog.
Before sending a queued payment, the worker re-checks that it is still wanted: the order was not cancelled, the customer did not pay with another method in the meantime, and the reservation has not expired.
6. Surfacing failures
Payments that exhaust retries, return unexpected responses or fail status inquiry land in a dead-letter queue (DLQ: a holding queue for messages that could not be processed automatically) and appear in an ops console with the full attempt history, processor responses and the order. Ops can re-drive them (same key), cancel them, or trigger customer outreach. Metrics and alerts: queue depth, oldest pending age, count in unknown, DLQ arrivals per minute.
7. Failover to a second processor
Failover is valuable for availability, but only pending_submission payments may move to a backup processor. An unknown payment on processor A that is resent to processor B can be charged by both, and no idempotency key spans two companies.
Trade-offs and pitfalls
- Queueing in memory (or in a broker without the database write, a broker being a standalone message-queue service such as SQS or RabbitMQ that the payment service writes to but that is not itself the source of truth) loses payments on a crash; the outbox costs one extra insert per payment and removes that class of loss.
- Treating timeouts as declines is the single most common source of double charges in this scenario.
- No jitter turns recovery into a synchronised retry storm that knocks the processor back over.
- Accepting orders pending payment trades conversion for credit risk; the reservation window and the product categories it applies to are business decisions to make explicitly.
- Unbounded retries mean a customer is charged hours later for an order they assumed failed and bought elsewhere; cap them and communicate.
Explain what idempotency means in payment processing. Provide concrete examples of problems that arise without idempotency (for example duplicate charges and duplicate fulfillment) and outline high-level strategies to implement idempotency across stateless, horizontally scaled services.
Sample Answer
Direct answer
An operation is idempotent if doing it twice has the same effect as doing it once. In payments that property has to be engineered, because "charge this card 50 USD" is naturally not idempotent: sending it twice charges twice. Duplicates are unavoidable (networks drop responses, clients retry, users double-click, message queues redeliver), so the system must recognise a repeat of the same intent and return the first result instead of acting again. In a horizontally scaled service that recognition cannot live in any one server's memory; it has to live in shared, durable state, usually a unique idempotency key stored alongside the payment and passed on to the processor.
Where duplicates come from
| Source | What happens | Why it is not a bug you can simply fix |
|---|---|---|
| Lost response | Server charged the card, the response died on a flaky mobile network, the app retries | The client cannot tell "never arrived" from "arrived, answer lost" |
| Impatient user | Double-click on Pay, or refresh on the confirmation page | Humans retry when things look slow |
| Load balancer or gateway retry | A proxy retries a request that timed out upstream | Retries are how distributed systems survive transient faults |
| Message redelivery | A queue delivers "payment succeeded" twice | Most queues are at-least-once (every message arrives, some more than once), because exactly-once delivery across a network is not achievable in general |
| Webhook replay | The PSP (payment service provider) resends an event because your endpoint was slow to acknowledge | Same at-least-once contract |
Problems without idempotency
- Duplicate charges. Two charge requests, two captures, one angry customer, a refund, and quite possibly a dispute.
- Duplicate fulfilment. A "payment succeeded" event processed twice ships two parcels or issues two gift-card codes. This one is often worse than a double charge because the goods are gone.
- Duplicate refunds or payouts. Money leaves the platform twice and must be clawed back.
- Corrupted ledger (the running record of every debit and credit). The same transaction posted twice means balances, revenue reports and reconciliation (matching two independent records of the same money to confirm they agree) are all wrong, and the error is discovered days later.
Strategies for stateless, horizontally scaled services
"Stateless" means any request can land on any of, say, 40 identical instances. So the memory of "I have seen this before" must be in a shared store, and the check-and-act must be atomic.
- Client-generated idempotency key. The client creates a random unique ID (for example a UUID, a universally unique identifier drawn from 122 random bits) once per payment attempt, stores it, and sends the same value on every retry. The server treats the key as the identity of the intent.
- Unique constraint, not check-then-insert. "SELECT to see if the key exists, then INSERT" lets two instances both see "not found" at the same moment. A database unique index on the key (scoped per merchant or per user) makes exactly one insert win.
- Store and replay the result. When the first request finishes, save its status code and body against the key. A retry gets the saved response, byte for byte, instead of a fresh execution.
- Fingerprint the request. Store a hash of the request body with the key. The same key with a different amount is a client bug, and should be rejected rather than silently replayed.
- Propagate the key downstream. When calling the processor, pass a key derived from yours. Then even if your service crashes between calling the processor and recording the result, the re-driven call cannot charge twice.
- Idempotent consumers for events. A service consuming "payment succeeded" records the event ID in a processed-events table in the same database transaction as its side effect. A redelivered event hits the unique constraint and is skipped.
- Make state transitions conditional. "Mark order shipped where status = 'paid'" is naturally idempotent: the second attempt matches zero rows. Modelling a payment as a state machine with legal transitions gets you a lot of idempotency for free.
Worked example
Maya taps Pay for a 50.00 USD order on a train.
Without a key: request 1 reaches the server, the card is charged, the response is lost in a tunnel. The app shows "Something went wrong", Maya taps Pay again, request 2 charges another 50.00. Her statement shows 100.00; support refunds 50.00; she may also have filed a dispute with her bank.
With a key: the app generated key 7f3c... when the order was created. Request 1 inserts the key, charges the card through the processor using the same key, stores 201 {payment_id: pay_881}. The retry with 7f3c... hits the unique constraint, finds the stored response and returns pay_881. One charge, and Maya sees "Paid".
And if the retry arrived while request 1 was still talking to the processor, it would find the key in an "in progress" state and get a "try again shortly" answer rather than starting a second charge.
Trade-offs and pitfalls
- Idempotency is not exactly-once. The request may still arrive and be checked several times; idempotency makes the effect happen once. People call this "effectively once".
- A key generated on each retry is useless. The key must be created once per intent and persisted on the client before the first attempt.
- Keys expire. Stores keep keys for a bounded window (Stripe documents that keys can be pruned once they are at least 24 hours old), so a retry after that window is treated as new.
- Scope matters. A key unique per merchant is fine; a key unique only per server instance is not.
- Do not cache failures you should retry. Decide deliberately whether a stored error is replayed or whether a retry is allowed to try again; validation errors and "conflict, still in progress" are usually not stored.
Your primary payment processor experiences an extended outage. Design a disaster recovery plan that ensures merchants can continue accepting payments (or degrade gracefully), eventual settlement and reconciliation occur correctly, fees and mapping are handled for backup processors, and customers and regulators are informed as required.
Sample Answer
Direct answer
Plan for three things in order: keep taking payments by routing new authorizations to a pre-integrated backup processor (and degrading payment methods that cannot move), never lose or double-count money by freezing every in-flight transaction with the primary as "unknown" until the primary can be asked what happened, and settle and reconcile per processor afterwards, because each processor pays out, charges fees and reports in its own way. Communication runs on a pre-agreed clock: merchants and customers through status pages and API signals within minutes, regulators and card-scheme partners according to their incident-reporting obligations.
Key terms
- Processor / PSP (payment service provider): the company that sends card authorizations to the card networks and later pays out the money.
- Authorization: the issuing bank approves and places a hold on funds. Capture: the merchant claims the held funds. Settlement: the processor actually transfers the money, usually a day or more later, minus fees.
- Reconciliation: matching what your own records say should have happened against what processors and banks report did happen.
- Circuit breaker: logic that stops sending traffic to a failing dependency once errors cross a threshold, then probes it periodically.
- MID (merchant ID): the identifier a processor or acquirer assigns to a merchant account; the backup needs its own.
What must exist before the outage
A DR (disaster recovery) plan for payments is mostly work done in advance:
- A second processor, integrated and warm (fully set up and already carrying a slice of live traffic, not sitting idle). Signed contract, underwriting completed (the processor's own review and approval of your business before it will process for you), MIDs issued for every merchant you intend to fail over, and a small share of live traffic (for example 2 to 5%) routed there permanently, so you know it works today, not in theory.
- Portable card credentials. Tokens issued by the primary processor do not work at the backup. Stored cards (subscriptions, one-click checkout) can only fail over if you hold network tokens (issued by the card networks, usable across processors) or run your own vault that can send card data to either processor. Without that, only customers typing a card fresh can pay through the backup.
- A mapping layer. A table per processor translating your internal payment methods, currencies, merchant category codes (MCCs, the standard 4-digit codes that classify what kind of business a merchant is), statement descriptors (the text that shows up on the cardholder's statement), decline codes and 3-D Secure (the card-holder authentication step) settings into that processor's vocabulary. Divergence here (for example a merchant category code the backup does not recognise, or a decline code mapped to the wrong retry behavior) is what turns a failover into a flood of declines.
- A routing service with per-processor health, a circuit breaker, and a manual override switch.
During the outage
flowchart TD
A[New payment] --> B{Primary healthy?}
B -- yes --> C[Primary processor]
B -- no --> D{Card usable at backup?}
D -- yes --> E[Backup processor]
D -- no --> F[Offer other method or retry later]
G[In-flight at primary when it failed] --> H[State: unknown, no retry elsewhere]
H --> I[Resolve via primary status query or settlement report]
- Route new authorizations to the backup once the breaker opens. Keep the idempotency key (the client's unique ID for this payment attempt) as your internal reference so each processor call is traceable to one payment.
- Do not replay in-flight payments at the backup. A request that timed out at the primary may have been approved there. Retrying it at the backup risks charging the customer twice. Mark it
unknown, tell the merchant the outcome is pending, and resolve it once the primary answers status queries or its settlement file arrives. - Captures, refunds and voids follow the original processor. An authorization made at the primary can only be captured or refunded through the primary. Queue these operations durably and drain them when the primary returns; if an authorization would expire first (online card authorizations are typically valid for about 7 days), decide per merchant whether to re-authorize at the backup.
- Degrade gracefully. Recurring charges on non-portable tokens are deferred and retried later rather than failed; merchants see a clear "processing delayed" status rather than hard declines. For card-present terminals, offline "store and forward" approvals (the terminal approves the sale itself on the spot, with no live authorization call, then submits it for real authorization once connectivity returns) under a low per-transaction limit are possible but the merchant carries the risk of later declines; enable it only where merchants opted in.
- Protect the backup. Ramp traffic gradually and watch approval rates; a sudden jump in volume can trigger the backup's own fraud controls.
After the outage: settlement and reconciliation
- Reconcile per processor. Each processor's settlement report is matched against your ledger (your internal, append-only record of money movements) for the transactions it handled. The routing decision is recorded on every payment, so each payment belongs to exactly one processor's reconciliation.
- Resolve every
unknown. For each, the primary either reports it approved (keep it, capture as normal) or never received or declined it (mark failed, and if the customer retried and succeeded at the backup, there is no double charge to unwind). Any real duplicate found is refunded proactively. - Different payout timing. The backup may pay out a day later, to a different bank account, with different fee deductions. Merchants' payout projections and your treasury forecast (the internal projection of cash moving in and out of the business) must show this explicitly.
- Chargebacks and disputes (a customer disputing a charge through their bank) for backup-processed payments arrive from the backup for months afterwards; the dispute system must know to look there.
Fees and who pays them
Fees differ between processors, so decide in advance whether the platform absorbs the difference or passes it on. Illustrative numbers (assumed contract rates, not any real vendor's price list):
- A merchant processes 2,000,000 USD per day, spread evenly, at an average ticket of 50 USD. A 6-hour outage moves 6/24 of that, 500,000 USD, or 10,000 payments, to the backup.
- Primary rate 2.2% + 0.10 USD: 11,000 + 1,000 = 12,000 USD.
- Backup rate 2.9% + 0.30 USD: 14,500 + 3,000 = 17,500 USD.
- Extra cost of the outage: 5,500 USD for this merchant.
Most platforms absorb this for short outages (it is small against lost sales and merchant trust) and write the rule into their merchant terms so it is not negotiated during an incident.
Communication
| Audience | When | What |
|---|---|---|
| Merchants | Within minutes of routing change | Status page, API status field on affected payments, dashboard banner: what works, what is delayed, whether payouts shift |
| Customers | Via merchants | Clear "payment pending" messages, never "failed" for an unknown outcome |
| Backup processor | Before ramping | Warn them of volume so their risk controls do not block it |
| Card schemes (another name for the card networks, such as Visa or Mastercard) and acquiring partners (the banks or institutions that hold your merchant accounts with those networks) | Per contract | Incident notices where agreements require them |
| Regulators | Per jurisdiction | Where the platform is a regulated payment institution (licensed by a financial regulator to move customers' money, not just a software vendor), major operational incidents are reportable within fixed deadlines measured in hours to days (for example, under the EU's DORA, the Digital Operational Resilience Act, for financial entities). Legal and compliance own the filing; engineering supplies the timeline and impact numbers |
Trade-offs and pitfalls
- Cost of warmth. Keeping a second processor live costs contract minimums and engineering on two integrations, but a cold backup is almost always broken when needed.
- Automatic vs manual failover. Automatic failover reacts in seconds but can flap (switch back and forth rapidly as health checks briefly pass, then fail, then pass again) on a partial outage and send traffic to the backup that the primary would have approved. A common compromise: automatic for hard failures (connection refused, sustained 5xx), human decision for soft degradation (elevated latency, falling approval rate).
- The dangerous mistake is converting timeouts into failures and retrying them elsewhere. That produces the double charges that customers remember long after the outage.
- Approval rates will drop on the backup (new MIDs, no transaction history, different issuer relationships). Plan and tell merchants; do not treat it as a new incident.
Design how your payments platform will support multi-currency transactions: how currency selection happens at checkout, where exchange rates are sourced, timing of conversion (pre-authorization vs settlement), how you store both display and accounting currency, and how reporting and dispute handling should account for FX differences.
Sample Answer
Direct answer
Treat every multi-currency payment as three amounts that must never be confused: the presentment amount (what the shopper sees and is charged, in their currency), the settlement amount (what the payment provider actually pays you, in your payout currency) and the accounting amount (what your books record, in your functional currency: the single currency a legal entity keeps its accounts in, normally the currency of the country where it primarily operates). Lock an exchange rate at checkout with a short expiry, charge the shopper in the presentment currency so the authorization and the capture use the same number, record the quote that produced it, and book the difference between the quoted and the realized conversion as an explicit FX (foreign exchange) gain or loss line. Refunds and disputes are always paid back in the presentment currency, so the FX difference on them is a cost you must model, not a rounding error.
Requirements I am designing to
- A marketplace or merchant platform selling in one base (price-list) currency, USD in the example, to shoppers in 30+ currencies.
- Shopper-facing: see a final price in their currency before paying, and be charged exactly that.
- Finance-facing: every entry reproducible later (which rate, from where, at what time), month-end reports in one functional currency, and correct tax per locale.
- Money is stored as an integer count of minor units (cents, yen) plus an ISO 4217 currency code, never as a float. The minor-unit exponent differs by currency: JPY has 0 decimals, EUR 2, and a few (such as KWD, the Kuwaiti dinar) have 3.
1. Currency selection at checkout
- Default from the shopper's billing country or saved preference, with a picker to override. Geolocation (IP address) is only a hint; the card's issuing country and the billing address are better signals.
- Only offer currencies you can actually charge and settle. A currency your PSP (payment service provider, such as Stripe or Adyen) cannot process for that payment method must not appear in the picker.
- Two different mechanisms, do not mix them up:
- Multi-currency pricing: you price and charge in the shopper's currency. The shopper's bank sees a local-currency charge and applies no conversion. This is the design below.
- DCC (dynamic currency conversion): the shopper is shown a conversion at the moment of payment of a charge that would otherwise be in the merchant's currency, and chooses. It is regulated (the shopper must be shown the rate and the choice) and often a poor deal for the shopper, so treat it as a separate product decision.
2. Where rates come from
- A Rate Service pulls mid-market rates (the midpoint between the buy and sell price in the currency market, with no markup added) from one or two providers (a market-data vendor, a bank, or the PSP's own FX quotes) on a schedule, for example every 60 seconds for majors (heavily-traded currencies like EUR, GBP or JPY) and less often for thin currencies (low-volume currencies where quotes are sparser and move in bigger jumps).
- Every stored rate row is immutable:
rate_id, base, quote, mid_rate, source, fetched_at. A new fetch is a new row; nothing is updated in place. - Guards: reject a new rate that moves more than a threshold (say 3%) from the previous one without a second source agreeing; if every source is stale beyond a limit, stop offering that currency rather than charging on an old rate.
- The shopper rate is mid rate times (1 + spread). The spread is a product and pricing decision (it pays for FX risk and provider fees) and is stored with the quote so it is auditable.
3. When the conversion happens (pre-authorization vs settlement)
Authorization is the bank's real-time approval and hold; capture is you confirming the amount to collect; settlement is the provider paying you days later.
| Option | What it means | Who carries FX risk | When I would pick it |
|---|---|---|---|
| Quote locked at checkout, charge in presentment currency (recommended) | Rate fixed when the price is shown, valid for a short TTL (time-to-live, for example 15 minutes). Authorization and capture both in the shopper's currency. | The platform, from checkout until the provider converts at settlement | Default for consumer checkout: the shopper sees exactly what they pay |
| Convert at settlement | Charge in the shopper's currency, but price your own books from the settlement-day rate only | Still the platform, just unmeasured | Never as the only record: you lose the ability to explain variance |
| Charge in merchant currency, let the issuer convert | Authorization in USD; the shopper's bank converts at its own rate | The shopper (their statement amount can differ from what the checkout showed) | Only for B2B (business-to-business) or when you cannot support the currency |
Rule: the rate must be fixed before authorization and the captured amount must not be re-converted. If the capture is delayed (ship later, booking confirmed later), the presentment amount stays the same and only the settlement conversion moves. That moving part is exactly what the FX variance line measures.
4. Storing display and accounting currency
CREATE TABLE fx_quote (
fx_quote_id uuid PRIMARY KEY,
rate_id uuid NOT NULL, -- the mid rate used
shopper_rate numeric(18,8) NOT NULL, -- mid * (1 + spread)
spread numeric(6,4) NOT NULL,
expires_at timestamptz NOT NULL
);
CREATE TABLE payment (
payment_id uuid PRIMARY KEY,
order_id uuid NOT NULL,
presentment_amount bigint NOT NULL, -- minor units, e.g. 9384
presentment_ccy char(3) NOT NULL, -- 'EUR'
base_amount bigint NOT NULL, -- price-list amount, e.g. 10000
base_ccy char(3) NOT NULL, -- 'USD'
fx_quote_id uuid NOT NULL REFERENCES fx_quote,
settlement_amount bigint, -- filled from the provider's settlement report
settlement_ccy char(3),
settlement_rate numeric(18,8),
status text NOT NULL
);
The ledger (an append-only record of money movements using double-entry bookkeeping, where every transaction has debits and credits that sum to zero) records each entry in its transaction currency and its functional currency (USD here), along with the rate used. Recognized revenue, FX spread income and realized FX gain/loss are separate accounts, so finance can see them apart.
5. Worked example (computed in Python with decimal, half-up rounding to cents)
- Price 100.00 USD. Mid rate at checkout: 1 USD = 0.9200 EUR. Spread 2%, so shopper rate = 0.9384 and the display price is 93.84 EUR. At the quote's own mid rate that EUR amount is worth 93.84 / 0.92 = 102.00 USD: 100.00 of revenue plus 2.00 of spread income.
- Converting the checkout mid rate to the same EUR-to-USD direction as the numbers below: 1 ÷ 0.9200 = 1.0870 USD per EUR. The provider settles two days later at 1 EUR = 1.0850 USD, below that 1.0870, meaning EUR weakened against USD between checkout and settlement: 93.84 x 1.0850 = 101.82 USD. Ledger lines: revenue 100.00, FX spread income 2.00, realized FX loss 0.18 (an actual cash-flow loss booked once the money changed hands, as opposed to an unrealized, mark-to-market change on a balance still held) (101.82 minus 102.00).
- Thirty days later the order is refunded in full. The shopper gets back exactly 93.84 EUR (never a re-converted amount). EUR has weakened to 1.0700 USD, so the refund costs 93.84 x 1.07 = 100.41 USD. Across sale and refund the platform keeps 101.82 minus 100.41 = 1.41 USD. This full refund reverses the whole sale, so none of the 2.00 spread income survives and none of the 100.00 revenue does either; what is left is purely the sum of currency movement across checkout, settlement and refund. It is tempting to compute that as spread income minus the settlement loss plus a "refund gain" measured against the checkout rate (2.00 − 0.18 + 1.59 = 3.41, where 1.59 is 102.00 minus 100.41), but that double-counts the checkout benchmark: the only correct calculation is actual cash received at settlement minus actual cash paid at refund, 101.82 − 100.41 = 1.41, because the spread and revenue no longer exist as separately kept amounts once the sale is fully reversed. If EUR had strengthened instead, the same refund would have cost more than was collected.
6. Reporting and disputes
- Reporting: roll up in functional currency using the rate stored on each entry (never today's rate applied to old rows). Show gross sales by presentment currency, spread income, realized FX gain/loss, and, at month-end, unrealized gain/loss (a paper gain or loss on a balance still held, not yet turned into cash, unlike the realized loss above which already was) on balances still held in foreign currency (revalued at the period-end rate).
- Chargebacks (the cardholder's bank reverses a charge on the cardholder's behalf): the disputed amount is in the presentment currency; the provider debits you in settlement currency at the rate on the day of the dispute, which is usually not the original rate. Store the dispute with its own rate and post the difference as FX gain/loss, so dispute losses and FX losses are not blended. When you respond to a dispute, the evidence shows the original presentment amount and the rate the shopper was shown and agreed to.
- Partial refunds are computed in presentment minor units from the original presentment amount, then converted at the refund-day rate for the books.
7. Tax and regulatory differences by locale
- Tax is calculated in the presentment currency on the presentment amount, because that is what appears on the shopper's receipt and what the tax authority expects. EU VAT (value-added tax) is usually shown tax-inclusive to consumers, US sales tax is added at checkout and varies by state and locality, Australia's and India's GST (goods and services tax) have their own registration thresholds.
- A tax engine (in-house rules or a tax provider) takes seller location, buyer location, product category and date, and returns rate and amount. Store the tax lines with the transaction and on the receipt.
- Some jurisdictions require invoices or tax reporting in the local currency even if you settle in USD; keep the presentment amounts, never only the converted ones.
- Currency controls: a few currencies cannot be settled offshore or have restrictions on refunds to other currencies. Encode a per-currency capability table (can present, can settle, refund rules) rather than scattering special cases.
8. Rolling out a new currency (phased)
- Configuration: add the currency to the capability table (minor-unit exponent, rounding rule, supported payment methods, tax registration), disabled.
- Offline tests: property tests (automated tests that generate many random inputs and check an invariant holds for all of them, rather than checking one fixed example) on money arithmetic (for any split, the parts sum exactly to the whole in minor units), a replay of last month's orders priced in the new currency, and end-to-end tests against the provider's test mode.
- Shadow mode: compute and log the new-currency prices for real traffic without showing them; compare against expectations.
- Canary: enable for a small share of shoppers in one country behind a feature flag (a runtime switch that turns code paths on for a chosen audience), watch authorization rate, refund and dispute rates, and daily reconciliation (matching your ledger against the provider's settlement report) for that currency.
- Widen, keeping a kill switch that falls back to base-currency pricing if rates go stale or reconciliation breaks.
flowchart LR
RS[Rate Service] --> Q[FX quote with TTL]
Q --> CO[Checkout: presentment price]
CO --> AUTH[Authorize and capture in presentment ccy]
AUTH --> PSP[Provider settles in payout ccy]
PSP --> REC[Reconciliation]
CO --> L[Ledger: presentment + functional amounts]
REC --> L
L --> RPT[Reports: spread, realized and unrealized FX]
Trade-offs and pitfalls
- Floats and "convert, then convert back". 0.1 + 0.2 in floating point is not 0.3; and converting 93.84 EUR back to USD at a different rate never returns 100.00. Store the original amounts and derive, never round-trip.
- Rounding per line vs per total. Convert the order total once, then allocate to line items with a largest-remainder split (round every line down to the nearest cent, then hand the leftover pennies to the lines with the largest fractional remainder, one cent each, until the total matches exactly) so the lines still sum to the charged total.
- Rate at authorization but capture much later. Locking gives the shopper certainty and gives you risk. For long gaps (a booking captured weeks later) either widen the spread for that product or settle in the shopper's currency and hold a balance in it.
- Recomputing reports with today's rate. It silently rewrites history; always use the rate stored with the entry.
- What would change the design: if the business settles in many currencies (holds EUR balances and pays EUR costs), FX exposure is naturally hedged (gains on one side offset losses on the other, so net exposure to rate movement is small) and you can drop the settlement conversion for those currencies entirely; if volumes are small, using the provider's built-in conversion and simply recording its reported rates is a reasonable first version.
Unlock Full Question Bank
Get access to all 37 Payment and Transaction Processing Systems interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.