Problem Statement
Design a system that scores payment transactions for fraud risk in under 100ms end-to-end (including network hops), combining deterministic rule-based checks with ML model scoring, at high transaction volume, with a continuous feedback loop for retraining and explicit management of the false-positive (legitimate transaction blocked, angry customer, revenue loss) vs. false-negative (fraud gets through, chargeback loss) trade-off.
Requirements Clarification
- Assume 5,000 transactions/sec average, 20,000 TPS peak (e.g., holiday shopping), globally distributed.
- Hard SLA: p99 decision latency ≤ 100ms from request received to allow/deny/challenge response, because this sits synchronously in the checkout path.
- Decision outcomes: ALLOW, DENY, CHALLENGE (step-up auth, e.g., 3DS/OTP) — a three-way, not binary, decision.
- Fraud rate assumption: ~0.1-0.5% of transactions are actually fraudulent; extreme class imbalance drives model and evaluation design.
- Business constraint: false-positive rate must stay very low (industry pressure — e.g., target <0.5% of legitimate transactions incorrectly challenged/denied) because blocking good customers has direct, measurable revenue and trust cost; false negatives are costed in chargeback-dollars and are more tolerable up to a budgeted loss threshold.
- Feedback loop: true fraud/not-fraud labels arrive late (chargebacks can take 30-90 days to materialize; some confirmed via customer dispute, some via card-network fraud reports) — label latency is a first-class design constraint, not an afterthought.
- Assume both card-present-like and card-not-present (e-commerce) flows; focus on card-not-present, higher fraud rate.
Architecture Diagram
┌───────────────────────────────┐
Merchant/Checkout ───request───▶│ API Gateway / LB │
└───────────────┬─────────────────┘
│ (p99 budget: 100ms total)
┌───────────────▼─────────────────┐
│ Real-Time Decision Engine │
│ │
│ ┌──────────────────────────────┐ │
│ │ Stage 1: Rule Engine (~2-5ms)│ │
│ │ - deterministic blocklists │ │
│ │ - velocity rules (in-memory) │ │
│ │ - hard DENY / hard ALLOW │ │
│ │ short-circuits │ │
│ └───────────────┬───────────────┘ │
│ │ (ambiguous cases)│
│ ┌───────────────▼───────────────┐ │
│ │ Stage 2: Feature Assembly │ │
│ │ (~10-20ms) │ │
│ │ - online feature store lookup │ │
│ │ (user velocity, device hist, │ │
│ │ merchant risk, geo mismatch)│ │
│ │ - request-time computed feats │ │
│ └───────────────┬───────────────┘ │
│ ┌───────────────▼───────────────┐ │
│ │ Stage 3: ML Scoring (~15-30ms) │ │
│ │ - ensemble: gradient-boosted │ │
│ │ tree (fast, tabular) + │ │
│ │ optional lightweight NN/ │ │
│ │ graph-embedding score │ │
│ │ - model served via low-latency │ │
│ │ in-process/co-located server │ │
│ │ (avoid extra network hop) │ │
│ └───────────────┬───────────────┘ │
│ ┌───────────────▼───────────────┐ │
│ │ Stage 4: Decision & Policy │ │
│ │ - threshold + business policy │ │
│ │ (risk score -> ALLOW/DENY/ │ │
│ │ CHALLENGE, tunable per │ │
│ │ merchant/segment) │ │
│ └───────────────┬───────────────┘ │
└──────────────────┼─────────────────┘
│ decision (sync response)
▼
Merchant/Checkout
Async, off critical path:
┌────────────────┐ ┌────────────────────┐ ┌───────────────────────┐ ┌────────────────────┐
│ Event Log/Kafka │──▶│ Feature Pipeline │──▶│ Online Feature Store │ │ Offline Data Lake │
│ (every txn + │ │ (streaming, updates │ │ (Redis/key-value, │◀──│ (all txns, features, │
│ decision) │ │ velocity counters, │ │ <5ms read SLA) │ │ labels when they │
└────────┬─────────┘ │ device/user graphs) │ └────────────────────────┘ │ arrive) │
│ └──────────────────────┘ └──────────┬─────────────┘
│ │
▼ ▼
┌────────────────────┐ ┌─────────────────────────┐
│ Chargeback/Label │────────────── labels (30-90 day lag) ──────────────────▶│ Model Retraining │
│ Ingestion (bank/ │ │ Pipeline (batch, periodic │
│ network feeds, │ │ + drift-triggered) │
│ manual review │ │ - shadow eval vs prod │
│ outcomes) │ │ - canary rollout │
└───────────────────────┘ └─────────────────────────┘
Key Design Decisions
-
Layered decision pipeline (rules first, then ML) vs. ML-only scoring.
- Chosen: cheap deterministic rules run first and can short-circuit (hard block known bad actors/blocklisted cards/impossible velocity; hard allow trusted low-risk repeat customers below a risk threshold), with ML scoring reserved for the ambiguous middle segment.
- Alternative: route every transaction through the ML model.
- Trade-off: rules-first reduces average latency (majority of low-risk repeat-customer traffic can be fast-pathed in 2-5ms) and gives instant, auditable response to known fraud patterns (e.g., a newly reported stolen-card BIN range) without waiting for model retraining, but rules require ongoing manual curation and can be gamed once discovered. ML-only is more adaptive but every transaction pays full latency and compute cost, and ML models are probabilistic/less auditable for hard compliance blocks.
-
Ensemble of gradient-boosted trees + lightweight graph/embedding signal vs. a single large neural model.
- Chosen: primary scorer is a gradient-boosted tree model (e.g., XGBoost/LightGBM-class) on tabular features — fast inference (sub-5ms), interpretable feature importances (needed for compliance/explainability requirements), well-suited to the structured, heterogeneous feature set (amounts, velocities, categoricals). Supplemented by a graph-based signal (e.g., precomputed device/account/card network-proximity-to-known-fraud-ring score) refreshed asynchronously.
- Alternative: a large deep learning / transformer-style sequence model over transaction history.
- Trade-off: deep models can capture richer sequential patterns but cost more at inference (harder to guarantee sub-30ms p99 at high concurrency), are harder to explain to compliance/regulators and dispute-resolution teams, and need much larger labeled datasets to avoid overfitting on a class-imbalanced problem. GBTs are the industry-standard choice for latency-critical, tabular, auditable fraud scoring; heavier models are more common as an offline/async secondary risk signal, not the hot path.
-
Online feature store with precomputed velocity counters vs. computing features live from raw transaction history at request time.
- Chosen: a streaming pipeline continuously maintains rolling aggregates (e.g., “transactions by this card in last 10 min,” “distinct merchants in last hour,” “device-to-account velocity”) in a low-latency key-value store (sub-5ms read), updated incrementally as new events arrive via Kafka.
- Alternative: query a transactional database for recent history at request time and compute aggregates on the fly.
- Trade-off: precomputed streaming aggregates keep the hot path fast and decoupled from raw-data query load, but introduce eventual consistency (a counter might lag by a few hundred ms behind the very latest transaction, which matters for burst/velocity fraud patterns happening within the same second) and adds pipeline operational complexity (exactly-once/at-least-once semantics, backfill on failure). Live computation is always fresh but cannot meet the latency budget at this volume/scale.
-
Three-way decision (ALLOW/DENY/CHALLENGE) with tunable, per-segment thresholds vs. a single global binary threshold.
- Chosen: risk score maps to a policy table that varies threshold by merchant category, transaction amount bucket, and customer segment, with a CHALLENGE middle tier (step-up authentication) to avoid outright denying ambiguous transactions.
- Alternative: one global score cutoff, binary allow/deny.
- Trade-off: a single global threshold either lets too much fraud through for high-risk segments or over-blocks legitimate transactions in low-risk segments — a one-size threshold cannot simultaneously satisfy both false-positive and false-negative targets across a heterogeneous population. Per-segment tunable thresholds plus a CHALLENGE tier let the business explicitly trade off friction vs. loss per segment (e.g., a $5,000 electronics purchase from a new device gets challenged rather than outright denied or blindly allowed), at the cost of a more complex policy management layer that itself needs governance/audit.
-
Delayed-label feedback loop design: how to retrain given 30-90 day label lag.
- Chosen: maintain two feedback signals — (a) fast, noisy proxy labels available quickly (customer disputes filed within days, velocity-pattern-confirmed fraud rings, manual review team outcomes) used for rapid drift detection and short-cycle retraining candidates, and (b) slow, high-confidence ground-truth labels from confirmed chargebacks/network fraud reports arriving weeks later, used for the authoritative periodic retrain and for calibrating the fast proxy’s precision. Every scored transaction and its features are logged immutably at decision time so training data can be reconstructed with the exact features seen in production, avoiding train/serve skew.
- Alternative: wait for full ground-truth labels before any retraining signal.
- Trade-off: waiting for full ground truth is the “correct” label but means the model can drift for months (fraud patterns evolve fast, e.g., a new attack vector) before a retrain reacts; using fast proxy labels enables quicker reaction but risks training on noisier, sometimes wrong labels, requiring careful loss weighting or a two-stage training approach (pretrain on proxy-heavy dataset, fine-tune on confirmed-label dataset).
-
Shadow/canary deployment for new model versions vs. direct hot-swap.
- Chosen: new model candidates run in shadow mode (scored alongside production model, decision not acted upon, purely logged and compared) for a defined evaluation window, then canaried on a small traffic percentage with real decisions and close false-positive/negative monitoring, before full rollout.
- Alternative: replace the production model directly after offline evaluation looks good.
- Trade-off: offline evaluation metrics (AUC, precision/recall on held-out historical data) can look good yet fail in production due to distribution shift or subtle feature-pipeline bugs; shadow+canary catches this before it causes real financial loss or customer friction, at the cost of slower rollout velocity and the operational overhead of running two models concurrently.
Scale Math
- 20,000 TPS peak. At p99 100ms budget split roughly: gateway/network 10-15ms, rules 2-5ms, feature assembly 10-20ms (dominated by feature-store network round-trip), ML scoring 15-30ms, decision/policy 2-5ms, response serialization/network 10-15ms — leaves margin for jitter.
- Feature store: needs to sustain 20,000 reads/sec (well within a well-sharded Redis-class cluster’s capability, typically >100K ops/sec per node) with sub-5ms p99; sized with replication for HA and sharded by card/account hash for even load.
- Kafka event log ingest: 20,000 events/sec × ~2KB avg event (transaction + features + decision) ≈ 40MB/sec sustained, ~3.4TB/day raw — retained ~90 days hot for the label-join window (~300TB), older data moved to cheaper cold storage in the data lake.
- Model serving throughput: a GBT model inference is typically sub-millisecond to a few ms per request on CPU; to hit 20,000 QPS with 15-30ms budget per call including any network hop, co-locate the model in-process with the decision engine (avoid a separate microservice hop) or use a low-latency model server with connection pooling; horizontal scaling of decision-engine instances (stateless) to N instances such that N × per-instance-QPS-capacity ≥ 20,000, with headroom (typically provision to 2-3x peak for burst absorption and rolling deploys).
- Fraud rate 0.1-0.5% of 20,000 TPS peak = 20-100 fraudulent transactions/sec at peak needing correct classification within a 0.5% false-positive budget on the other 19,900-19,980 legitimate transactions/sec — i.e., roughly under 100 wrongly-blocked legitimate transactions/sec tolerable at peak, which is still a large absolute number, underscoring why threshold tuning and CHALLENGE (rather than hard DENY) matters.
Failure Modes & How They’re Handled
- Feature store unavailable/slow: decision engine cannot get velocity features within budget. Mitigated with a strict per-call timeout (e.g., 15ms) and a degraded-mode fallback: if feature fetch times out, fall back to a reduced-feature model (rules-heavy, fewer ML features) rather than blocking the transaction entirely or failing open/closed blindly — fail-open with elevated rule strictness is typically preferred over hard-failing checkout, but this is a business policy decision made explicitly, not a silent default.
- Model server crash/latency spike: ML scoring stage fails. Mitigated by circuit breaker around the ML call — on repeated failures, engine falls back to rules-only decisioning (documented, monitored, alerts on-call) rather than blocking all checkouts; this degrades fraud catch rate temporarily but preserves availability, an explicit business trade-off.
- Label pipeline breaks (chargeback feed outage): retraining data silently goes stale. Mitigated with freshness monitoring/alerting on label ingestion lag, and retraining jobs that refuse to run (or flag as degraded) if label completeness for the training window falls below a threshold, preventing a retrain on an incomplete/biased label set.
- Adversarial adaptation (fraudsters probe thresholds): fraud patterns shift specifically to evade current rules/model. Mitigated by continuous drift monitoring on score distributions and fraud-rate-by-segment, fast-path rule updates (rules can be deployed in minutes, unlike model retrains which take longer), and periodic red-team/adversarial testing of the model.
- Train/serve skew: features computed differently in the offline training pipeline vs. the online feature store (e.g., a time-window boundary computed differently). Mitigated by logging the exact feature vector used at decision time for every transaction (not recomputing features from raw logs during training) — this guarantees the training pipeline sees exactly what production saw.
- Regional outage / latency spike in one geo: transactions from that region miss SLA. Mitigated by regional deployment of the full decision pipeline (feature store replicas, model servers per region) with local decisioning and only asynchronous replication to a global data lake, avoiding cross-region calls in the synchronous path.
Interviewer Follow-Up Q&A
Q: How do you decide the ALLOW/CHALLENGE/DENY thresholds, and who owns that decision? A: Thresholds are set via a policy layer, informed by a cost model that weighs the dollar cost of a false positive (blocked legitimate transaction — lost revenue + customer trust, often modeled as a multiple of transaction value) against the dollar cost of a false negative (chargeback loss + network fines + fraud team investigation cost). This is jointly owned by risk/fraud operations (business) and the ML/platform team (mechanism) — the platform team should not unilaterally pick a threshold; it exposes tunable per-segment thresholds and simulates historical impact (backtesting) before any threshold change ships, ideally behind the same canary process as model changes.
Q: Why not just always challenge (step-up auth) ambiguous transactions instead of trying to get the binary decision right? A: Challenge has real cost too — cart abandonment; a meaningful fraction of legitimate customers abandon checkout when hit with extra friction (step-up auth, OTP), so over-challenging is its own false-positive-like revenue loss. The three-way decision with tuned thresholds specifically minimizes total expected cost (blocked-revenue + friction-abandonment + fraud-loss), not just accuracy — challenge is reserved for the genuinely ambiguous middle band, not used as a blanket hedge.
Q: How would you detect that the model is degrading in production before enough chargeback labels arrive to prove it statistically? A: Monitor leading indicators that don’t require waiting for chargebacks: score distribution drift (population stability index between current scoring distribution and training-time baseline), manual-review-queue disagreement rate with the model, sudden shifts in ALLOW/CHALLENGE/DENY rate by segment, and business-visible proxy signals like customer complaint volume or dispute-filing rate (available faster than confirmed chargeback outcome). These are imperfect but actionable within days rather than months.
Q: The rules engine and ML model can disagree — how do you handle that, and how do you keep rules from becoming an unmaintainable pile over time? A: Rules only get authority to hard-short-circuit for high-confidence, low-ambiguity cases (explicit blocklist hits, impossible velocity); everything else flows to the ML stage, so disagreement is structurally limited to a narrow band. Rule lifecycle is governed like code: version-controlled, owned, with usage/hit-rate metrics tracked per rule, and a periodic review that retires rules with near-zero hit rate or that the ML model has functionally subsumed (verified by testing removal in shadow mode first).
Q: How would this design change for a card-present (in-store, chip/tap) scenario versus card-not-present e-commerce? A: Card-present fraud rates are typically an order of magnitude lower and the latency budget is even tighter (often <300ms end-to-end including the payment terminal round trip, well below e-commerce checkout tolerances), so the model tends to be simpler/faster (fewer, cheaper features, more reliance on chip-level cryptographic verification and terminal-reported risk signals already computed by the payment network) with correspondingly less reliance on the heavier online feature-store lookups used for e-commerce identity/device/velocity signals.