Designing a Live Card-Payment Fraud Scoring Pipeline
Machine LearningModel answerLast updated
Design an ML system that scores card payments inside the authorization path, handling extreme class imbalance, delayed labels, concept drift, and uneven costs of errors.
Context
A payments platform processes card transactions online. Each payment must be assessed for fraud while the customer waits, so the score has to be produced inside the authorization flow. Fraud is rare, fraudsters change tactics, and confirmed labels (such as chargebacks) can take weeks or months to arrive.
Task
Propose an end-to-end design for a system that flags fraudulent card transactions in real time. Your answer should cover:
- Requirements and success metrics: latency budget, throughput, class balance, and how you would define "good" when mistakes have unequal costs.
- Data sources and labels: what signals you would collect, where labels come from, and how you deal with label delay.
- Feature engineering: which kinds of features matter, and how you keep training data consistent with what was known at decision time.
- Modeling: which model families you would use, how you handle imbalance, and where unsupervised methods fit.
- Decisioning: how a score becomes an action (approve, extra authentication, review, decline) and how thresholds are chosen.
- Serving architecture: the online path, the offline path, and failure handling.
- Retraining and monitoring: cadence, feedback-loop bias, and how you detect drift.
State any assumptions (volumes, fraud rate, latency) explicitly and discuss the main trade-offs.
Hints
Hint 1
Begin with numbers: transactions per second, a rough fraud rate, and a latency budget for the whole scoring call. These drive nearly every later choice, including model size and feature lookups.
Hint 2
Frame the objective as total expected cost (fraud losses, wrongly blocked good customers, friction, reviewer time), not accuracy. Think about which metric stays meaningful at a very low positive rate, and how a score maps to several actions rather than one cutoff.
Hint 3
Consider what you can and cannot learn from the data: blocked payments never produce chargebacks, and labels arrive late. Think about logging the exact features served, holding out a small exploration slice, and watching both input distributions and delayed performance for drift.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify requirements
Assumptions I would state up front:
- Volume: about 5k transactions/sec on average, with peaks near 20k/sec on busy days.
- Latency: scoring is in the authorization path, so aim for p99 under 100 ms end to end. A rough split is about 20 ms for feature retrieval and a few ms for model inference, leaving room for network and rules.
- Base rate: roughly 0.1% of transactions are fraud, so data is highly imbalanced.
- Label delay: chargebacks arrive 30-90 days later. Customer reports and analyst decisions arrive in hours to days.
- Actions: approve, step-up authentication (3DS/OTP), send to manual review, or decline. Review capacity is finite.
- Objective: minimize total cost = fraud losses + lost revenue from false declines + friction cost + review cost.
Metrics: the primary metric is dollar-weighted recall at a fixed false-decline rate (for example 0.5%). Use PR-AUC as a secondary offline metric. ROC-AUC looks flattering at a 0.1% base rate and hides poor precision.
2. Data and labels
- Authorization stream: amount, merchant, MCC, channel (card-present or not), entry mode, timestamp.
- Customer and card profile: account age, typical spend, home geography, registered devices.
- Device and network: device fingerprint, IP geolocation, proxy/VPN/Tor flags.
- Merchant data: category, age, historical chargeback rate.
- Authentication outcomes: 3DS and OTP results, useful both as features and as weak labels.
- Labels: chargebacks (authoritative but slow), customer-reported fraud, analyst outcomes, and shared blocklists.
Because labels are late, training sets are built from transactions old enough to have matured, and fast signals are used for quick-reacting rules and for monitoring.
3. Features
Most signal comes from behavior relative to the entity's own history:
- Velocity: counts and sums per card, device, and IP over 1 minute, 1 hour, and 24 hours; distinct merchants per card; distinct cards per device (card testing).
- Deviation: amount z-score versus the card's 90-day history, first-time merchant or MCC, unusual hour.
- Geo: distance and implied speed since the last transaction, mismatches between IP, billing, and merchant country.
- Entity risk: merchant and BIN fraud rates with Bayesian smoothing for low volume, computed only from matured labels.
- Graph features: shared devices, emails, or addresses across many cards; connected-component size (fraud rings).
- Novelty/account takeover: new device, recent password or phone change, new shipping address.
Point-in-time correctness is essential. Use log-and-wait: persist the exact feature vector used at scoring time, then join labels later. This removes training/serving skew and leakage.
4. Modeling
- Rules layer: blocklists, sanctions, and impossible-velocity checks. Rules respond to a new attack in minutes, are explainable, and act as a fallback.
- Primary model: gradient-boosted trees (LightGBM/XGBoost). They perform well on tabular data, infer in under a millisecond, handle missing values, and support SHAP-based reason codes for analysts and regulators.
- Imbalance: downsample legitimate traffic (keep perhaps 5-10%) or use class weights, then recalibrate (Platt or isotonic) so scores reflect true probabilities. Calibration matters because thresholds are cost-based.
- Unsupervised/semi-supervised: isolation forest or autoencoders catch novel patterns not yet labeled. Use them as features or to route to review, not as sole decline triggers, since their false-positive rate is high.
- Advanced options: sequence models over a card's recent transactions; offline GNN embeddings pushed into the feature store.
- Segmentation: card-present and card-not-present behave differently; use separate models or a strong channel feature.
5. Decisioning and thresholds
Use cost-based logic rather than one cutoff. Decline when p(fraud) x amount exceeds the cost of a false decline. In practice use bands:
- Low score: approve.
- Medium: step-up authentication (cheap friction).
- Ambiguous and high value: manual review, sized to analyst capacity.
- High: decline.
Tune thresholds per segment (region, MCC, amount band) on a time-based holdout, and re-tune whenever the model or score distribution shifts.
6. Serving architecture
Auth request -> Gateway -> Scoring service (rules + model)
|-- Online feature store (Redis/Aerospike)
'-- Response -> decision
Scoring log -> Kafka -> Data lake -> Training pipeline
Labels (chargebacks, disputes, analysts) -> Label store -> joined to scoring log
- Streaming: a stream processor (e.g. Flink) maintains windowed velocity features; include the current transaction's contribution so bursts are not missed.
- Serving: load the model in-process, keep services stateless and horizontally scalable, and partition by card ID for cache locality.
- Offline path: daily batch jobs compute heavy features (graphs, 90-day profiles) and push them to the online store.
- Degradation: on feature-store timeout, fall back to rules plus a lightweight model on raw features. Choose fail-open versus fail-closed by amount tier.
- Analyst tooling: a case UI whose outcomes become labels.
7. Feedback loop, retraining, monitoring
Selection bias: declined payments never yield chargebacks, so the model only learns from what it approved. Mitigations: approve a small random slice of borderline traffic (exploration) with strict dollar caps, use step-up outcomes and analyst labels as additional ground truth, and apply inverse-propensity weighting where exploration probabilities are known.
Retraining: retrain on a regular cadence (weekly or biweekly) with a rolling window, validate on a later time-based holdout, and deploy via shadow mode, then canary, then full rollout with fast rollback. Trigger an out-of-cycle retrain on detected drift or a new attack pattern.
Monitoring:
- Inputs: PSI or KS tests per feature, missing-value rates, and feature-store latency and freshness.
- Scores: score distribution and decision-band rates (approve/step-up/decline) over time.
- Outcomes: early proxies (analyst-confirmed fraud rate, step-up failure rate, customer complaints) and matured metrics (recall, precision, dollar loss) as chargebacks land.
- Business: false-decline rate, review queue size, and fraud basis points.
8. Common mistakes
- Optimizing accuracy or ROC-AUC on a 0.1% base rate.
- Random train/test splits instead of time-based splits, which leak future behavior.
- Computing merchant fraud rates with immature labels, or from data that includes the target transaction.
- Forgetting calibration after downsampling, which breaks cost-based thresholds.
- Ignoring selection bias and training only on approved traffic.
- Using one threshold for all segments and amounts.
- No fallback path when the feature store is slow.
Trade-offs
Richer features (graphs, sequences) improve recall but add latency and operational complexity; precompute them offline where possible. Aggressive thresholds reduce fraud losses but raise false declines and customer churn; step-up authentication is the pressure valve between approve and decline.