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.
Explain the difference between tokenization and encryption when protecting cardholder data. Describe how tokens are generated and mapped to PANs, where the mapping and encryption keys ideally live, and how tokenization can reduce PCI footprint while supporting use cases like recurring payments.
Sample Answer
Direct answer
Encryption transforms the card number with a key; anyone with the key can mathematically reverse it, so the encrypted value is still card data and the systems holding it (and the keys) stay in audit scope. Tokenization replaces the card number with a random substitute that has no mathematical relationship to it; the only way back is a lookup in a separately secured token vault. Systems that hold only tokens, and cannot ask the vault to reverse them, can be taken out of scope for most of the card-security standard. That is why merchants store tokens for recurring billing instead of card numbers.
Key terms
- PAN (primary account number): the card number, typically 13 to 19 digits in practice (the ISO/IEC 7812 standard allows 8 to 19); most Visa, Mastercard and Discover cards use 16, American Express uses 15, and some older Visa cards use 13.
- PCI DSS (Payment Card Industry Data Security Standard): the security standard every business that stores, processes or transmits card data must meet.
- CDE (cardholder data environment): the systems that touch PANs plus anything connected to them. "Reducing PCI footprint" means shrinking the CDE.
- Detokenization: exchanging a token back for the PAN. Only a few tightly controlled systems should be able to do it.
- HSM (hardware security module): tamper-resistant hardware that stores keys and performs cryptography so the key never leaves it. A cloud KMS (key management service) offers similar key custody as a managed service.
Tokenization vs encryption
| Encryption | Tokenization | |
|---|---|---|
| Relationship to PAN | Mathematical: ciphertext plus key gives the PAN | None: a random value, reversible only through the vault |
| What an attacker needs | The ciphertext and the key | Access to the vault itself |
| Scope effect | For whoever holds or can use the key, the ciphertext is still cardholder data | Systems holding only tokens, with no detokenize access, can be out of scope |
| Typical use | Protecting PANs inside the vault, on disk, and in transit | Letting the rest of the business reference a card safely |
| Format | Ciphertext is usually longer binary data unless format-preserving encryption (encrypting into an output that still looks like a normal card number: same length, same character set) is used | Can be designed to look like a card number (same length, keep last four digits) |
They are complementary: the vault itself encrypts the PANs it stores. Tokenization moves the problem into one small place; encryption protects that place.
How tokens are generated and mapped
- Generate a token from a cryptographically secure random number generator, not from the PAN. A format-preserving token might keep the length and last four digits (useful for receipts and "card ending 4242" screens) and randomise the rest, taking care the result cannot be mistaken for a real, valid card number, for example by deliberately failing the Luhn check (the checksum built into every genuine PAN's last digit, which software uses to catch typos) that a real card number would pass.
- Store the mapping in the vault as
token -> encrypted PAN. The PAN is encrypted with a data key; the data key is itself encrypted by a master key in the HSM or KMS (this is called envelope encryption). - Support lookup by PAN (so the same card gets the same token for a customer, if you want that) with a keyed hash of the PAN, such as an HMAC (a hash combined with a secret key, so only someone holding that key can compute or check it) with a key held in the HSM. A plain unsalted (no random, per-value salt mixed in before hashing, so the same PAN always produces the same output) hash of a PAN is not safe: a 16-digit PAN's first six digits are a public BIN (bank identification number) and its last digit is a Luhn check digit computed from the rest, not random, leaving only about 9 unknown digits, at most 10^9 (one billion) possibilities. Someone who obtains the hashes can precompute all one billion candidates for a known BIN, which is well within reach of ordinary hardware in under a day, and read off which hashes match, so they can be brute-forced.
- Detokenize only for a short list of callers (the service that sends the authorization to the processor), each authenticated, authorised and logged.
Where things should live. The vault, its database and the keys belong in separate security domains: keys in an HSM or KMS whose administrators are not the vault's database administrators, and the vault in its own network segment or cloud account. Stealing the database alone yields ciphertext; stealing a key alone yields nothing to decrypt. Many merchants never run a vault at all: the payment service provider (PSP, the company that processes card payments for the merchant) runs it, and the merchant only ever sees the PSP's tokens.
How this reduces PCI footprint and supports recurring payments
- The customer types their card into a payment form hosted by the PSP (a hosted page or an embedded iframe), so the PAN goes browser to PSP and never reaches the merchant's servers.
- The PSP returns a token such as
pm_1a2b3c. The merchant's database, billing jobs, logs and analytics hold only that token. - For each monthly charge, the merchant's billing job calls the PSP API with the token. The PSP detokenizes inside its own environment and sends the authorization to the card network.
- Because the merchant never stores, processes or transmits the PAN and cannot detokenize, its CDE shrinks dramatically, and its compliance validation becomes far lighter.
Network tokens go one step further: the card networks themselves (for example Visa Token Service and Mastercard's tokenization service) issue a token tied to a merchant, and the network updates it when the physical card is reissued or expires. Recurring billing then keeps working after the customer gets a new card, which reduces involuntary churn.
Worked example
A streaming service bills 2 million subscribers monthly. With encryption only, it would store 2 million encrypted PANs and manage the keys: its database servers, billing workers, backup system and every administrator with key access would be inside the CDE. With PSP tokenization, its database stores pm_... tokens and "Visa ending 4242, expires 08/28" for display. A breach of that database leaks tokens that are useless outside that merchant's PSP account, and cannot be turned into card numbers. The billing job on the 1st of the month submits 2 million charges by token; the PSP holds the only mapping.
Trade-offs and pitfalls
- Tokens are PSP-specific. A token from one PSP does not work at another, which creates lock-in and complicates failover to a backup processor. Network tokens or a PSP-independent vault reduce this, at extra cost or scope.
- "Out of scope" requires that no system can detokenize. If a merchant service has an API credential that can reverse tokens, that service is back in scope.
- Never store sensitive authentication data (the CVV security code, full magnetic-stripe or chip data, PINs) after authorization, whether encrypted or tokenized. PCI DSS forbids it regardless of protection.
- Encryption is not a scope escape for the key holder. Encrypting PANs in your own database is required protection, but if you also hold the keys, those systems are still in scope.
- Card numbers leak sideways. Logs, error messages, support tickets and analytics pipelines are where PANs turn up unexpectedly; scan for them.
A large retailer wants to automatically issue service credits (redeemable through a partner ride or delivery provider's API) to customers when their online orders are delayed. Design a secure, scalable voucher system that generates, distributes, validates, and redeems these credits. Cover anti-fraud controls, idempotency, expiration, region controls, and how you'd reconcile issued and redeemed credits for accounting.
Sample Answer
Direct answer
Model each credit as a stored-value liability (money we owe the customer, sitting on our books as a debt until they spend or lose it) in a ledger (an append-only record of every money movement), not as a string in a table: issuing a credit moves money from "compensation expense" into "credits outstanding", redeeming it moves it from "credits outstanding" to "owed to the partner", and expiry moves it back. Issuance is keyed by the delayed order so a retried or duplicated delay event can never issue a second credit; codes are long random tokens bound to one customer and one region; redemption is an atomic, idempotent state change enforced on our side even though the ride or delivery happens in the partner's app. Finance reconciles three things daily: what we issued, what the partner says was redeemed, and what the partner invoices us.
Requirements and scale
- Trigger: an order misses its promised delivery window by more than a threshold (for example 60 minutes). One credit per order, amount by tier (say 5.00 or 10.00), redeemable only through the partner's API, in the customer's region, within 30 days.
- Scale (assumptions stated so the arithmetic can be redone): 2,000,000 orders/day and 3% late gives 60,000 credits/day (21.9 million a year). A bad-weather evening can put 40% of a day's delays in one hour: 60,000 x 0.4 / 3,600 = about 7 issuances per second. That is small; the hard parts are correctness, fraud and accounting, not throughput.
- With a 30-day expiry about 60,000 x 30 = 1.8 million credits are live at any time.
Architecture
flowchart LR
OMS[Order Management System: delivery late] --> ELIG[Eligibility and risk service]
ELIG --> ISS[Issuance service]
ISS --> DB[(Credit store + ledger)]
ISS --> OUT[Outbox]
OUT --> PAPI[Partner adapter: create credit]
OUT --> NOTIF[Notify customer]
PARTNER[Partner redemption webhook or API call] --> RED[Redemption service]
RED --> DB
DB --> RECON[Daily reconciliation]
PFILE[Partner statement and invoice] --> RECON
- Eligibility and risk service consumes "order delivered" events, compares actual vs promised time, and applies rules (customer not suspended, order not already refunded, caps per customer).
- Issuance service writes the credit, its ledger entries and an outbox row (a table row written in the same database transaction that a relay, a background process that polls this table and publishes each row to its destination with retries, later publishes, so a crash can never leave "credit written but partner never told" or the reverse).
- Partner adapter calls the partner's API to create or load the credit on their side with our credit ID as the partner's idempotency reference, retrying with backoff (waiting longer between each retry attempt rather than immediately retrying again). Partner credentials live in a secrets manager and are scoped to issue and query only.
- Redemption service receives the partner's redemption callback (or answers the partner's synchronous validation call), checks status, region, expiry and owner, and records the redemption.
Generation and distribution
- Generation: the code is created by the issuance service from a cryptographically secure random source at the moment the credit row is written; only its HMAC (hash-based message authentication code: a keyed hash) is stored, and the plaintext exists just long enough to hand to the partner and the notification.
- Distribution: the customer receives it in-app and by push or email as a one-time claim link that attaches the credit to their account on first open; the raw code is shown only as a fallback. Notifications go through the outbox, so a credit is never announced before it exists and never exists silently: a relay retries sends and marks the credit
deliveredonce the partner has confirmed creation and the message has gone out.
Data model
CREATE TABLE credit (
credit_id uuid PRIMARY KEY,
order_id uuid NOT NULL,
reason text NOT NULL, -- 'late_delivery'
customer_id uuid NOT NULL,
region text NOT NULL, -- e.g. 'US-CA'
amount_minor bigint NOT NULL, -- 1000 = 10.00
currency char(3) NOT NULL,
code_hash bytea NOT NULL UNIQUE, -- HMAC of the code, never the code itself
status text NOT NULL, -- issued|delivered|redeemed|expired|revoked
expires_at timestamptz NOT NULL,
partner_ref text,
UNIQUE (order_id, reason) -- the issuance idempotency guarantee
);
Idempotency (issuance and redemption)
An idempotency key is an identifier that makes a repeated request have the same effect as a single one.
- Issuance key = (order_id, reason). The late-delivery event may arrive twice (the event bus delivers at-least-once, meaning a message can arrive more than once) or be replayed after an outage; the unique constraint turns the second insert into a no-op that returns the existing credit. A random request ID would not work here, because the duplicate is a new message with a new ID.
- Partner call key = credit_id. If the partner call times out we do not know whether they created the credit. Retrying with the same reference makes their side dedupe it; if the partner's API has no idempotency support, the adapter first queries by our reference before retrying.
- Redemption key = the partner's redemption ID. The state change is a compare-and-set (an update that only succeeds if the row is still in the state we last read, so two concurrent attempts cannot both win):
UPDATE credit SET status='redeemed' WHERE credit_id=$1 AND status='delivered' AND expires_at > now(). Exactly one concurrent redemption sees one row updated; the other sees zero and returns "already redeemed" (or the stored result if the redemption ID matches).
Anti-fraud controls
| Threat | Control |
|---|---|
| Guessing codes | Codes are 16 characters of Crockford base32 (an alphabet of 32 letters and digits that drops look-alikes such as I, L, O and U, so 5 bits per character) from a cryptographic random generator: 80 bits. With 1.8 million live codes, one guess succeeds with probability 1.8e6 / 2^80, about 1.5e-18; even a billion guesses gives about 1.5e-9. Plus rate limits and lockout on the validation endpoint. |
| Code stolen from email or shared online | Credit is bound to the customer's account: the partner must redeem it for a linked account, or the code is delivered as a one-time link that attaches it. A leaked code is useless to anyone else. |
| Manufacturing delays (collusion, fake addresses, self-reporting) | Lateness computed from our own delivery timestamps, never from a customer claim; caps (for example 3 credits per customer per 30 days); risk scoring on accounts with many late orders, new accounts, shared devices or payment instruments (the card, wallet or bank account used to pay); high-risk credits held for review. |
| Insider or bug issuing credits in bulk | Daily issuance budget per region with an alert and hard stop; issuance only by the service identity; every manual credit needs a reason code and a second approver. |
| Database leak | Store only an HMAC (hash-based message authentication code, a keyed hash) of each code, so a dump of the table cannot be turned back into redeemable codes. |
Expiration and region controls
expires_atis set at issuance and passed to the partner; our redemption check enforces it too (defence in depth: checking the same rule in more than one place so a single broken check cannot cause a failure, and clocks differ). A nightly job moves expired, unredeemed credits toexpiredand posts the reversing ledger entry.- Region is recorded at issuance (from the order's delivery address). Redemption checks the partner-reported ride or delivery region against an allow-list for that credit; local rules also matter: in some jurisdictions stored-value or gift-card style instruments cannot expire, or must be disclosed differently, so expiry length is a per-region configuration reviewed with legal, not a constant.
Reconciliation and accounting
Double-entry means every movement is two or more ledger lines that sum to zero, so the books always balance. By convention, a debit increases an expense or asset account and decreases a liability account, while a credit does the opposite: increases a liability and decreases an expense. That is why issuing a credit debits (increases) the expense and credits (increases) the liability below, while expiry reverses both to reflect the liability being extinguished without the expense ever being paid out.
| Event | Debit | Credit |
|---|---|---|
| Issue 10.00 | Customer compensation expense 10.00 | Credits outstanding (liability) 10.00 |
| Redeem 10.00 | Credits outstanding 10.00 | Payable to partner 10.00 |
| Partner invoice paid | Payable to partner 10.00 | Cash 10.00 |
| Expire 10.00 | Credits outstanding 10.00 | Customer compensation expense 10.00 (reversal) |
Daily reconciliation (comparing independent records of the same money to confirm they agree) matches three sources by credit ID: our credit table, the partner's redemption report, and (monthly) the partner's invoice. Every mismatch becomes a typed break: redeemed at partner but not in our ledger (missed webhook: backfill and alert), redeemed in our ledger but not at partner (our bug or reversed ride), amount differs, redeemed after expiry, redeemed twice. The invariant checked every day: issued = redeemed + expired + revoked + outstanding, per currency, to the cent.
Worked example
Tuesday: 60,000 credits of 10.00 issued = 600,000.00 of compensation expense and 600,000.00 of liability. By day 30, 45% are redeemed (27,000 credits, 270,000.00 moved to payable to partner) and 55% expire (33,000 credits, 330,000.00 reversed out of expense), so the invariant holds: 270,000 + 330,000 = 600,000. At the day-30 close, though, reconciliation shows the partner reporting 27,000 redemptions against 26,997 in our ledger. The three missing IDs are traced to redemption webhooks rejected during a signing-key rotation (the partner briefly signed webhooks with a new secret while our verifier still expected the old one, so genuine deliveries failed signature checks and were dropped); replaying them brings both sides to 27,000 and the partner's invoice line of 270,000.00 then matches our payable exactly. Without the break report, those three credits would have been expired on our side (their cost reversed out of expense) while the partner still invoiced us 30.00 for them.
Trade-offs and pitfalls
- Partner-held balance vs our code. If the partner can hold stored credit in the customer's own account, prefer loading it there by API: no code to steal. Codes are the fallback when accounts are not linked.
- Keying issuance on a request ID instead of the business event is the classic double-issue bug.
- Treating credits as a marketing number, not a liability, fails an audit: outstanding credits are money you owe.
- Synchronous partner calls on the order path make an order failure out of a partner outage; the outbox keeps issuance durable and retries later.
- What would change the design: if credits became transferable or spendable across partners, this turns into a stored-value wallet with stronger regulatory requirements and a proper balance model rather than single-use instruments.
Describe the lifecycle of a chargeback and dispute from customer complaint to final resolution. Explain how chargebacks should be represented in system state, their impact on ledger balances and merchant reporting, and architectural patterns for surfacing dispute status to merchants and operations teams.
Sample Answer
Direct answer
A chargeback is the cardholder's bank forcibly taking money back from the merchant after the cardholder disputes a charge. The lifecycle runs: customer complains to their bank, the bank (the issuer) opens a dispute with a reason code (a standardized code the network defines, such as "fraudulent transaction" or "product not received", that tells the merchant why the dispute was filed), the card network pulls the money plus a fee from the merchant's side, the merchant either accepts or submits evidence (representment), and the issuer decides, typically weeks to a few months later. In system terms a dispute is its own entity with its own state machine, linked to the original payment rather than overwriting it; its money effects are recorded as new ledger entries at each step, never as edits; and merchants and ops see it through an event-driven dispute record with a visible evidence deadline.
The lifecycle
- Customer complaint. The cardholder tells their bank a charge is fraud ("I didn't make this"), goods never arrived, were not as described, or a refund never came. Card networks typically allow disputes within about 120 days of the payment, longer in some cases (for a future event, the window often runs from the event date).
- Optional inquiry. Some networks (American Express and Discover most often) start with an inquiry or "retrieval request": the issuer asks for information before charging back. Answering, or refunding, can end it here with no dispute fee. Ignoring it can escalate to a chargeback that is effectively unwinnable.
- Chargeback. The issuer files the dispute through the network. The network debits the acquirer (the merchant's card-acceptance bank), which debits the merchant, usually through the PSP (payment service provider). The disputed amount is held for the whole dispute, and a dispute fee is charged. The disputed amount can differ from the original: a partial dispute, or currency conversion at today's rate rather than the purchase-day rate.
- Merchant response. The merchant accepts (and loses the money) or submits evidence: delivery tracking, logs showing the customer used the product, 3-D Secure authentication records, refund history. Response windows are short, usually 7 to 21 days depending on the network.
- Issuer decision. The issuer reviews the evidence, usually within 60 to 75 days depending on the network. Won: the held amount is returned to the merchant (the dispute fee usually is not). Lost: the money stays with the cardholder.
- Further rounds, sometimes. Networks define pre-arbitration and arbitration stages where a party escalates a decision, with additional fees. Not every PSP exposes these; Stripe, for instance, documents that it does not support the arbitration phase.
The whole thing typically takes 2 to 3 months, which is why dispute state must survive deploys, schema changes and staff turnover.
Representing it in system state
Do not model a chargeback as a payment status. A payment that was captured stays captured; it happened. A dispute is a separate object because:
- one payment can have more than one dispute (a different reason code, a refiled dispute, a multi-capture payment);
- the dispute has its own timeline, deadlines, evidence and outcome;
- the payment may also have been partially refunded, and that fact matters to the dispute.
stateDiagram-v2
[*] --> Inquiry: issuer asks first
[*] --> NeedsResponse: chargeback filed
Inquiry --> NeedsResponse: escalated
Inquiry --> Closed: answered or expired
NeedsResponse --> UnderReview: evidence submitted
NeedsResponse --> Lost: accepted or deadline missed
UnderReview --> Won
UnderReview --> Lost
Won --> [*]
Lost --> [*]
Closed --> [*]
A minimal dispute record: dispute_id, payment_id, psp_dispute_id, reason_code, network, disputed_amount and currency, status, evidence_due_at, opened_at, closed_at, outcome, plus an append-only event history. Every PSP webhook (the PSP's push notification) is applied idempotently by its event ID, because webhooks are delivered at least once and sometimes out of order; the state machine rejects illegal transitions (for example Won after Lost) and flags them for a human rather than overwriting.
Impact on the ledger
A ledger here is a double-entry record: every movement is an entry whose debits and credits sum to zero, and balances are derived from entries, never edited. Chargebacks add entries; they never modify the original sale. By convention, whether a debit increases or decreases a balance depends on the account's type: debiting an asset account (like psp_settlement, our cash at the PSP) or an expense account increases it, while debiting a liability account (like merchant_balance, what we owe the merchant) decreases it; crediting does the reverse in each case. That is why "debit merchant_balance" in the table below makes the merchant's available balance go down while "debit psp_settlement" makes our cash balance go up: the same word, opposite effect, because the two accounts are different types.
Worked example: a merchant sold 100.00 USD, captured and settled. The customer disputes it; the PSP charges a 15.00 USD dispute fee (an example figure; fees vary by PSP and country). Accounts from the platform's point of view: merchant_balance (what we owe the merchant), disputes_held (merchant money frozen by the dispute), psp_settlement (cash at the PSP), fee_expense_passthrough (fees charged on to the merchant).
| Event | Debit | Credit | Merchant available balance |
|---|---|---|---|
| Sale settled (earlier) | psp_settlement 100.00 | merchant_balance 100.00 | 100.00 |
| Dispute opened: funds withdrawn | merchant_balance 100.00 | disputes_held 100.00 | 0.00 |
| Network pulls the funds | disputes_held 100.00 | psp_settlement 100.00 | 0.00 |
| Dispute fee charged by PSP | fee_expense_passthrough 15.00 | psp_settlement 15.00 | 0.00 |
| Fee passed to merchant | merchant_balance 15.00 | fee_expense_passthrough 15.00 | −15.00 |
| If won: funds returned | psp_settlement 100.00 | merchant_balance 100.00 | 85.00 |
| If lost: nothing further | −15.00 |
Each row sums to zero. The merchant's end state is 85.00 if won (100 minus the non-returned fee) and −15.00 if lost (the sale is gone and the fee is owed), both derived from the entries. Keeping disputed funds in a named account is what lets reports show "held in disputes" separately from "refunded" and from "available", and lets reconciliation (comparing our own records against the PSP's to confirm they agree) match the PSP's dispute debits line by line.
Merchant reporting then shows: disputed amount held, fees, won/lost counts and amounts, and the dispute rate (disputes divided by transactions over a period, which networks monitor per merchant). A merchant whose rate climbs faces monitoring programmes, higher fees, or loss of card acceptance, so the rate is a first-class metric, not a footnote.
Surfacing dispute status
- Ingestion: PSP dispute webhooks go to a dedicated consumer that applies them to the dispute state machine. A daily dispute report from the PSP is reconciled against the dispute table to catch any missed webhook.
- Merchants: a dispute list in the dashboard with the evidence deadline front and centre, email and webhook notifications on open, approaching deadline and outcome, and an evidence upload flow that submits through the PSP's API.
- Operations: a work queue ordered by deadline then amount, deadline alerts (an internal SLA: a service-level agreement, here an internal deadline the ops team commits to hitting) at, for example, 72 hours before the evidence deadline, and the ability to bulk-accept low-value disputes where fighting costs more than the dispute is worth.
- Read model (a copy of the data, reshaped and stored specifically for fast reads, kept in sync with the events rather than queried live from the write path): the dashboard reads from a query-optimised view built from dispute events, so a heavy ops query cannot slow down the webhook consumer.
Trade-offs and pitfalls
- Overwriting the payment's status loses history and breaks the "one payment, several disputes" case.
- Refunding a payment that is already disputed is a classic double loss: many PSPs block it, but if yours does not, the customer gets the money twice.
- Missing a deadline is an automatic loss, so deadlines must drive alerts, not just sit in a column.
- Assuming the disputed amount equals the sale breaks reconciliation for currency-converted and partial disputes.
- Fighting every dispute wastes effort: a counter-fee plus staff time can exceed a small disputed amount. The policy (fight above a threshold or with strong evidence) belongs in configuration.
Describe, step-by-step, the end-to-end flow for a typical online card payment (card-not-present) from customer checkout through authorization, capture, settlement, and reconciliation. Highlight which components commonly run in the merchant, payment gateway, processor, and card network, and where latency, failure, retries, and fraud checks typically occur.
Sample Answer
Direct answer
An online card payment is two separate journeys. The authorization is a real-time question ("will the cardholder's bank stand behind this amount?") that travels merchant → payment gateway → processor/acquirer → card network → issuing bank and back while the customer waits. The money movement happens later and in batches: the merchant captures (confirms the amount it wants), captured transactions are cleared through the network, funds are settled from the issuer to the merchant's bank a day or more later, and the merchant reconciles what arrived against what it expected. Latency and fraud checks concentrate on the synchronous authorization leg; failures that matter most are timeouts where you do not know whether the bank said yes.
The cast (who runs what)
| Party | What it is | What runs there |
|---|---|---|
| Merchant | The shop | Checkout UI, order service, its own fraud rules, the order and payment records, reconciliation |
| Payment gateway | The front door the merchant integrates with (often bundled with the processor as a PSP, payment service provider, e.g. Stripe or Adyen) | Card-field collection and tokenization (swapping the card number for a reference so the merchant never stores it), API, idempotency, routing, often a fraud-scoring product |
| Processor / acquirer | The acquirer is the merchant's bank for card acceptance; the processor is the technical platform that talks to the networks on its behalf | Formatting authorization messages, batching captures for clearing, paying the merchant out |
| Card network | Visa, Mastercard and similar | Routing authorizations to the right issuer, running clearing and settlement between banks, network-level fraud and dispute rules |
| Issuer | The cardholder's bank | Approve/decline decision, available-credit check, its own fraud model, placing the hold, and later the customer's statement |
Card-not-present (CNP) means the card is not physically at a terminal (online, in-app, phone), so there is no chip to prove the card is real. That is why CNP leans on extra checks such as the CVC (the three- or four-digit card verification code), address verification and 3-D Secure (3DS: a step where the issuer authenticates the cardholder, for example with a push to the banking app; completing it successfully also shifts fraud liability from the merchant to the issuer, since the issuer vouched for the cardholder).
sequenceDiagram
participant C as Customer
participant M as Merchant
participant G as Gateway/PSP
participant A as Processor/Acquirer
participant N as Card network
participant I as Issuer
C->>M: Pay 80.00
M->>G: Create payment (token, amount, idempotency key)
G->>A: Authorization request
A->>N: Route by card number range
N->>I: Authorize?
I-->>N: Approved, hold placed
N-->>A: Approved
A-->>G: Approved
G-->>M: Authorized
M-->>C: Order confirmed
M->>G: Capture 80.00 (later)
A->>N: Clearing batch
N->>A: Net settlement funds
A->>M: Payout net of fees
Step by step
- Checkout and tokenization (merchant + gateway). The card number is typed into fields served by the gateway, not the merchant's own form, and comes back as a token. This keeps most of the merchant's systems out of scope for PCI DSS (the Payment Card Industry Data Security Standard that governs anyone storing or handling card numbers).
- Create the payment (merchant → gateway). The merchant sends amount, currency, token and an idempotency key (a unique ID for this attempt so a retried request cannot create a second charge). Merchant-side fraud rules usually run here, before the bank is ever asked.
- Authentication, if needed (issuer). For risky transactions, or where regulation requires strong customer authentication (for example much of Europe), the issuer runs 3DS. This is the step with human-scale latency, because the customer may have to approve in an app.
- Authorization (gateway → processor → network → issuer and back). The issuer checks the account, available funds, CVC/address results and its own fraud score, then approves or declines. An approval places a hold: the customer's available credit drops, but no money has moved yet.
- Capture (merchant → gateway). The merchant confirms the final amount, immediately for digital goods or at shipment for physical goods. Authorizations expire: for online card payments Stripe documents a typical 7-day validity window for customer-initiated transactions (Visa merchant-initiated ones are shorter). An expired authorization cannot be captured.
- Clearing (processor → network → issuer). Captured transactions are sent in batches; the issuer converts the hold into a posted charge on the statement.
- Settlement (issuer → network → acquirer → merchant). Banks settle net positions through the network, and the acquirer pays the merchant the captured amount minus fees (interchange, the per-transaction fee paid to the card-issuing bank, set by the network; network fees; the acquirer/PSP markup), usually one to a few business days later depending on the contract.
- Reconciliation (merchant). The merchant matches the settlement report and the bank deposit against its own ledger: every captured payment should appear once, at the expected net amount, and anything else (missing items, fee differences, chargebacks, meaning a cardholder's bank forcibly reversing a payment after a dispute) becomes a break (an unexplained mismatch between what was expected and what arrived) to investigate.
Where latency, failure, retries and fraud checks sit
| Stage | Latency | Typical failures | Retry rule | Fraud control |
|---|---|---|---|---|
| Tokenize/create | Low | Validation errors | Safe with idempotency key | Merchant rules, velocity checks (limits on how many attempts, or how much value, one card, device or account can push through in a short window) |
| 3DS | Seconds to minutes (human) | Customer abandons | Customer-driven | Issuer authentication |
| Authorization | The bulk of machine latency: several network hops | Timeout (outcome unknown), soft decline (e.g. issuer unavailable), hard decline (e.g. stolen card) | Retry a timeout with the SAME idempotency key or query status first; do not blindly retry hard declines | PSP risk score, issuer model, network checks |
| Capture | Low, not customer-facing | Auth expired, amount above authorized | Retry with idempotency key; re-authorize if expired | Rarely |
| Clearing/settlement | Hours to days, batch | Missing or partial items | Handled by reconciliation, not API retries | n/a |
| Post-settlement | Weeks to months | Refunds, chargebacks | Separate flows | Dispute evidence |
The most important failure in the list is the authorization timeout: the request may have reached the issuer and been approved even though the merchant saw an error. Treating that as a decline and letting the customer click Pay again is how customers get charged twice. The correct handling is to mark the payment as unknown, retry with the same idempotency key (the gateway returns the original result) or query the gateway for the payment's status.
Worked example
A customer buys an 80.00 USD jacket on Monday.
- Monday 10:00: authorization for 80.00 approved; the customer's banking app shows an 80.00 pending item.
- Tuesday: the jacket ships; the merchant captures 80.00.
- Tuesday night: the capture goes out in the processor's clearing batch.
- Thursday: payout arrives. If the merchant's all-in pricing were 2.9% + 0.30 USD (an example rate, not a quote), the fee is 80.00 × 0.029 = 2.32, plus 0.30, so 2.62; the deposit line is 80.00 − 2.62 = 77.38 USD.
- Thursday reconciliation: the merchant's ledger expected 80.00 gross; the report shows 80.00 gross, 2.62 fee, 77.38 net. Matched. Had the merchant reconciled the bank deposit against gross revenue it would have seen a false 2.62 shortfall on every order.
Trade-offs and pitfalls
- Authorization is not payment. An approved authorization can still expire uncaptured, and captured money can still come back as a refund or chargeback months later. Fulfilment logic should key off the state it actually needs.
- Unknown is a real state. Systems that model only success/failure convert timeouts into duplicate charges or into lost sales.
- Soft vs hard declines. Retrying a "do not honour" (the generic issuer decline code that gives no specific reason) or stolen-card decline over and over looks like card testing (an attacker running many small charges to find out which stolen card numbers still work) to issuers and networks; retry only declines that are explicitly transient.
- Gross vs net. Reconciliation must model fees, currency conversion and timing, or it produces noise that ops teams learn to ignore.
- Capture timing is a business decision (capture now vs at shipment), with consequences for refunds, disputes and expiry; it should be chosen deliberately, not left at an SDK default.
Design an architecture to route payment requests to multiple payment gateways and processors based on business rules: card BIN, currency, transaction amount, gateway success rate, cost, and merchant preferences. Include failover, throttling per gateway, dynamic rule updates without code deploys, and monitoring needed to validate routing decisions.
Sample Answer
Direct answer
Put a payment router between checkout and the gateways that makes a decision in two layers: a rules layer (hard constraints and merchant preferences: which gateways may take this BIN, currency and amount) that produces an ordered candidate list, and a scoring layer that ranks the candidates by expected value (approval rate times margin, minus fees), filtered by live health and per-gateway quota. Rules are versioned data pushed to routers without deploys; every decision is logged with the rule version and inputs, so you can prove, and measure, that routing is doing what you intended. Fail over only on errors that guarantee the first gateway did not authorize.
Inputs, glossed
- BIN (bank identification number): the first 6 to 8 digits of the card, which identify the issuing bank, the card brand, the country, and whether it is debit, credit or prepaid. A BIN table lookup turns the card into routing attributes.
- Gateway success rate: approval rate per gateway, measured per segment (card brand × issuer country × currency), because a gateway can be excellent for domestic UK debit and poor for Brazilian credit.
- Cost: fee schedule per gateway (percentage plus fixed fee, cross-border surcharges, FX (foreign exchange) margin, the markup a gateway adds to the wholesale exchange rate when converting currencies; this is a separate concept from the merchant profit "margin" used in the scoring formula below, which happens to share the same word).
- Merchant preferences: "only use gateway B for this merchant", "never route to X", contractual volume commitments.
Architecture
flowchart LR
API[Payment API] --> RT[Router]
CFG[(Rule store, versioned)] -. push .-> RT
BIN[(BIN table)] --> RT
HS[Health and approval stats] --> RT
RT --> QA[Per-gateway quota]
QA --> GA[Gateway A adapter]
QA --> GB[Gateway B adapter]
QA --> GC[Gateway C adapter]
RT --> DL[(Decision log)]
GA --> HS
GB --> HS
GC --> HS
Decision procedure (per payment)
- Enrich: BIN lookup → brand, issuer country, card type; merchant config.
- Rules filter (first-match rule sets, evaluated in order): eligibility (gateway supports the currency and brand, the merchant is contracted there, amount within limits), then preferences (pin, exclude, weights).
- Health filter: drop gateways whose circuit breaker is open (recent error or timeout rate above threshold).
- Score: for each remaining gateway,
where p^g ("p-hat", read as the estimated probability of approval) is the smoothed approval rate for this segment: the segment's raw recent approval rate blended with a longer-running average, so one unlucky batch of ten declines does not swing the score. A raw rate over a small recent sample is noisy on its own and can send traffic away from a genuinely good gateway on a bad afternoon. margin is the merchant's own profit on the order before payment costs (20.00 on this 80.00 order at 25% margin, worked below), so margin - fee_g is what the merchant actually keeps after paying gateway g. Add a small exploration share (for example 5% of traffic spread across eligible gateways) so the approval estimates for non-winning gateways do not go stale.
5. Quota check: take a token from the gateway's bucket (a token bucket is a counter that refills at a fixed rate up to a cap; each request consumes one token, and an empty bucket means the gateway's rate limit for this instant is used up); if empty, move to the next candidate.
6. Send with an idempotency key (a value attached to the request so a retried send cannot double-charge the card); log the decision.
Worked example: cost versus success rate
An 80.00 order where the merchant earns 25% margin (20.00). Gateway A charges 2.9% + 0.30; gateway B charges 2.5% + 0.30.
| Fee | Approval rate (segment) | Expected value | |
|---|---|---|---|
| A | 80 × 0.029 + 0.30 = 2.62 | 92% | 0.92 × (20.00 − 2.62) = 15.99 |
| B | 80 × 0.025 + 0.30 = 2.30 | 88% | 0.88 × (20.00 − 2.30) = 15.58 |
The cheaper gateway loses 0.41 per attempt because four points of approval rate are worth more than 0.32 of fee. A rules engine that only says "route to the cheapest" leaves money on the table; this is why the score uses both.
Failover
- Safe to fail over: connection refused, TLS failure, an explicit "not processed" response, or a soft decline code (a temporary refusal the issuer expects might succeed on a later or different attempt) that the gateway documents as retryable elsewhere (for example "issuer unavailable").
- Not safe: a timeout after the request was sent. The first gateway may have authorized; routing to a second can put two holds on the customer's card. Mark the attempt
unknown, query the first gateway's status by idempotency key, and only then decide. - Hard declines (a refusal the issuer will give the same answer to no matter how many times or where you retry) (stolen card, insufficient funds) are never retried on another gateway: it annoys issuers and networks penalize excessive retries.
- Cap total attempts per payment (for example 2) and total time within the checkout budget.
Throttling per gateway
Each gateway has contractual or technical limits (say 300 requests per second). Two options:
| Option | How | Verdict |
|---|---|---|
| Central counter (Redis token bucket) (Redis is an in-memory key-value data store, fast enough to check and decrement a shared counter on every request) | Every router takes tokens from one shared bucket | Exact, but adds a network hop per payment and Redis becomes critical-path |
| Local buckets | Each of N router instances gets limit ÷ N (with 12 instances, 25 per second each), rebalanced every few seconds from a coordinator | No extra hop; slightly conservative when load is uneven |
Recommendation: local buckets with periodic rebalancing, because the router is on the checkout path and a small under-use of the gateway's limit is cheaper than another dependency. Spill-over when a bucket is empty goes to the next candidate, not to a queue (a queued card payment is a waiting shopper).
Dynamic rule updates without deploys
- Rules live in a versioned rule store (a database table or config service) with a schema validator, and every change goes through review and approval in an admin tool.
- Routers subscribe to changes and swap the whole rule set atomically (build new, validate, then switch a pointer), so no payment sees half a rule set.
- New rule sets can run in shadow mode: evaluated on live traffic and logged, but not acted on, to see what they would change.
- Staged rollout: apply to 1% of traffic, compare approval rate and cost, then widen. One-click revert to the previous version.
- Router instances expose the rule version they are running; a mismatch across the fleet is an alert.
Monitoring to validate routing decisions
- Decision log per payment: rule version, candidates considered, scores, chosen gateway, reason for skips (breaker open, quota, rule). This answers "why did this payment go to C?".
- Outcome by route: approval rate, decline-code mix, latency and cost per gateway per segment, compared with the scorer's predictions.
- Counterfactual measurement: the exploration slice gives unbiased approval rates for every gateway, so you can check whether the chosen gateway actually beats the alternatives.
- Health: breaker state changes, quota rejections, failover rate, unknown-outcome count.
- Business guardrails: share of volume per gateway versus contractual commitments; alert if a commitment will be missed at the current run rate.
Trade-offs and pitfalls
- Stale approval rates make the router lock onto one gateway; exploration traffic and time-decayed statistics (an average that weights recent observations more heavily than old ones, so the estimate keeps up as approval rates drift) prevent that.
- Rules that grow into code: keep the rule language to predicates and weights; anything that needs loops belongs in the router with a code review.
- Tokenization lock-in: if each gateway holds its own card tokens, you cannot route a saved card anywhere else. A vault you control, or network tokens (card-network-issued tokens usable across processors), is a precondition for multi-gateway routing of repeat customers.
- Double authorization on ambiguous failover is the most expensive bug here: it creates duplicate holds, angry customers and disputes.
Unlock Full Question Bank
Get access to all 35 Payment and Transaction Processing Systems interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.