Real-Time Transaction Risk Scoring System Design
Machine LearningModel answerLast updated
Design an end-to-end ML system that scores payment transactions in real time and decides whether to approve, block, challenge, or escalate them.
Scenario
You are joining the risk engineering team at a high-volume online payment platform processing around one billion transactions per month. The business loses revenue to fraudulent transactions but also loses customers when legitimate purchases are incorrectly blocked. Your task is to design the machine learning system that sits inside the transaction authorization path and assigns a risk score to each transaction.
The system's output drives one of four decisions: approve, block, challenge (trigger step-up authentication), or send to manual review. Review-queue capacity is finite, so the system cannot punt every uncertain case to humans.
What to cover
1. Problem framing and trade-offs What are the competing business objectives? How do you turn them into a cost function or optimization target? What latency budget does the system have, and why does it matter?
2. Training data and labels Where do fraud labels come from, and what are their failure modes? How do you handle the fact that blocked transactions never receive labels? What does point-in-time correctness mean here, and how do you enforce it?
3. Feature engineering What signals do you extract from the transaction itself, the cardholder, the merchant, the device, the IP, and historical behavior? What role do graph-based features play, and how do you keep velocity features fresh?
4. Modeling Which model family fits this problem, and why? How do you handle severe class imbalance (roughly 0.1% fraud rate)? How do you deal with the fact that chargebacks can arrive weeks or months after the transaction?
5. Serving architecture Sketch the real-time pipeline from checkout event to decision. Where do features come from online, and what are their freshness requirements? What happens when a downstream dependency times out?
6. Evaluation, thresholds, and experimentation Which metrics reflect business value better than raw accuracy? How do you set and tune decision thresholds? How do you run an A/B test on a fraud model safely?
7. Monitoring and adversarial robustness How do you detect model degradation before it shows up in chargeback rates? How does the system respond when fraudsters adapt their behavior?
Constraints and assumptions
- ~400 TPS average, up to ~8,000 TPS during peak sales events
- p99 end-to-end latency budget for risk scoring: ~100 ms, with ~30 ms for feature retrieval and ~10 ms for model inference
- Chargeback labels arrive anywhere from a few days to 120+ days after the transaction
- Manual review team can handle a fixed number of cases per day (on the order of a few thousand)
- The system must be explainable enough to produce reason codes for merchant dashboards and internal review
A strong answer demonstrates that you understand the production ML concerns — not just the modeling choices — and can reason through the trade-offs between fraud loss, false positives, user friction, and operational cost.
Hints
Hint 1
Before choosing a model, frame the problem as expected-cost minimization rather than binary classification. Different actions (block vs. challenge vs. review) have different costs, and the optimal decision depends on both the predicted probability and the transaction amount.
Hint 2
Blocked transactions are permanently unlabeled — the model never finds out whether they were actually fraudulent. Think about how you would use a small exploration holdout and propensity weighting to correct for this selection bias in both training and offline evaluation.
Hint 3
Velocity features (counts and sums over short windows keyed by card, device, IP) are among the highest-signal inputs and the hardest for fraudsters to fake, but they require near-real-time updates. Separate your feature store into two tiers: a streaming tier updated within seconds for velocity signals, and a batch tier updated hourly or daily for graph and merchant-level features.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements and Scale
Pin down the numbers first, because they constrain every later design choice.
- ~400 TPS average, ~8k TPS peak; feature store and model serving must handle the spike without degradation.
- Fraud rate ~0.1% by transaction count, higher by dollar volume — fraud skews toward large amounts.
- End-to-end latency budget: ~100 ms p99 inside the authorization path. Feature fetch ~30 ms, model inference ~10 ms, decision logic ~5 ms, with the rest as network and overhead.
- Chargeback labels arrive 1–120+ days post-transaction.
- Review queue capacity is fixed; the model must triage, not outsource.
2. Problem Framing: Expected-Cost Minimization
Raw accuracy or even AUC does not map to business outcomes. Frame the objective as minimizing expected cost per decision.
For a transaction with fraud probability p and transaction amount A:
- Approve: expected cost =
p × (A + chargeback fee + network penalty) - Block: expected cost =
(1 − p) × (lost margin + customer lifetime value impact) - Challenge (3DS): a friction cost — roughly 10–20% of legitimate users abandon — but liability shifts and most fraud fails step-up auth, so net cost is lower than blocking for mid-range risk
- Review: analyst cost plus decision latency; used only in the uncertain middle band, capped at queue capacity
This gives risk bands rather than a single threshold, and the bands should be tunable per merchant — a digital-goods merchant with near-zero cost of goods tolerates very different trade-offs than a luxury retailer.
Common mistake: setting a single global threshold without accounting for amount. A 60% fraud probability on a $5 transaction warrants a different decision than 60% on a $2,000 transaction.
3. Labels and Training Data
Positive signals:
- Chargebacks with fraud reason codes (definitive, but delayed)
- Issuer early fraud warnings (TC40/SAFE) — arrive within days, useful as fast labels
- Manual-review verdicts marked as confirmed fraud
- Merchant-reported fraud refunds
Negative labels: transactions that matured 90+ days with no fraud signal.
Key pitfalls:
Point-in-time correctness. Features must reflect what was knowable at scoring time — never include post-transaction signals when training. The cleanest solution is to log the exact feature vector served online and train directly from those logs. This eliminates training/serving skew by construction.
Selection bias from blocking. Blocked transactions never receive labels. If you train only on approved transactions, the model learns nothing about blocked patterns and can develop blind spots in exactly the high-risk region you care about most. Fix this with an exploration holdout: randomly approve ~0.5% of would-be-blocked, low-amount transactions, log their outcomes, and use inverse-propensity weighting when training and evaluating. The dollar exposure is bounded; the signal value is high.
Label noise and partial fraud. Many fraudulent transactions are never disputed. Treat unmatured negatives as "soft negatives" and weight confirmed labels more heavily. Also separate first-party fraud (friendly fraud, "item not received") from stolen-card attacks — they have different feature profiles and different appropriate responses.
4. Feature Engineering
| Entity | Representative features |
|---|---|
| Transaction | amount, currency, MCC, card-present flag, local hour of day, amount z-score vs. user baseline |
| Card | BIN country, card type, platform age, distinct merchants in 24h, decline count in 1h |
| User/account | account age, email domain age, payment methods added recently, shipping ≠ billing address |
| Merchant | rolling fraud/dispute rate, MCC category, new-merchant flag, volume anomaly vs. baseline |
| Device | fingerprint age, distinct cards seen on device in 24h, headless browser / emulator signals |
| IP | ASN type (proxy, Tor, datacenter), geo-distance from BIN country and shipping address |
| Velocity | counts and sums over 1m / 1h / 24h / 7d windows, keyed by card, device, IP, email |
| Graph | connected-component size linking cards-devices-emails-IPs, fraud rate among close neighbors, node embeddings from GNN or node2vec |
Velocity and graph features are the highest-signal because they capture ring attacks and card-testing bursts that look benign at the single-transaction level. They are also the hardest for fraudsters to fake, since doing so requires fresh, uncorrelated identities at scale.
For high-cardinality categorical IDs, use time-respecting target encoding or learned embeddings to avoid label leakage.
5. Model Choice, Imbalance, and Delayed Labels
Primary model: gradient-boosted trees (LightGBM or XGBoost).
- Handles heterogeneous tabular features natively
- Sub-millisecond CPU inference
- Robust to missing values (important when features time out online)
- SHAP values provide explainable reason codes for reviewers and merchant dashboards
Optionally ensemble with a DNN using entity embeddings or an LSTM over transaction sequences. The GBDT handles the bulk of the signal; the DNN captures temporal patterns in repeat-user behavior.
Maintain a rules engine alongside the model for hard blocks (sanctions-listed cards, known-bad device fingerprints) and for analyst-authored rules that can be deployed in minutes during an active fraud wave without waiting for a model retrain.
Handling class imbalance:
- Downsample negatives to roughly 1:20 fraud-to-legit ratio to speed training without discarding positives
- Weight samples by transaction amount if optimizing for dollar loss rather than transaction count
- Recalibrate predicted probabilities after downsampling — use Platt scaling, isotonic regression, or the analytic correction for the sampling rate; the cost function requires true probabilities, not uncalibrated scores
- Avoid synthetic oversampling (SMOTE): it creates unrealistic interpolations in mixed-type tabular data and provides no benefit over downsampling here
Handling delayed labels:
- Train on transactions that have fully matured (e.g., 120–30 days ago) to ensure stable labels
- Supplement with fast early signals (TC40 warnings, review verdicts) so the model sees recent patterns
- Evaluate on a temporally later held-out slice, never a random split — random splits leak future information and produce optimistic metrics
- Weight recent "unlabeled" negatives using the empirical chargeback-arrival curve: a transaction 20 days old with no chargeback is less certainly negative than one at 120 days
6. Online Serving Architecture
Checkout → API Gateway → Risk Service
├── Online feature store (Redis/KV, <10 ms)
│ ├── Streaming tier: velocity counters (seconds-fresh)
│ └── Batch tier: graph, merchant stats (hourly/daily)
├── GBDT model server (in-process, <10 ms)
├── Rules engine
└── Decision policy (cost bands + merchant thresholds)
↓
Log: features + score + decision → Kafka → data warehouse
Kafka txn events → Flink streaming → online store (velocity, seconds latency)
Spark batch jobs → online store (graph embeddings, merchant profiles, hourly/daily)
Feature freshness matters asymmetrically. Velocity counters must update within seconds — card-testing attacks fire dozens of transactions in a burst, and a stale counter misses the signal entirely. Graph and embedding features can be refreshed hourly without meaningful accuracy loss.
Graceful degradation. Fetch all feature groups in parallel with individual timeouts. If the graph feature group times out, fall back to a model variant trained without those features rather than failing the entire request. Never fail closed (block everything) unless the risk signal is already clearly high.
Two-stage scoring. The synchronous stage runs inside authorization, within the latency budget. A heavier asynchronous stage (graph models, sequence models) runs post-auth before capture or payout, and can trigger a hold, a review, or a refund without adding to checkout latency.
7. Evaluation, Thresholds, and Experimentation
Offline metrics:
- PR-AUC over ROC-AUC — at 0.1% prevalence, ROC-AUC is inflated and misleading; PR-AUC is sensitive to recall at the high-precision operating points that matter in production
- Dollar-weighted precision/recall — a model that catches 80% of fraud dollars at 5% false positive rate is more informative than one that catches 80% of fraud transactions
- KS statistic — how cleanly does the score separate fraud and legit distributions
Threshold setting: use the cost function from section 2 on a held-out matured slice. Tune separately by merchant tier if volume allows. Revisit thresholds when fraud patterns shift, not just when the model is retrained.
A/B testing: shadow-score with the challenger model before any traffic shift. When ramping live traffic, use merchant- or user-level splits rather than transaction-level splits — mixing treatment and control within a single user's session creates contamination. Detect significant differences in chargeback rate after the label maturation window (not immediately).
Monitoring:
- Feature distribution drift (PSI) on key features daily — shifts in velocity distributions often precede chargeback spikes by weeks
- Score distribution drift: a sudden shift toward the middle band suggests the model is losing confidence on a new pattern
- Business metrics: fraud rate, false-positive rate, review queue fill rate, manual override rate — these are the ground truth of whether the system is working
- Set up automated alerts on chargeback rate by merchant category and card BIN; anomalies there localize the problem faster than global metrics
Adversarial robustness: fraudsters observe their block rates and adapt. Mitigations include: deploying model updates on a rolling schedule so attackers cannot profile a static system, keeping rule updates rapid and separate from model retrains, using behavioral biometrics and device signals that are costly to spoof, and actively monitoring for probing patterns (many small test transactions) that precede large fraud waves.
Common mistakes to avoid:
- Training on a random split instead of a temporal split
- Reporting ROC-AUC without PR-AUC at very low prevalence
- Forgetting to recalibrate after downsampling
- Ignoring selection bias from previously blocked transactions
- Building a single global threshold when merchant risk profiles differ significantly