Design a Real-Time Fraud Prevention Platform
Machine LearningModel answerLast updated
Architect a scalable, low-latency system to score payment transactions for fraud under severe class imbalance and delayed feedback loops.
Architect an end-to-end real-time fraud detection engine for an enterprise online marketplace. The service evaluates incoming card payment authorizations to block fraudulent behavior, issue verification challenges, or approve transactions.
Key Operational Constraints & Requirements
- Low-Latency & High-Throughput: The system must process an average of 5,000 transactions per second (TPS) with peaks reaching 30,000 TPS. Strict budget: total authorization flow budget allocation for fraud risk scoring is < 100ms at the 99th percentile ($p_{99}$).
- High Availability: Must maintain 99.99% uptime. System outages must fail open safely without blocking valid checkouts.
- Data & ML Challenges:
- Severe Imbalance: Fraud rates represent < 0.2% of all transactions (~1:500 ratio).
- Delayed Ground Truth: Confirmed negative/positive labels arrive asynchronously. User disputes and credit card chargebacks can take 30 to 90 days to finalize.
- Adversarial Drift: Tactics evolve quickly; static rules degrade over time.
System Requirements
Your architecture proposal should clearly cover:
- API & System Architecture: Define the primary risk scoring API contract and overall data flow topology.
- Data Engineering & Feature Infrastructure: How online features (real-time velocity aggregate features) and offline features are maintained without training-serving skew.
- Modeling & Training Strategy: Model selection, addressing extreme imbalance, calibrating probabilities, and adjusting business thresholds.
- Label Ingestion & Delayed Feedback: Techniques to train effectively given multi-week chargeback arrival latencies and selection bias from previously blocked transactions.
- Deployment & Monitoring: Continuous validation, shadow/canary rollouts, and detecting feature/concept drift.
Hints
Hint 1
Establish a clear latency budget Breakdown (e.g., Network + Online Store Lookup + Inference + Rules Engine) before designing the feature pipeline.
Hint 2
Address training-serving skew by combining a dual-storage Feature Store (Redis/DynamoDB + S3/Iceberg) with point-in-time correct joins or direct request-log join pipelines.
Hint 3
For delayed feedback, consider importance weighting based on empirical delay distributions, as well as an exploration slice to mitigate selection bias from declined transactions.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. High-Level Requirements & Operational Scale
System Scale & Latency Allocation
- Average Throughput: 5,000 TPS
- Peak Throughput: 30,000 TPS (design infrastructure for 3× peak = 90,000 TPS burst capacity)
- Target SLA: $p_{99} \le 100\text{ ms}$, Availability $\ge 99.99%$
- Base Fraud Rate: $\sim 0.2%$ (1 in 500 transactions)
Latency Budget Allocation ($p_{99} = 100\text{ ms}$)
+-------------------------------------------------------------------------+
| Total Budget: 100ms |
+--------------+-------------------+--------------------+-----------------+
| Network In/Out| Online Feature Fetch| Model Inference | Business Rules |
| (10ms) | (25ms) | (20ms) | (15ms) |
+--------------+-------------------+--------------------+-----------------+
| Reserved Buffer / Tail Latency Margin: 30ms |
+-------------------------------------------------------------------------+
2. API Contract
The API receives request context, returns a score alongside actionable business decisions, and executes synchronously within the payment flow.
Request Payload (POST /v1/risk/assess)
{
"transaction_id": "tx_9876543210",
"account_id": "acc_44129",
"timestamp": "2023-10-24T14:32:01.102Z",
"amount": 499.99,
"currency": "USD",
"payment_method": {
"card_hash": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"bin": "411111"
},
"device_context": {
"device_fingerprint": "dfp_a8f90c12",
"ip_address": "198.51.100.42",
"user_agent": "Mozilla/5.0..."
},
"shipping_address_hash": "addr_88192a"
}
Response Payload
{
"transaction_id": "tx_9876543210",
"fraud_score": 0.8421,
"action": "CHALLENGE_3DS",
"reason_codes": ["HIGH_VELOCITY_IP", "DEVICE_FIRST_SEEN_ABROAD"],
"model_version": "xgb_v2023_10_15_2",
"execution_time_ms": 34
}
3. System Architecture
+-----------------------+
| Client / Checkout |
+-----------+-----------+
|
v
+-------------+-------------+
| Risk Gateway API |
+------+--------------+-----+
| |
+--------------------+ +--------------------+
| |
v v
+-------------+-------------+ +-------------+-------------+
| Online Feature Store | | Rules Engine |
| (Redis / DynamoDB) | | (Hot-swappable rules) |
+-------------+-------------+ +-------------+-------------+
| |
+--------------------+ +--------------------+
| |
v v
+---------------------+------+
| Model Inference Service |
| (Champion / Shadow Pods) |
+--------------+-------------+
|
v
+--------------+-------------+
| Kafka Event Stream |
+--------------+-------------+
|
+--------------------------------+--------------------------------+
| |
v v
+---------------+---------------+ +-----------------+---------------+
| Stream Processing (Flink) | | Data Lake / Offline Feature |
| (Real-time aggregation window)| | Store (S3 + Apache Iceberg) |
+---------------+---------------+ +-----------------+---------------+
| |
+--------------------------------> <------------------------------+
|
v
+----------------+----------------+
| Batch Model Retraining Engine |
+---------------------------------+
4. Feature Engineering & Feature Store Infrastructure
Feature Categories & Compute Tiers
- Static / Low-Frequency (Batch computed daily via Spark):
- Account age, historical dispute count, average account transaction value over 90 days.
- Real-time Velocity Aggregates (Streaming computed via Apache Flink):
- Transactions on card hash in past 5 minutes, 1 hour, 24 hours.
- Unique device IDs attached to
account_idin past 24 hours.
- Request-Time Dynamic Features:
- Great-circle distance between current IP geo-location and primary shipping address.
- Exact time delta since last password reset or email update.
Preventing Training-Serving Skew
- Dual-Storage Feature Store (e.g., Feast / Hopsworks): Real-time values write to an Online Storage (Redis cluster configured with sub-5ms lookup latency) and simultaneously append to an Offline Storage (S3 data lake backed by Iceberg/Delta format).
- Log-and-Wait Design: To completely eliminate point-in-time calculation errors during model training, save the exact feature vector evaluated at prediction time directly to an immutable log stored in S3 via Kafka. Model training joins these exact served vectors with ground-truth labels once finalized.
5. Machine Learning Pipeline & Class Imbalance
Model Architecture Selection
- Champion Model: Gradient Boosted Decision Trees (XGBoost / LightGBM).
- Why GBDT? Exceptional performance on heterogeneous tabular data, sub-10ms native C++ CPU inference runtimes, natively robust to missing data, and supported by SHAP values for fast reason-code generation.
- Deep Learning / Graph Component: An auxiliary Graph Neural Network (GNN) run asynchronously to compute account risk graph embeddings (clustering shared credit cards, IP ranges, and device fingerprints). The resulting embedding vector is populated into the online feature store.
Handling Severe Class Imbalance (1:500 Ratio)
- Subsampling Negatives: Retain 100% of confirmed fraudulent transactions while downsampling legitimate transactions (e.g., 10:1 ratio).
- Logit Correction / Recalibration: Downsampling alters predicted class distributions. Adjust raw scores back to true baseline probabilities using the downsampling ratio $w$: $$\text{logit}(p_{\text{true}}) = \text{logit}(p_{\text{sampled}}) + \ln(w)$$ Follow up with Isotonic Regression on an un-sampled holdout set to ensure generated scores match true empirical probabilities.
- Loss Functions & Metrics: Avoid using raw Accuracy or standard ROC-AUC. Train optimizing for PR-AUC (Precision-Recall AUC) or Focal Loss. Evaluate using Recall at fixed Precision (e.g., Recall at 90% Precision) and Cost-Weighted Loss.
Business Threshold Mapping
Instead of static binary classification thresholds, dynamic cost optimization dictates the action:
$$\text{Expected Loss} = p \cdot \text{Transaction Amount}$$
- Score $< 0.15 \Rightarrow$ APPROVE: Low risk.
- $0.15 \le \text{Score} < 0.75 \Rightarrow$ CHALLENGE_3DS: Medium risk; prompt two-factor auth or 3D-Secure verification. Softens false positive friction.
- Score $\ge 0.75 \Rightarrow$ DECLINE: High risk; decline transaction immediately and assign manual review flag.
6. Delayed Labeling & Feedback Loops
The Delayed Ground Truth Problem
While immediate signals exist (e.g., failed OTP verification, rapid user account takeover calls), formal credit card chargebacks (TC40/SAFE reports) take 30 to 90 days to fully settle.
Transaction Event (Day 0)
├── Fast Label: OTP Failed / Rule Trigger (Hours)
├── Dispute Filed by Customer (Days 1–7)
└── Official Chargeback Finalized (Days 30–90)
Mitigation Strategies
- Out-of-Time (OOT) Training Window: Mask out the most recent 30–60 days of transaction data from training sets to avoid mislabeling un-matured fraud as definitive negatives. Validate models strictly on Out-Of-Time test splits (e.g., train on Jan–June, evaluate on July data after September maturity).
- Importance Weighting / Soft Labels: Assign sample weights to non-disputed transactions in the 0–30 day window based on a maturity survival probability $S(t) = P(\text{No chargeback observed by day } t)$.
- Exploration Slices for Selection Bias: Transactions declined by the model never generate sales or normal payment chargebacks, creating selection bias (unobserved counterfactuals). Allocate a tiny fraction ($\sim 0.5%$) of low-value, medium-risk transactions to bypass declines or route to 3DS step-up to gather unbiased ground-truth labels.
7. Serving, Deployment, & Adversarial Drift
Deployment Pipeline
[Model Registry] ---> Deployment Engine
├── 1. Shadow Deployment (100% async score mirroring)
├── 2. Canary Deployment (1% traffic gated by fallback)
└── 3. Full Production Rollout (Blue-Green Swap)
- Shadow Mode Execution: Deploy updated candidate models alongside the primary champion model. Incoming requests mirror features to the candidate asynchronously off the critical path. Evaluate candidate scores, latency, and outputs against historical labels before routing live traffic.
- Canary Rollout: Gradually route $1% \rightarrow 5% \rightarrow 100%$ of production traffic using dynamic account-level hash routing to ensure consistent candidate evaluation for individual users.
Resiliency & Edge Cases
- Circuit Breaking & Fallback: If latency spikes $> 70\text{ ms}$ or the model microservice throws $5\text{xx}$ errors, short-circuit inference calls. Fall back immediately to a lightweight, highly optimized local rules engine (evaluating basic high-risk BINs and transaction velocity limits) to guarantee sub-100ms response guarantees.
Detecting Adversarial & Feature Drift
- Population Stability Index (PSI): Monitor daily distribution shifts of online feature inputs. A $\text{PSI} > 0.25$ triggers automated alerts signifying feature drift.
- Unsupervised Anomaly Layers: Run an auxiliary streaming Isolation Forest or Autoencoder on request vectors. Sudden spikes in reconstruction errors highlight novel fraud patterns before chargeback labels arrive.
- Dynamic Rule Deployment: Provide risk operators with a high-throughput, low-latency rules engine (e.g., internal engine or custom Go/Rust rule evaluator) to instantly patch emerging attack vectors within minutes without requiring full model retrains.