Real-Time Transaction Fraud Scoring System
Machine LearningModel answerLast updated
Design a complete ML pipeline to classify payment fraud in under 100ms, addressing delayed labels, streaming features, class imbalance, and cost-aware decisions.
Context
You're building a machine learning system to detect fraudulent transactions for a payment platform that handles checkout flows for thousands of online merchants. The platform processes roughly 500,000 transactions daily. Each time a customer completes a purchase, your model must return a risk score within 100 milliseconds to decide one of three outcomes:
- Accept the transaction immediately
- Challenge with additional verification (SMS code, 3D Secure authentication)
- Block the transaction outright
Operating Environment
- Volume: Peak load reaches 500 transactions per second; approximately 20 million monthly transactions
- Fraud prevalence: Around 0.15% of transactions are eventually confirmed as fraudulent
- Feedback latency: Chargebacks and fraud confirmations typically surface 30–90 days after the original purchase
- Data sources: Transaction details (amount, currency, addresses, IP, device ID), customer transaction history, merchant risk profile, payment instrument metadata
Your Task
Design the end-to-end fraud detection system. Address each of the following:
1. Training Labels Under Delayed Feedback
How do you define the fraud label when ground truth arrives months later? What strategy handles transactions that haven't matured yet, and how do you account for fraud that's never reported?
2. Feature Design for Low-Latency Scoring
Propose 4–6 strong predictive features spanning customer behavior, transaction velocity, and entity relationships. Explain how you compute time-windowed aggregations (like "transactions in the last hour") at serving time while avoiding temporal leakage during training.
3. Model Selection and Training with Extreme Imbalance
Recommend a model architecture considering both the 100ms latency budget and the 0.15% positive class rate. How do you train it without distorting probability estimates?
4. Offline Evaluation and Decision Boundaries
Which metrics should you track, and why are standard accuracy or AUC misleading here? How do you determine the two score thresholds that separate accept / challenge / block decisions?
5. Production Monitoring Before Labels Arrive
Fraud patterns shift constantly, but labels lag by months. What signals can you monitor to detect model degradation, distribution shift, or adversarial adaptation in near real-time?
Hints
Hint 1
Think about which transactions are safe to include in your training set based on label maturity time
Hint 2
Velocity features are powerful but require precomputed streaming aggregates with strict time boundaries
Hint 3
Calibrated probabilities enable threshold selection based on business costs, not just ranking performance
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Real-Time Transaction Fraud Scoring System: Model Answer
Overview
This problem tests your ability to build an ML system under operational constraints: ultra-low latency, delayed ground truth, severe class imbalance, and adversarial drift. Strong candidates connect four pillars: careful label construction, point-in-time feature engineering, calibrated probability outputs, and cost-based decision rules.
Quick baseline math to frame the problem:
- 20M transactions/month × 0.15% fraud rate = 30,000 fraud cases monthly—enough signal for a supervised model once labels mature
- At 500 TPS and a 1% false positive rate, you'd incorrectly block ~5 legitimate orders per second, roughly 7× the actual fraud volume, so precision is critical
- The 100ms end-to-end budget leaves ~10–20ms for feature retrieval and ~5ms for model inference
1. Training Labels Under Delayed Feedback
Label definition: Mark fraud = 1 if the transaction receives a fraud chargeback, merchant fraud report, or card issuer fraud alert (TC40/SAFE) within 90 days. Otherwise fraud = 0. Exclude non-fraud disputes like "item not received" unless you model them separately.
Training window strategy: Train exclusively on transactions at least 90–120 days old—for instance, use a 12-month training window ending 90 days ago. This ensures labels have matured; including recent transactions would wrongly treat unreported fraud as negatives and teach the model that emerging fraud patterns are safe.
Handling immature transactions:
- Proxy labels for recency: Use early fraud signals like issuer declines with fraud reason codes, account takeover flags, 3DS failures, or merchant cancellations marked as fraud. These can train a lightweight "early warning" model or serve as auxiliary features. Don't naively mix them into the primary label without adjustment.
- Survival modeling approach: Weight recent negatives by the fraction of eventual chargebacks that have historically arrived by that age. For example, if 70% of chargebacks surface by day 30, a 30-day-old negative could receive weight 0.7.
Unreported fraud (false negatives): Some fraud never generates chargebacks—small-value purchases, friendly fraud, or unmonitored cards. Mitigations:
- Entity propagation: If a card or device is confirmed fraudulent, retroactively flag earlier transactions sharing that entity within a short time window as likely fraud.
- Positive-unlabeled learning: Treat negatives as "unlabeled" rather than definitively clean, using techniques like weighted loss.
- Sample validation: Manually review a random sample of negatives to estimate the noise rate.
2. Feature Design for Low-Latency Scoring
High-signal features:
-
Velocity aggregates: Counts and total amounts per card token, device fingerprint, IP address, and email over sliding windows (1 minute, 1 hour, 24 hours). Also track distinct cards per device and distinct devices per card—key card-testing signals.
-
Cross-merchant activity: Number of unique merchants a card or device has transacted with in the past hour. This is a powerful indicator available only at the platform level, not to individual merchants.
-
Customer profile: Account age, count of prior successful orders, historical chargeback rate, and the z-score of the current transaction amount relative to the customer's purchase history.
-
Identity consistency checks: Distance between billing and shipping addresses, IP geolocation vs. billing country, card BIN country mismatch, disposable email domain flags.
-
Merchant risk context: Merchant's risk tier, trailing 30-day fraud rate, business category (electronics and gift cards carry higher risk), and how the order amount compares to the merchant's typical transaction size.
-
Payment instrument metadata: Card age since first use, issuer bank reputation, whether the card has been tokenized across multiple accounts.
Avoiding temporal leakage:
- Streaming feature computation: Use a stream processor (Kafka + Flink or Spark Streaming) to maintain sliding-window counters in a low-latency store like Redis or a feature store. Lookups complete in single-digit milliseconds.
- Point-in-time correctness: Each feature uses only events timestamped strictly before the current transaction. Add the current event to aggregates after scoring.
- Training-serving consistency: Log the exact feature vector served at inference time and train on those logs. Offline training must use "as-of" joins that respect event time ordering.
- Label-derived features: Features like "customer's prior chargebacks" must count only chargebacks known at transaction time, not future ones that arrive later.
3. Model Selection and Training with Extreme Imbalance
Recommended baseline: Gradient Boosted Decision Trees (LightGBM or XGBoost).
- Handles mixed feature types, missing values, and non-linear interactions naturally
- Inference on ~200–500 trees completes in 1–3ms on CPU
- SHAP values enable feature importance and debugging
- Easily retrainable as patterns shift
Logistic regression is a useful sanity check but misses critical interactions. Deep learning (RNNs, graph networks) offers more expressiveness but adds latency and operational overhead—consider them as feature generators (precomputed embeddings) rather than serving-path models.
Training under imbalance without breaking calibration:
- Use standard log-loss on the full dataset, or apply negative downsampling (e.g., 10:1 negatives:positives) followed by an analytic probability correction:
p_true = p_sampled / (p_sampled + (1 - p_sampled) / sampling_ratio). - Avoid SMOTE and synthetic oversampling—they distort feature distributions and hurt calibration.
- Class weights can be used for ranking but require post-hoc calibration via Platt scaling or isotonic regression on a held-out, time-forward validation set.
- After training, verify calibration using reliability diagrams (binned predicted probability vs. observed frequency) and expected calibration error (ECE).
Calibrated probabilities are essential because decision thresholds are set by expected cost, not ranking.
4. Offline Evaluation and Decision Boundaries
Why standard metrics fail:
- Accuracy: Predicting "never fraud" achieves 99.85% accuracy—useless.
- ROC-AUC: The massive negative pool dominates. An FPR of 0.5% looks small on a ROC curve but means thousands of false declines daily.
Better metrics:
- Precision-Recall AUC (average precision)—focuses on the minority class
- Recall at fixed precision or precision at fixed recall (e.g., recall at 1% decline rate)
- Dollar-weighted recall: Fraction of fraud losses (not just counts) prevented
- Calibration quality: Brier score and ECE
- Expected cost per transaction on an out-of-time holdout
Threshold setting via cost-benefit analysis:
Let:
- p = calibrated fraud probability
- L = fraud loss (transaction amount + chargeback fee, ~$25)
- M = cost of false decline (lost margin + customer lifetime value)
- f = cost of challenge friction (abandonment rate × M)
- r = effectiveness of 3DS challenge (fraud stopped or liability shifted, ~70%)
Expected costs:
- Accept:
p × L - Challenge:
f + p × L × (1 - r) - Decline:
(1 - p) × M
Decision rules:
- Accept when
p < T_low, whereT_low ≈ f / (L × r)(challenge cost ÷ benefit) - Challenge when
T_low ≤ p < T_high - Decline when
p ≥ T_high, where challenge and decline costs intersect
Because L scales with amount, thresholds are amount-dependent. Apply business constraints: maximum challenge rate for UX, decline rate caps, per-merchant risk tolerance. Validate on out-of-time data and roll out via A/B test with close monitoring of approval rate, fraud rate, and customer drop-off.
5. Production Monitoring Before Labels Arrive
Input distribution drift:
- Track PSI (Population Stability Index) or KL divergence for each feature, comparing daily distributions to training baseline
- Monitor feature nullness rates, quantile shifts, and correlation changes
- Alert on sudden changes in merchant mix or geography
Prediction distribution:
- Watch the distribution of fraud scores over time—shifts suggest either drift or adversarial adaptation
- Track acceptance, challenge, and decline rates daily—stable rates under stable traffic suggest stable behavior
Proxy outcome metrics (before chargebacks arrive):
- Issuer declines with fraud reason codes
- 3DS failure rate among challenged transactions
- Velocity of repeat entities: Spike in cards or devices appearing multiple times in short windows
- Manual review queue volume and outcomes (if human review is part of the workflow)
Model performance on labeled subsets:
- Run daily evaluation on the subset with early fraud signals (e.g., issuer fraud alerts, which arrive faster than chargebacks)
- Re-evaluate past predictions as labels mature to detect delayed degradation
Adversarial indicators:
- Sudden surge in new entities (cards, devices, IPs) without historical footprint
- Increase in low-confidence scores (entropy of predictions)—suggests the model sees unfamiliar patterns
- Geographic or merchant concentration anomalies
Continuous retraining cadence: Retrain weekly or biweekly on the most recent matured data (ending 90+ days ago). Deploy canary-style with holdout validation and rollback capability.
Common Mistakes to Avoid
- Training on recent unlabeled data, teaching the model that new fraud is safe
- Using accuracy or ROC-AUC as primary metrics
- Oversampling or SMOTE without recalibration
- Setting a single universal threshold instead of cost-based, amount-aware thresholds
- Temporal leakage: computing features with future data or training without respecting event time
- Ignoring calibration—treating the model as a ranker when probabilities drive business decisions
- Not monitoring until chargebacks arrive, missing weeks of degraded performance