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 backend architecture for a subscription-based membership program on a marketplace platform (for example, waived delivery or service fees for subscribers): entitlement checks, billing-gateway integration and subscription lifecycle, perk enforcement, offline behavior on driver and merchant apps, and reconciliation between usage and the billing ledger. Explain how you would ensure consistency, minimize latency in entitlement checks, and prevent abuse.
Sample Answer
Direct answer
Separate the money side (subscription lifecycle, charged through a billing gateway) from the entitlement side (the fast yes/no "is this customer a member right now, and which perks apply?"). A Subscription service owns the lifecycle as a state machine and is the source of truth; every change emits an event that updates a read-optimised entitlement store and cache, so checkout reads entitlement in single-digit milliseconds. Every perk actually granted is recorded on the order as a benefit event with the entitlement version it relied on, so a nightly job can reconcile benefits consumed against what the billing ledger (an append-only record of every money movement) says each member paid. Money-affecting decisions are re-checked authoritatively at order placement, and driver and merchant apps never decide entitlement themselves; they only display a signed decision already made by the server.
Requirements and scale (assumed, so the arithmetic can be checked)
- A membership (monthly or annual) waives delivery or service fees on eligible orders above a minimum basket; free trials; cancellations; failed renewals.
- Load: 10 million orders/day, each checking entitlement about 3 times (browse badge, cart quote, checkout) = 30 million checks/day, which is 30,000,000 / 86,400 = about 350 checks/second on average and about 1,050/second at a 3x dinner peak.
- Target: p99 (the 99th-percentile latency: 99 of every 100 checks faster than this) under 10 ms for the check itself, because it sits inside the quote and checkout calls.
- 5 million members at about 200 bytes of entitlement state each is about 1 GB: small enough to hold entirely in memory in a replicated cache.
Architecture
flowchart LR
BG[Billing gateway] -->|webhooks| SUB[Subscription service]
SUB --> SDB[(Subscription DB + ledger)]
SUB -->|outbox events| BUS[Event stream]
BUS --> ENT[Entitlement projector]
ENT --> CACHE[(Entitlement cache)]
CO[Checkout and pricing] -->|check| CACHE
CO -->|miss or stale| SUB
CO --> ORD[(Orders + benefit events)]
ORD --> REC[Usage vs ledger reconciliation]
SDB --> REC
CO -->|signed decision| APPS[Driver and merchant apps]
The "outbox events" arrow above is the outbox pattern: a state change is written to a table row in the same database transaction as the subscription update, and a separate publisher reads that table and emits the event, so a crash between updating the subscription and publishing the event can never happen.
Subscription lifecycle and billing-gateway integration
States: TRIAL -> ACTIVE -> PAST_DUE -> (ACTIVE | CANCELED), plus CANCEL_AT_PERIOD_END (still active until the paid period ends) and PAUSED.
- Renewals are driven by the gateway's billing engine or our scheduler, but either way the gateway's events (invoice paid, payment failed, subscription updated) arrive by webhook (an HTTP callback the gateway sends when something changes). The Subscription service verifies the signature, dedupes by event ID, and re-reads the subscription from the gateway before changing state, because webhooks can arrive duplicated and out of order.
- Idempotency: calls we make to the gateway (create subscription, cancel, change plan) carry an idempotency key (an identifier the gateway uses to recognize a retried request and return the original result instead of repeating the action) derived from our own command ID, so a retried request cannot create a second subscription or a second charge.
- Failed renewal (dunning): the process of retrying a failed recurring payment and reminding the customer. The subscription goes
PAST_DUEwith a grace period (say 3 days) during which perks continue, while the gateway retries the card on a schedule. After grace, perks stop; after the final retry,CANCELED. - Ledger: each paid invoice is posted as double-entry lines (debits and credits that sum to zero): cash in, and deferred revenue, a liability released day by day over the period the member has paid for. That daily release is what reconciliation compares benefits against.
- Multiple gateways (for example card processor plus app-store billing, Apple's or Google's own in-app purchase system, which handles the charge and takes its own cut, for in-app purchases) sit behind an adapter interface; the Subscription service's state machine is the same whichever gateway produced the event.
Entitlement checks with low latency
- The entitlement projector turns subscription events into a flat record:
member_id, plan, perks[], valid_until, grace_until, version, updated_at(the timestamp this record was last refreshed). It writes it to a replicated in-memory cache (and a durable table behind it). A separate projection exists because the Subscription DB is built for correctness and low-volume writes, not for a few hundred low-latency reads per second sitting inside every checkout call: querying it directly for every check would put checkout's tail latency at the mercy of the billing database's own load, joins and lock contention, and would miss the sub-10 ms p99 budget below. - Checkout reads the cache: a single key lookup, well inside the 10 ms budget. The decision is computed from
valid_untilagainst the server clock, so an expired membership stops granting perks at the right moment even if an event is delayed. - Two consistency levels, chosen by what is at stake:
- Browse and cart quote: the cached record is enough; showing "free delivery" a few seconds after a cancellation is harmless.
- Order placement, where the fee is actually waived: if the cached record's
updated_atis older than a freshness bound (say 60 seconds), meaning the projector has not refreshed it recently and may be behind, or it is a cache miss, read the Subscription DB directly. Concretely: of the roughly 350 checks/second average (1,050 at peak), about a third are order-placement checks (the "checkout" leg of the three checks per order), so roughly 117/s average and 350/s at peak. Under healthy operation the projector's lag stays well under the 60-second bound, so only a small share of those, cache misses and the rare record whose refresh has genuinely fallen behind, actually read the Subscription DB; even a conservative 5% miss-or-stale rate is only about 6/s average and 17/s at peak, comfortably tens, not thousands.
- Read-your-writes after sign-up: when a customer joins and immediately orders, checkout passes the version returned by the sign-up call; if the cache is behind that version, it reads the source. This removes the "I just subscribed and was still charged a fee" bug.
- If the cache is unavailable, fall back to the source behind a circuit breaker (a guard that stops calling a failing dependency for a cool-down period so it is not overwhelmed); if both are down, fail open for display (show normal fees) and closed for money (charge normal fees and refund the difference later if the member was entitled). A small refund is cheaper than giving free perks to everyone during an outage.
Perk enforcement
- Perks are rules evaluated at pricing, not flags scattered across services: "delivery fee = 0 if member and basket at least 15.00 and merchant participates". The pricing service writes the result on the order as a benefit event:
order_id, member_id, perk, amount_waived, entitlement_version, decided_at. - Merchant participation and regional rules are part of the rule's inputs, so a non-participating merchant or region simply does not qualify.
Offline behaviour on driver and merchant apps
Drivers and merchants do not decide entitlement; they need to show and honour what was decided. So:
- The server attaches a signed decision to the order at placement (for example a compact token signed with the platform's private key, containing order ID, perks applied and amount waived). Apps verify the signature with the public key they already have, offline, and display it.
- If a driver's app is offline, it keeps working from the last-synced order payload; nothing it does changes what the customer is charged, because the fee was fixed on the server at placement.
- Actions taken offline (merchant marks a perk item as provided, driver completes delivery) are queued locally with timestamps and idempotency keys and synced when back online; the server applies them once.
- What the apps must never do: cache a "this customer is a member" flag and grant perks to new orders from it. That turns every offline device into an entitlement authority.
Reconciliation between usage and the billing ledger
A nightly job joins benefit events with the subscription ledger, per member-day:
- Every waived fee has a covering entitlement: a benefit event is valid only if the member was
ACTIVE,TRIALor within grace atdecided_at. Violations are counted by cause (stale cache, bug, fraud). - Every paid period has a subscription state: invoices paid without an active subscription, or active subscriptions without a paid invoice past grace, are breaks.
- Economics per cohort: fees waived vs deferred revenue recognised, for product and finance.
- Grace exposure is measured, not guessed: if 2% of 5 million members fail renewal in a month (100,000), and each orders 0.2 times per day during a 3-day grace with a 2.99 fee waived, grace costs 100,000 x 0.2 x 3 x 2.99 = 179,400 in waived fees per month. That number decides whether a 3-day grace is worth its recovered renewals.
Preventing abuse
| Abuse | Control |
|---|---|
| Serial free trials with new accounts | Trial eligibility keyed on payment-instrument fingerprint (a hash derived from the card or payment method's identifying details, so the same card is recognized even under a new account), device and address, not only account |
| Account sharing | Limit active delivery addresses and concurrent devices per membership; flag unusual order patterns |
| Subscribe, order heavily, dispute the membership charge | Chargeback (the issuer forcibly reversing a captured payment after the cardholder disputes it) on the membership charge moves the account to CANCELED and blocks re-trial; benefit events provide the evidence of usage |
| Cancel-and-rejoin to game trial or promo pricing | Promotions are once per payment fingerprint and household |
| Manipulating the client to show a fee waiver | Fee is computed server-side at placement; the client's view is never trusted |
Trade-offs and pitfalls
- Calling the billing gateway on every check puts an external dependency and its latency on the checkout path; the gateway is the system of record for payments, not a query service for entitlement.
- Cache-only entitlement with long TTLs (time-to-live, how long a cached value is used) lets cancelled members keep perks; use event-driven updates, validity timestamps and an authoritative check at placement.
- Ignoring out-of-order webhooks can resurrect a cancelled subscription when a late "invoice paid" arrives; re-read the subscription before transitioning.
- Not recording the entitlement version on the order makes reconciliation guesswork.
- What would change the design: at a few thousand members, drop the projector and cache and query the Subscription DB directly (a primary-key read is fast enough); if perks become usage-limited (for example 5 free deliveries a month), entitlement becomes a counter that must be decremented atomically at placement, which needs a stronger consistency path than a cached flag.
Provide a recommended microservice decomposition for a merchant payments platform. List core services (for example gateway adapter, authorization service, ledger/settlement service, fraud service, reconciler, notifications), describe responsibilities, typical APIs between them, and how you would handle ownership of critical data like transaction state and merchant configuration.
Sample Answer
Direct answer
Split the platform along ownership of money-critical data: one service owns the lifecycle of each payment, one owns balances (the ledger), one owns merchant configuration, and each external processor sits behind its own adapter. The synchronous path that a buyer waits on (API gateway, payment service, fraud check, processor adapter) stays short, and everything else, ledger postings, notifications, reconciliation (matching internal records against what the processor and the bank report), and reporting, reacts to events. The rule that keeps it correct: every critical piece of data has exactly one service that writes it, and every other service reads it through that service's API or through events it publishes.
Key terms
- PSP (payment service provider) / processor: the external company that sends authorizations to the card networks and settles funds.
- Authorization: the bank approves and holds funds. Capture: the merchant claims them. Settlement: the money actually moves, net of fees.
- Ledger: an append-only record of money movements using double-entry bookkeeping (every movement is a debit on one account and an equal credit on another, so the books always sum to zero).
- Reconciliation: matching internal records against processor and bank reports.
- Outbox: a table written in the same database transaction as a state change, from which events are published, so a state change and its event can never disagree.
- Idempotency key: a client-chosen unique ID attached to a request so that if the same request is retried (for example after a timeout), the server can recognize the repeat and return the original result instead of creating a second payment.
- Event bus: the shared channel a service publishes domain events to (such as
payment.captured) so other services can subscribe and react, without the publisher calling any of them directly. - Debit and credit: in double-entry bookkeeping every ledger line is a debit or a credit. A debit increases an asset or expense account and decreases a liability or revenue account; a credit does the reverse. A receivable is an asset, money owed TO the platform (for example by the PSP, once it has taken a card payment but not yet settled it); debiting it records that the platform is now owed more. A payable is a liability, money the platform owes someone else (a seller's pending balance, a merchant's fee credit); crediting it records that the platform now owes more.
Proposed services
flowchart LR
API[API gateway] --> PAY[Payment service]
PAY --> AUTH[Authorization service]
AUTH --> FR[Fraud service]
AUTH --> AD[Processor adapters]
AD --> EXT[External PSPs]
PAY --> BUS[Event bus]
BUS --> LED[Ledger and settlement]
BUS --> NOT[Notifications]
REC[Reconciler] --> LED
REC --> AD
CFG[Merchant config] -.-> PAY
| Service | Responsibilities | Owns (sole writer) | Typical API |
|---|---|---|---|
| API gateway | Authentication of merchants, rate limits, idempotency-key handling, request validation | Idempotency records | Public REST: POST /payments, POST /payments/{id}/capture, POST /refunds |
| Payment service | The payment state machine: created, authorized, captured, partially refunded, refunded, failed, disputed; enforces legal transitions | Payment and refund state | Internal: CreatePayment, Capture, Refund over gRPC (a binary remote-procedure-call protocol); publishes payment.authorized, payment.captured, refund.succeeded |
| Authorization service | Decides how to authorize: calls fraud, picks the processor (routing), handles 3-D Secure (cardholder authentication) | Routing decisions and authorization attempts | Authorize(payment_id, amount, token, merchant) returns approved, declined or unknown |
| Fraud service | Scores risk from device, velocity (how rapidly this device or card is attempting payments, a common fraud signal) and history; returns allow, review or block within a strict time budget | Risk scores and rules | Score(payment context), plus async feedback events for chargebacks (a cardholder disputing a charge through their bank, which pulls the funds back from the platform) |
| Processor (gateway) adapters | One gateway adapter per external PSP: translate the internal model to that PSP's API, map decline codes (the processor's classification of why an attempt failed, such as insufficient funds or a stolen card, which routing logic needs in order to decide whether to retry elsewhere), handle PSP-specific retries and status queries | Raw PSP request and response log | Authorize, Capture, Refund, GetStatus, and a webhook receiver (an HTTP endpoint the PSP calls to push status updates to us, instead of us polling for them) that emits normalised events |
| Ledger and settlement | Double-entry postings for every money movement; merchant balances; payout calculation and scheduling | Journal entries, balances, payouts | Consumes payment events; GetBalance(merchant); publishes payout.created |
| Reconciler | Ingests PSP settlement files and bank statements; matches them to ledger and payment records; raises breaks (unmatched or mismatched items) | Reconciliation results and break cases | Batch jobs plus ListBreaks for finance tooling |
| Notifications | Merchant webhooks (signed, retried), customer receipts, email | Delivery attempts | Consumes events; ReplayWebhook(event_id) |
| Merchant configuration | Merchant profile, enabled payment methods, fees, payout schedule, API keys, risk settings | Merchant config, versioned | GetMerchantConfig(id) returning a version number; publishes merchant.config_changed |
| Token vault (often the PSP's) | Stores raw card numbers and issues a token in their place (a token is a random reference that stands in for the card number, so other services never need to handle the real number) | Card data | Tokenize (turn a card number into a token), restricted Detokenize (reverse a token back to the real card number) |
Ownership of critical data
- Transaction state is owned by the payment service only. The adapter reports what the PSP said; the payment service decides the state transition. This avoids two services disagreeing about whether a payment is captured.
- Balances are owned by the ledger only. Nobody else computes "how much does this merchant have". The ledger derives it from postings, and reporting reads a copy.
- Merchant configuration is owned by the config service, but read on the hot path from a local cache. Every payment records the config version it used, so a fee change at 12:00 cannot make a 11:59 payment's fee ambiguous later.
- Events carry facts, not commands to change someone else's data. The ledger posts entries because it heard
payment.captured, not because the payment service wrote into the ledger's tables. Each consumer de-duplicates by event ID, because delivery is at-least-once (an event may arrive more than once). - No shared databases. Each service's store is private; a shared table is where two writers eventually corrupt each other.
Worked example: one card payment
- Merchant calls
POST /paymentsfor 80.00 EUR with idempotency keyord-5531. The gateway records the key. - The payment service creates
pay_901in statecreated, reads merchant config version 14 from cache. - The authorization service gets a fraud score (allow), routes to PSP A, and the adapter returns approved. The payment service moves
pay_901toauthorizedand writespayment.authorizedto its outbox in the same transaction. - The merchant ships and calls capture; the state becomes
capturedandpayment.capturedis published. - The ledger posts: debit "PSP A receivable" 80.00, credit "merchant pending balance" 78.40, credit "platform fee revenue" 1.60 (a 2% fee from config version 14). The three lines net to zero.
- Two days later the reconciler matches PSP A's settlement line for
pay_901against the receivable and clears it.
Trade-offs and pitfalls
- Separate authorization service or not. At small scale, fold authorization into the payment service; split it out when routing across several PSPs and 3-D Secure logic grows enough to deserve its own team and deploy cadence.
- Too many synchronous hops on the buyer's path add latency and failure points. Keep it to gateway, payment, fraud and adapter; everything else is asynchronous.
- Fraud outage policy must be explicit: fail open (accept with lower limits) or fail closed (decline). Most platforms fail open for low amounts and closed for high ones.
- A distributed transaction across services (making the payment update and the ledger posting commit together) is the wrong tool; use the outbox plus idempotent consumers and let reconciliation catch the rare gap.
- Over-splitting (a separate refunds service, a separate captures service) scatters one state machine across services, which is exactly where money bugs come from.
Design a global payouts system to onboard large partners that handles KYC, local tax reporting, and multiple local payment rails while minimizing per-partner customization. Outline data models, workflow orchestration, and how you would manage regulatory differences between countries.
Sample Answer
Direct answer
Build one payout engine and push every country and partner difference into data: a versioned per-country rule pack (which identity checks, which tax forms, which rails, which limits) and a per-partner configuration that only picks options from those packs. Onboarding, identity verification, tax enrollment and each payout run as durable workflows (long-running state machines whose progress survives crashes and restarts), and every money movement is posted to a double-entry ledger (every transaction records equal and opposite entries, so money can never appear or vanish). Local payment rails sit behind one adapter interface, so adding Brazil means writing a rule pack and a rail adapter, not changing the core.
What we are designing to
- Who: "large partners" are platforms (a marketplace, a gig app) that pay many recipients (sellers, drivers, creators). Partner onboards once; its recipients number in the hundreds of thousands.
- KYC (know your customer: verifying who someone is and screening them against sanctions lists) applies to the partner as a business (KYB, know your business, including its beneficial owners (the real individuals who ultimately own or control the business, even when hidden behind holding companies)) and, depending on country and amount, to each recipient.
- Local tax reporting: collect the right tax identity documents, withhold where a country requires it, and file year-end information returns per jurisdiction.
- Multiple local rails: ACH (the US batch bank-transfer network), SEPA Credit Transfer and SEPA Instant (euro-area bank transfers), UK Faster Payments, Brazil's Pix (the central bank's instant payment system), India's UPI (Unified Payments Interface) and IMPS (Immediate Payment Service), plus card push and wallets where banks are thin.
- Minimal per-partner customization: the success test is that onboarding partner number 50 needs zero code changes.
Architecture
flowchart LR
P[Partner API and dashboard] --> WF[Workflow engine]
WF --> ID[Identity and KYC service]
WF --> TX[Tax profile service]
WF --> PO[Payout orchestrator]
RP[(Country rule packs)] --> WF
PO --> LG[(Double-entry ledger)]
PO --> RA[Rail adapters]
RA --> R1[ACH / SEPA / Faster Payments]
RA --> R2[Pix / UPI / wallets]
RA --> RC[Reconciliation]
RC --> LG
| Component | Job | Why it is separate |
|---|---|---|
| Workflow engine (for example Temporal, a durable-execution framework: if the process crashes mid-workflow, it resumes exactly where it left off, by replaying the sequence of already-completed steps from a saved history, rather than starting over or losing track of what was already done) | Runs onboarding, verification loops, payout batches as resumable steps with timers and retries | KYC can wait days for a document; a payout batch must resume exactly where it stopped after a crash |
| Country rule packs | Versioned data: required fields, KYC tier thresholds, tax form types, withholding rules, allowed rails, cut-off times (the latest time of day a payment instruction can be submitted and still go out same-day on that rail), holiday calendars | Regulatory differences change on regulators' schedules, not deploy schedules |
| Identity and KYC service | Collects documents, calls screening vendors, stores decisions and evidence references | One audit trail for "why was this person allowed to receive money" |
| Tax profile service | Stores tax residency, tax IDs, treaty claims, withholding rate (treaty claims: a recipient's claim to a reduced withholding rate under a tax treaty between their country and the paying country), and generates filings | Tax logic is jurisdictional and date-effective |
| Payout orchestrator | Turns "pay recipient R 120.00 EUR" into a rail choice, an instruction, and ledger postings | Keeps money logic out of the rail adapters |
| Rail adapters | One interface (quote, submit, status, parse_return) per rail or banking partner | New rail = new adapter, nothing else changes |
| Ledger | Source of truth for balances and every movement | Auditors and reconciliation read one place |
Data model
The core tables (simplified, all times in UTC, all amounts in integer minor units such as cents):
partner(partner_id, legal_name, home_country, kyb_status, config_version, created_at)
partner_config(partner_id, version, allowed_countries[], payout_schedule, fee_plan_id,
funding_model, rule_pack_overrides_json) -- options only, never code
recipient(recipient_id, partner_id, country, type{individual,business},
kyc_tier, kyc_status, tax_profile_id, created_at)
kyc_check(check_id, subject_id, check_type, vendor, result, evidence_ref,
rule_pack_version, decided_at) -- append-only
tax_profile(tax_profile_id, residency_country, tax_id_token, form_type,
form_status, withholding_bps, treaty_claim, valid_from, valid_to) -- withholding_bps is the withholding rate in basis points (hundredths of a percent), so 1500 means 15%; treaty_claim records a recipient's claim to a reduced rate under a tax treaty between their country and the paying country
payout_method(method_id, recipient_id, rail, account_token, verified_at)
rule_pack(country, version, effective_from, body_json, approved_by)
payout(payout_id, partner_id, recipient_id, amount_minor, currency, rail,
status, idempotency_key UNIQUE, rule_pack_version, created_at)
ledger_entry(entry_id, txn_id, account, amount_minor, currency, posted_at)
rail_event(event_id, payout_id, rail_ref, event_type, raw_ref, received_at)
Three design decisions carry most of the weight:
- Every decision stamps the rule-pack version it used. Months later, when a regulator asks why a recipient was paid without a tax ID, you can show that the German pack version in force that day did not require one below the threshold.
- Bank details and tax IDs are stored as tokens pointing into an encrypted vault, so most services never see the raw values.
- Payout status is a state machine (
created → screened → funded → submitted → settled | returned | failed), and only the orchestrator moves it, driven by rail events.
Workflow orchestration
Partner onboarding (days to weeks): collect business details → KYB and beneficial-owner screening → contract and funding set-up → sandbox test payouts → go live. Each step is a workflow activity (one durable, retryable unit of work inside the workflow, such as one API call) with its own retry policy; a "waiting for document" step is a durable timer (a wait the workflow engine itself schedules and resumes from, surviving restarts, rather than a separate polling job) that reminds the partner and escalates, not a cron job scanning a table.
Recipient onboarding (minutes, at scale): the partner submits recipients through the API; the workflow looks up the recipient's country pack to decide the KYC tier (for example "name and bank account only" below a volume threshold, "ID document plus liveness check" (a liveness check is a quick photo or video challenge proving the ID is being presented by a live person in front of the camera, not a photo of a photo) above it) and which tax form to collect, then marks the recipient payable only when every check the pack requires has passed.
Payout run:
- Partner submits a batch with an idempotency key per payout (an idempotency key is a client-chosen ID that makes a retried request return the original result instead of paying twice).
- Screening: sanctions re-check, limits from the pack, recipient still payable.
- Funding: debit the partner's prefunded balance in the ledger (or confirm incoming funds).
- Tax: compute withholding from the tax profile and post it to a tax-payable account.
- Rail selection by rules: the recipient's currency and country, speed promised by the partner's plan, cost, and cut-off times.
- Submit through the adapter; post
recipient_payable → rail_in_transit(a balanced ledger transaction that debits the recipient_payable account and credits rail_in_transit by the same amount, moving the money from "owed to the recipient" to "handed to the rail and awaiting confirmation"). - Rail events (settled, returned with reason code) arrive asynchronously and complete the workflow; a return reverses the ledger entries and notifies the partner.
Managing regulatory differences between countries
- Rule packs as reviewed data. A compliance analyst edits a pack; a second person approves it; it gets a version and an effective date. Engineers review only the schema.
- Evaluate, do not branch. Code asks the pack "what KYC tier applies to an individual in BR receiving 3,000 BRL per month?" rather than containing
if country == "BR". - Licensing and entity routing. Payouts in some countries must be made by a licensed local entity or partner bank. The pack names which legal entity and banking partner originates the payout, and the ledger has per-entity accounts.
- Data residency. Where identity data must stay in-country, the vault is regional and the core stores only tokens and decisions.
- Tax reporting differs in kind, not just rate. The US uses W-9/W-8BEN forms for tax identity and 1099-series information returns; the EU's DAC7 directive makes platform operators report seller income to tax authorities. Each is a report generator reading the same ledger and tax profiles, parameterized by the pack. Thresholds change (the US 1099-K threshold has been changed several times recently), which is exactly why they live in the pack with effective dates rather than in code.
Worked example: onboarding one partner into two countries
A delivery platform wants weekly payouts to 40,000 couriers in Germany and 60,000 in Brazil.
| Germany pack (DE) | Brazil pack (BR) | |
|---|---|---|
| Rail | SEPA Credit Transfer (batch), SEPA Instant for express | Pix (instant, runs around the clock) |
| Recipient ID | Name, IBAN (international bank account number), date of birth; document check above the pack's volume tier | Name, CPF (Brazilian individual taxpayer number), Pix key |
| Tax | Income data feeds the DAC7 platform report | Local reporting per the BR pack |
| Originating entity | EU licensed entity | Local partner institution |
Partner work: choose allowed_countries = [DE, BR], payout_schedule = weekly, a fee plan. No code. Load in one run: 100,000 payouts. If the orchestrator processes a batch in chunks of 1,000 with ten parallel workers, that is 100 chunks, 10 rounds of work per run. Ledger postings: each payout writes 3 to 4 ledger transactions: funding and submission always happen, tax withholding only when it applies for that recipient's country, and one more on settlement once the rail confirms. Each transaction posts one debit and one credit (a balanced pair), so 3 to 4 transactions means 6 to 8 ledger entries per payout, not a flat "three pairs plus one" regardless of whether tax applies. For a capacity estimate we take the conservative upper bound, 4 transactions (8 entries) per payout: roughly 100,000 × 4 = 400,000 ledger transactions (800,000 entries) per weekly run, which a single well-indexed relational ledger handles comfortably as a batch.
Trade-offs and pitfalls
- Rules engine versus code. A generic rules language becomes an unreviewable second programming language. Keep packs declarative (thresholds, lists, enums) and put genuinely novel behaviour in a new adapter or activity with code review.
- Prefunding versus paying on receipt. Requiring the partner to prefund removes credit risk (the risk that the partner never repays money the platform already advanced) and simplifies the ledger; paying before funds arrive is a credit product and needs underwriting (assessing the partner's ability to repay before extending that credit).
- Instant rails are irrevocable. Pix and SEPA Instant settle in seconds, so screening must finish before submission; on batch rails you sometimes have time to recall.
- Returns come late. An ACH return can arrive days after (the US bank network rejecting or reversing a transfer after it initially looked successful, for example a closed account or insufficient funds) "success". Treat submission as
in_transit, notpaid, and never let a partner re-pay a recipient until the original is definitively returned. - Common wrong turn: storing per-partner
ifstatements "just for this big customer". Every exception becomes a permanent fork; offer it as a pack option or decline it.
Design the architecture for scoring a payment for fraud risk inside the authorization path, where the entire decision (rules plus model) must complete within a strict latency budget of roughly 100ms. Cover how you'd decide fail-open versus fail-closed when the scoring service is slow or unavailable, how chargeback outcomes feed back into the system over time, and how you'd safely roll back a scoring change that starts degrading approval rates.
Sample Answer
Direct answer
Treat the 100 ms as a hard deadline that the scoring service owns end to end: every input the decision needs is precomputed and read from memory, rules and the model run in parallel against a fixed per-stage budget, and when the deadline hits the service returns a decision from a cheap local fallback instead of waiting. Whether that fallback leans "approve" (fail-open) or "decline/step up" (fail-closed) is a per-segment business policy computed from expected loss, not a global switch; for most card traffic it is fail-open with guardrails. Chargebacks (a cardholder's bank forcibly reversing a payment after a dispute) come back weeks later as labels (the fraud or not-fraud outcome attached after the fact to a past decision) that flow into offline analysis and model retraining (updating the model with those new examples), never into the live request. And every rule set and model ships as an immutable, versioned bundle behind shadow mode and a canary, so rollback is a pointer flip triggered automatically by an approval-rate guardrail.
Requirements I am designing to
- Deadline: p99 (the 99th-percentile latency, the time 99 of 100 requests beat) of about 100 ms for the full fraud decision, measured at the authorization service that calls us. The issuer round trip is outside this budget.
- Decision: approve, decline, or step-up (send the customer through 3-D Secure, the issuer's authentication challenge), plus a reason code and the bundle version that produced it.
- Availability: the payment path must not go down because fraud scoring did. A fraud outage that stops all checkouts is itself a revenue incident.
- Traffic: I will use 2,000 TPS (transactions per second) at peak for the arithmetic below.
Architecture
flowchart LR
AUTH[Authorization service] -->|deadline 100ms| GW[Scoring API]
GW --> FS[(In-memory feature store)]
GW --> RULES[Rule evaluator in process]
GW --> MODEL[Model server]
GW --> FB[Local fallback policy]
GW -->|async| LOG[(Decision log)]
STREAM[Payment and dispute events] --> AGG[Streaming aggregates]
AGG --> FS
LOG --> LABEL[Label join with chargebacks]
LABEL --> TRAIN[Offline retrain and rule review]
TRAIN --> REG[(Versioned bundle registry)]
REG --> GW
The critical rule: nothing on the request path does work that could be done earlier. Velocity counts ("attempts on this card in the last 10 minutes"), device reputation, customer history and merchant risk tiers are maintained by a streaming job (a program that continuously updates its output as new events arrive, instead of running on a fixed schedule) and written into a low-latency key-value store (an in-memory store such as Redis, or an in-process cache for slow-changing data). The request path only does point reads by key. No joins, no calls to the ledger (the system of record for completed payments and balances), no third-party lookups without their own hard timeout.
Budget allocation
| Stage | Budget | Notes |
|---|---|---|
| Network into and out of the scoring service | 10 ms | Same region, persistent connections |
| Parse and enrich from the request payload | 5 ms | BIN (bank identification number, the card's first digits) lookup from memory |
| Feature fetch | 25 ms hard timeout | All keys fetched in parallel in one batched round trip |
| Rules and model | 30 ms hard timeout | Run in parallel once features arrive; rules are cheap, the model is the long pole |
| Combine and respond | 5 ms | Decision log written asynchronously |
| Total on the critical path | 75 ms | 10 + 5 + 25 + 30 + 5 |
| Headroom | 25 ms | Garbage-collection pauses (brief stalls while the language runtime reclaims memory), a retry to a second feature replica, queueing at peak |
Why the headroom matters: tail latencies compound. If a request makes k independent parallel calls and each is slower than its own p99 1% of the time, the chance at least one is slow is
P(at least one slow)=1−0.99kFor k=5 that is 1 − 0.951 = 4.9%, so a request with five fan-out calls hits a p99-slow dependency about once in 20 requests. The design answers this by batching feature reads into one round trip, hedging (sending a duplicate read to a second replica if the first has not answered after a short delay), and treating each stage's budget as a timeout that falls through to defaults rather than waiting.
Deadline propagation
The authorization service sends the absolute deadline with the request. Each stage computes remaining time and gives up when it runs out: a missing feature becomes an explicit "unknown" value the rules and model were trained to handle, and a model timeout means the decision is made by rules plus fallback. The scoring API always answers before the deadline; it never lets the caller's own timeout be the thing that fires.
Fail-open versus fail-closed
Fail-open means approving (letting the issuer decide) when we cannot score; fail-closed means declining or stepping up. The right answer is the one with the lower expected cost for that segment, so compute it.
Illustrative inputs (not measurements): at the 2,000 TPS peak stated above, a 10-minute scoring outage is 2,000 × 600 = 1,200,000 payments; average ticket 60 USD; baseline fraud rate on this traffic 0.3%.
- Fail-open loss ≈ 1,200,000 × 0.003 × 60 = 216,000 USD of fraud, plus chargeback fees and some dispute-rate damage.
- Fail-closed loss ≈ 1,200,000 × 0.997 × 60 = 71,784,000 USD of good sales declined, plus customers who do not come back.
For ordinary card traffic, fail-open wins by more than two orders of magnitude (216,000 USD versus 71,784,000 USD, about 330 times less). But "open" should never mean "unguarded". The fallback policy is a small, fast rule set compiled into the scoring service itself, with no external dependencies:
- hard caps on amount per transaction and per card during degraded mode;
- a denylist of known-bad cards, devices and BIN ranges held in memory;
- step-up to 3DS instead of approve for transactions above a threshold, which shifts fraud liability toward the issuer where 3DS applies;
- fail-closed for segments where the arithmetic flips: gift cards, crypto purchases, high-value electronics, or a merchant currently under active card-testing attack (an attacker running many small, automated authorizations to find which stolen card numbers still work), where fraud rates are high and goods are instantly resellable.
The policy is data (per merchant category and amount band), is reviewed by the risk team, and every degraded-mode decision is tagged so it can be reviewed and its losses measured afterwards.
The chargeback feedback loop
Chargebacks (the cardholder's bank forcibly reversing a payment after a dispute) are the ground truth for fraud, but they arrive late: card networks typically let cardholders dispute within about 120 days, and most disputes arrive well inside that. The architecture accepts that delay instead of fighting it:
- Decision log. Every decision is written with the payment ID, the features actually used (as read, including which were missing), the bundle version, and the outcome. This is what makes later analysis honest: you train on what the system saw, not on today's recomputed values.
- Label join. Dispute events from the PSP (payment service provider) and settlement reports are joined back to the decision log by payment ID. Early fraud warnings (issuer fraud reports such as Visa TC40 and Mastercard SAFE data, which often precede or replace a formal dispute) give an earlier, noisier label.
- Label maturity (waiting long enough after a payment for its true fraud-or-not outcome to be known before trusting it as a training label). A payment only counts as "not fraud" once it is old enough that most disputes would have arrived. Retraining on last week's payments treats not-yet-disputed fraud as good traffic.
- Fast path for rules. Rules react in hours (an analyst writes a rule for a new pattern and ships it through the same canary); the model retrains on a slower cadence. Chargeback outcomes also feed the streaming aggregates (the same continuously updated feature values the streaming job maintains) directly: a card with a fresh fraud dispute goes onto the denylist immediately.
- Approved-only bias. You only observe chargebacks on payments you approved. Holding back a tiny random slice of would-be declines for review, or routing them to 3DS instead of declining, is how you learn whether the rules are rejecting good customers.
Safe rollout and rollback
A bundle is an immutable, versioned artifact: rule set, model, feature schema, thresholds and fallback policy, together. The scoring service holds a pointer to the active bundle and can hold a second one.
- Shadow: the candidate bundle scores live traffic alongside the active one; only the active decision is enforced. Compare decision distributions by segment.
- Canary: the candidate enforces on a small, randomly assigned slice (say 5%) of traffic, assigned by hashing the payment ID so it is stable.
- Guardrails: automatic rollback when approval rate, decline rate, step-up rate or issuer decline rate for the canary diverges from control beyond a threshold.
- Rollback: repoint to the previous bundle, which every node already has loaded. No deploy, no restart.
Set the threshold from the noise, not from intuition. At the 2,000 TPS peak, a 5% canary over 5 minutes sees 2,000 × 0.05 × 300 = 30,000 payments. With a 90% approval rate the standard error (roughly, how much this percentage would wobble from sample to sample by chance alone, computed as sqrt(p(1-p)/n)) of the canary's approval rate is
300000.9×0.1≈0.00173that is about 0.17 percentage points (0.18 pp for the difference against the much larger control group, which adds a little of its own, smaller sampling noise). A three-standard-error threshold is then about 3 × 0.18 ≈ 0.54 pp. A real 2 pp drop sits (2 − 0.54) / 0.18 ≈ 8 standard errors above that threshold, so it is caught with near certainty inside one 5-minute window; only a drop within about a percentage point of the threshold would need a longer window or a bigger canary to tell from noise, which is exactly the trade-off to state out loud.
Approval rate alone is not enough: a bundle that approves more is also dangerous. Guard both directions, and keep a delayed guardrail on early fraud warnings and dispute rate for the weeks after full rollout, since that is where a too-permissive change shows up.
Trade-offs and pitfalls
- Synchronous feature computation ("just query the last 30 days of transactions") is the most common way a 100 ms budget becomes 800 ms at peak.
- Global fail-closed looks safe and is usually the most expensive choice; global fail-open without caps is exploited within hours once attackers notice.
- Training-serving skew: features computed one way in the stream and another way offline produce a model that scores well in evaluation and poorly in production. Logging the served features avoids it.
- Rollback that requires a deploy is not a rollback under incident conditions; keep the previous bundle hot.
- Timeouts that are not tested: run chaos tests (deliberately injected failures, used to check the system degrades the way it was designed to) that stall the model server (the service that runs the fraud model and returns a score) and the feature store (the low-latency key-value store described above), and assert that the fallback answers within the deadline.
Compare synchronous (authorize-and-capture inline) versus asynchronous (authorize now, capture later) payment capture flows. Analyze the trade-offs in customer experience, latency, risk exposure, reconciliation complexity, and how chargebacks and refunds are affected, and recommend when you'd use each pattern.
Sample Answer
Direct answer
Capture immediately when you deliver immediately: digital goods, subscriptions, instant services. Authorize at checkout and capture later when the final amount or the fulfilment date is not known at checkout: physical goods that ship later, hotels, car rental, ride-hailing, restaurants with tips. Delayed capture lowers the cost of cancellations (a void instead of a refund) and aligns the charge with delivery, which reduces "item not received" disputes; the price is extra states to manage, the risk that an authorization expires before you capture (typically 7 days for an online card payment), and more reconciliation work.
The two flows
- Synchronous (authorize and capture inline): one call reserves and claims the money. The customer's bank shows a charge that will post; nothing more for the merchant to do.
- Asynchronous (authorize now, capture later): the checkout call places a hold (an authorization: the issuer reserves the amount but no money moves). A later capture call, from the fulfilment system, claims all or part of it. Uncaptured holds are released by a void (cancelling the authorization) or by expiry.
- Customer-initiated vs. merchant-initiated: a customer-initiated payment is authorized while the customer is actively completing checkout, in real time, whether that checkout is online or at a physical terminal. A merchant-initiated one is charged later off a payment method saved earlier, with no customer present at all, such as a subscription renewal or a no-show fee. The card networks give the two different authorization-expiry windows, which matters for how long you can wait before you capture.
In both, the customer waits for the authorization, so checkout latency is essentially the same. The difference is when money is claimed and what the merchant must do afterwards.
Trade-off analysis
| Dimension | Capture inline | Authorize now, capture later |
|---|---|---|
| Customer experience | Simple: charged once, immediately. But charged for items that may be backordered or cancelled | Customer sees a pending hold; for split shipments may see several captures. Cancellation before shipping just releases the hold |
| Latency | Same authorization latency at checkout | Same at checkout; capture is a later background call |
| Risk exposure | Money in hand early; lowest risk of failing to collect | Authorization can expire before capture (Stripe documents 7 days for customer-initiated online card payments on the major networks, 5 days for Visa merchant-initiated ones); re-authorizing later can be declined |
| Cancellation cost | A refund: a new money movement that takes days to appear, and processing fees are often not returned | A void: the hold disappears, usually no processing fee |
| Reconciliation | One event per payment; settlement follows capture date | More states (authorized, partially captured, voided, expired) and a time gap between order and settlement; partial captures mean one order maps to several settlement lines |
| Chargebacks | Charging before delivery raises "not received" and "cancelled" dispute exposure if fulfilment slips | Capturing on shipment gives delivery evidence that lines up with the charge date; an authorization that was voided cannot be charged back because no money moved |
| Refunds | Every change after purchase is a refund | Price adjustments before capture are just a smaller capture (a partial capture releases the rest) |
Recommendation
- Digital goods, subscriptions, instant services: capture inline. Delivery is immediate, so there is no gap to protect, and a second step only adds failure modes.
- Physical goods shipped within a few days: authorize at checkout, capture per shipment. Cancellations become voids, and the charge date lines up with delivery evidence.
- Amount not known up front (tips, ride fares, hotel incidentals, weighed groceries): authorize an estimate, capture the final amount. Capturing less releases the remainder; capturing more than authorized is only possible for eligible payments (sometimes called overcapture), so size the estimate conservatively.
- Fulfilment that can run past the authorization window (preorders, made-to-order): do not rely on a hold. Either capture inline with a clear refund policy, or save the payment method with the customer's consent and charge when you ship.
What would flip the choice: high cancellation or out-of-stock rates push toward delayed capture; a high rate of expired authorizations (fulfilment slower than expected) pushes toward inline capture or save-and-charge-later.
Worked example
An order totals 120.00 USD, paid online by Visa on day 0 while the customer is checking out (customer-initiated, the category the 7-day window governs). Two items ship separately: 70.00 on day 2 and 50.00 on day 9.
- Inline capture: 120.00 charged on day 0. The second item turns out to be out of stock on day 9: refund 50.00. The customer sees 120.00 charged then a 50.00 credit several days later, and the merchant may have paid processing fees on the full 120.00.
- Auth-then-capture with a single capture: capture 70.00 on day 2. On most payment setups a partial capture releases the rest and you cannot capture again, so the 50.00 is gone. This is the trap.
- Auth-then-capture done correctly, for this timeline: where the processor and card support it, multicapture (several captures against one authorization) is generally the better tool, because both shipments stay tied to a single authorization and a single fraud check. It does not work here, though: multicapture still requires every capture to land before the authorization expires, and day 9 is past the 7-day window, so by day 9 the original authorization is already gone. For this order, the correct move is to capture 70.00 on day 2 against the original authorization, then create a new, separate payment for 50.00 at shipment on day 9 using the saved payment method (stored with the customer's consent), rather than trying to draw on an authorization that no longer exists.
The system needs a scheduled job that, for every open authorization, captures or voids before its expiry, and alerts on any that will lapse; this is also where the reconciliation for "authorized but never captured" lives.
Pitfalls
- Forgetting to capture: revenue silently disappears when authorizations expire. Monitor authorizations by age.
- Assuming one capture per order breaks split shipments.
- Authorizing a large estimate ties up the customer's credit and generates complaints; networks also expect the authorized amount to be a genuine estimate.
- Treating a hold as revenue in reports overstates sales and confuses reconciliation.
Unlock Full Question Bank
Get access to all 15 Payment and Transaction Processing Systems interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.