ML System Design · Module 28 of 47 · 11 concepts · about 13 min

Design: Real-Time Fraud Detection

A complete design for scoring every Kirana Kart payment and refund for fraud before it completes: rare and late labels, velocity and device features, rules plus a model plus anomaly detection, a decision policy sized to the review team, and defending against fraudsters who adapt.

At work: Asked as 'design a fraud detection system' for payments, e-commerce, ads clicks or account sign-ups. It tests imbalance, label delay, real-time features and adversaries all at once.

Requirements

What it is

Clarify:

  • goal: cut fraud losses while declining or delaying as few honest customers as possible;
  • scale: about 630,000 payments and refund requests a day; peaks around 22 a second, far higher during sales;
  • latency: a decision within 100 ms (p99) at payment time, before the order is confirmed;
  • fraud types: stolen cards, fake accounts made for sign-up offers, refund abuse ('item never arrived'), account takeover;
  • constraints: a review team of 15 people; decisions must be explainable to reviewers; customers can appeal.

Why it matters

Each fraud type has different signals and labels, so name them.

  • The latency limit forces online scoring with precomputed and streaming features.
  • Review capacity turns the threshold into an operations question (below).

In the real world: Payment companies typically separate models (or at least labels and features) for card fraud, account takeover and promotion abuse.

Treating fraud as one problem. Refund abuse by real customers looks nothing like stolen-card fraud by strangers, and one undifferentiated model handles both poorly.

Framing

What it is

Turn the goal into an ML task with a decision layer:

  • target: probability the payment is fraudulent (confirmed by chargeback, reviewer decision or a later ban);
  • decision policy: allow, send to review, or block, by score bands and amount (module 3);
  • offline metrics: PR-AUC; precision and recall at the operating thresholds; cost of mistakes (module 16);
  • online metrics: fraud loss as a share of payment value; false decline rate; reviewer workload; customer appeals upheld.

Why it matters

Fraud is extremely imbalanced (module 7), so accuracy and ROC-AUC mislead.

  • Thresholds come from the cost of each mistake and the review team's capacity, and can change daily without retraining.
  • False declines are a real cost: an honest customer declined may never return.

In the real world: Kirana Kart prices a missed fraud at its average loss and a false decline at the lifetime value at risk, and sets thresholds from those prices.

Measuring only fraud caught. A model that blocks far more honest customers can 'catch more fraud' while losing more money than it saves.

Data and labels

What it is

Labels are rare, late and shaped by the system:

  • chargebacks arrive over weeks to 90 days (module 6);
  • reviewer decisions arrive within a day but only for reviewed cases;
  • later evidence: accounts banned for abuse, linked to earlier orders;
  • selective labels: blocked payments never produce chargebacks, so their truth is unknown;
  • holdout: a small random share of medium-risk payments is reviewed instead of blocked, to keep learning the truth (module 22).

Why it matters

Training only on matured labels means the model learns from patterns that may be months old.

  • Fast reviewer labels fill the gap for recent patterns.
  • Without a holdout, the model can never learn whether its blocks were right.

In the real world: Kirana Kart trains on payments 60 to 365 days old with matured labels, adds reviewer-labelled recent cases with higher weight, and keeps a 1% review holdout in the medium-risk band.

Training on last week's payments as if they were labelled. Most of their fraud has not been reported yet, so the model learns that new fraud patterns are safe.

Practise it: Design Model Monitoring, Design a Search Ranking System

Features

What it is

The strongest fraud features describe behaviour and links, not single facts:

  • velocity (streaming, sliding windows): payments, cards and addresses used by this account, device and card in the last 5 minutes, hour and day (module 10);
  • account: age, verified phone, past orders and refunds, past disputes;
  • device and network: device fingerprint, emulator signals, IP reputation, distance between IP location and delivery address;
  • payment: amount relative to the account's usual, new card on an old account, card country;
  • graph: how many accounts share this device, card, phone or address; links to accounts banned before.

Why it matters

Fraudsters can change names and emails easily; devices, payment instruments and networks of linked accounts are harder to fake.

  • Velocity captures bursts: many attempts in minutes.
  • Graph features catch rings of fake accounts that look innocent one by one.

In the real world: Graph features (accounts sharing a device or card with a previously banned account) are among the most predictive features at Kirana Kart, especially for sign-up-offer abuse.

Visual example

Features

Hard-to-fake signals carry the model.

Fraud features by kind and how they are computed
kindexamplecomputed
VelocityPayments by this device in the last 10 minutesStreaming
AccountAccount age; past refund rateBatch
Device and networkEmulator detected; IP far from addressOn-demand
PaymentAmount vs account's 90-day medianOn-demand + batch
GraphAccounts sharing this card or deviceBatch + streaming updates

Relying on easily changed features (email domain, name). Fraudsters learn within days which ones the model trusts.

Practise it: Design a Demand Forecasting Platform, Design a Predictive Maintenance System, Design a Real-Time Fraud Detection System, Design an ML Feature Store

Architecture

What it is

Three layers, each catching what the others miss:

  • rules: known patterns and hard limits, maintained by the risk team ('more than 3 cards on one account in an hour');
  • supervised model: gradient-boosted trees on the features above, scoring general risk (module 12);
  • anomaly detection: an unsupervised detector for unusual clusters of new accounts or orders, catching new schemes before labels exist;
  • decision service: combines the three with amount and customer history into allow, review or block.

Why it matters

Rules are fast to change and explainable; the model generalises; anomaly detection covers the unknown.

  • Keeping the decision in its own service lets the risk team change thresholds and rules daily.

In the real world: Almost every large payments fraud system pairs a rules engine with machine-learned scores; Stripe Radar, for example, lets merchants add rules on top of its model.

Visual example

Fraud

Three signals, one decision, within 100 ms.

Scoring one payment

  1. PaymentAmount, account, card, device
  2. Features~20 msBatch, streaming, on-demand
  3. three signals, in parallel
    RulesKnown patterns; hard limits
    ModelProbability and top reasons
    AnomalyUnusual cluster score
  4. Decide~2 msAllow, review or block
  5. Log and queueReviews queued with reasons
Payment request (amount, account, card, device, address)
  -> fetch features: account (batch), velocity (streaming), graph (batch),
     device and IP (on-demand)                                    ~20 ms
  -> rules engine: hard blocks and known patterns                    ~5 ms
  -> fraud model (LightGBM) -> probability + top reasons            ~5 ms
  -> anomaly score from the account's cluster (precomputed)
  -> decision service: allow / review / block by score band, amount
     and customer history                                          ~2 ms
  -> log decision, features, model version; write to review queue if needed
Timeout or failure: fail open below ₹1,000, hold for review above

Replacing the rules with the model. Rules handle newly discovered attacks the same day; the model needs labels and a retrain.

The decision policy and the review team

What it is

Two thresholds turn the score into actions:

  • block above the high threshold, automatically;
  • review between the two: a person decides, seeing the top reasons;
  • allow below the low threshold.

The low threshold must produce no more reviews than the team can handle; otherwise the queue grows and customers wait.

Why it matters

Review capacity is a hard constraint.

  • Module 16's cheapest threshold (0.3) would flood a 15-person team.
  • Raising the review threshold to fit capacity is a business decision, with the cost made visible: some fraud between the thresholds now gets through.
  • Better models raise precision in the band, so the same team catches more.

In the real world: Kirana Kart reviews payments scored 0.5 to 0.9; at 0.3 it would need more than twice its review team.

Visual example

Computed

630,000 payments a day; block above 0.9; each reviewer handles 480 a day. A team of 15 can handle the review band only from 0.5 up.

Flag rates per 100,000 from module 16
review fromreviews a dayreviewers neededfits a team of 15?
0.317,13636No
0.56,67814Yes
0.72,3945Yes

Setting thresholds from cost alone, ignoring capacity. The review queue backs up, orders wait for hours, and reviewers rush and make more mistakes.

Serving and failure handling

What it is

Scoring sits on the payment path, so it must be fast and safe when it fails:

  • features fetched in one batched call; the model is a few hundred trees, under 5 ms;
  • fail open or closed by amount: if scoring fails, allow small payments, hold large ones for review (module 4);
  • streaming velocity features with freshness checks and defaults (module 10);
  • the account risk score is precomputed in the stream after logins and profile changes, so payment-time scoring reads it instantly (module 18).

Why it matters

A fraud service outage must not stop all orders, nor open the doors entirely.

  • Splitting by amount limits both kinds of damage.
  • Precomputation keeps the payment-time path short.

In the real world: During a feature-store incident, Kirana Kart's fraud service fell back to rules plus defaults for 20 minutes; small orders flowed normally and large ones waited for review.

Failing closed for everything. One bad deploy then blocks every order across the country.

Practise it: Design Feature Monitoring, Diagnose Training-Serving Skew, Design a Model Serving Platform, Design an ML Feature Store

Evaluation

What it is

Fraud models are hard to evaluate quickly:

  • offline: on matured labels only; time split; PR-AUC, recall at fixed precision, cost at thresholds; slices by fraud type, city, payment method, new accounts;
  • shadow: run the challenger beside the champion for weeks until chargebacks mature, then compare on live data (module 20);
  • online: holdout-based comparison of loss and false-decline rates; reviewer overturn rate as a fast signal.

Why it matters

Label delay means a real verdict on a new model takes weeks.

  • Shadow mode gives that verdict without risk.
  • Fast proxies (overturns, appeals, disputes) catch obvious regressions in days.

In the real world: Kirana Kart shadows each new fraud model for six weeks before promotion, with a risk analyst approving the release.

A/B testing a fraud model on customers and reading the result after a week. Most of the fraud in the treatment group has not surfaced yet.

Practise it: Design a Large-Scale Classification Platform, Design a Predictive Maintenance System, Design a Real-Time Anomaly Detection System, Design a Recommendation System, Diagnose Training-Serving Skew, Improve a Low-Recall Model, Design a Search Ranking System

Monitoring and adversaries

What it is

Fraud models face people actively looking for gaps:

  • monitor: score distribution, flag and block rates by segment, reviewer overturns, appeals, chargeback rate by cohort age (module 21);
  • anomaly alerts: sudden spikes in new accounts from one device type, one area or one offer;
  • retrain weekly plus on triggers; layered defences so one evasion does not open everything (module 25);
  • do not reveal exact reasons to suspected fraudsters; reviewers see them, customers get general explanations.

Why it matters

Fraud patterns shift within days after a defence is deployed.

  • Rules give same-day responses to new attacks; the model catches up at the next retrain.
  • Cohort-based monitoring avoids false alarms from immature labels.

In the real world: When a new sign-up-offer abuse ring appeared using cheap new phones, Kirana Kart's anomaly detector flagged the cluster on day one; a rule blocked it that evening and the next retrain learned it.

Celebrating a falling chargeback rate. If the model is blocking more, fewer chargebacks can mean more honest customers turned away, not less fraud.

Practise it: Design Feature Monitoring, Design Model Monitoring

Interview questions: the fraud design

What it is

The questions interviewers ask about the fraud design, from the first screening call to the senior round. Cover the answer, say yours aloud, then compare.

Why it matters

Reading an idea and explaining it are different skills.

  • Each answer below is the two or three sentences an interviewer is listening for.
  • The reasoning behind each one is in the cards above. If an answer surprises you, go back to that card.

In the real world: Fraud interviews almost always reach label delay and the review team within fifteen minutes. A decision layer with two thresholds sized to capacity is a mark of experience.

Q: How do you handle extreme class imbalance?

Measure with PR-AUC and precision and recall at thresholds, use class weights or negative sampling with recalibration, and set thresholds from the cost of mistakes and review capacity.

Q: How do you deal with labels that arrive 90 days late?

Train on matured data, add fast reviewer labels with higher weight, monitor with proxies and cohort-based metrics, and shadow new models until labels mature.

Q: What features matter most?

Velocity over sliding windows, device and network signals, account history, amount relative to normal, and graph links between accounts, cards and devices: signals that are hard to fake.

Q: Why have rules as well as a model?

Rules respond to new attacks the same day and encode hard limits; the model generalises; anomaly detection catches new schemes. The decision service combines them.

Q: What happens if the fraud service is down?

Fail open for small payments, hold large ones for review, using rules and defaults where possible; never block everything or allow everything.

Q: How do you stop the model learning only from what it allowed?

A small random holdout in the medium-risk band that is reviewed rather than blocked, giving unbiased labels for the cases the model would have blocked.

Optimising recall alone, with no word on false declines or reviewers.

Practise it: Design a Real-Time Fraud Detection System

Exercise: design a fraud variant

What it is

A short build that uses this module's ideas. Write it yourself before looking anything up; the checks at the end tell you whether it works.

Why it matters

An idea you have only read fades in a week.

  • Building it once, even in fifty lines, is what makes it yours.
  • Interviewers can tell the difference between someone who has read about a loop and someone who has debugged one.

In the real world: Risk and trust-and-safety teams interview with exactly these variants.

Your task. Adapt this design to a different fraud problem and present it as in an interview.

Steps

  1. Pick one: fake reviews on a marketplace, click fraud on ads, or fake account sign-ups for a referral offer.
  2. Write requirements with numbers, the fraud types and the decision deadline.
  3. Define the label, its delay and its biases, and a holdout to counter them.
  4. List features in five kinds, marking which are hard to fake.
  5. Draw rules, model, anomaly detection and decision layer.
  6. Size the review team or the automatic actions for your volume.
  7. Plan evaluation under label delay and three monitored adversarial changes.

You are done when

  • Your decision policy fits a stated review capacity.
  • Your evaluation plan works despite label delay.
  • You name at least one way a fraudster would adapt, and the layer that catches it.

Stretch. Build the velocity and graph features for a public fraud dataset (for example the IEEE-CIS fraud data) and measure how much they add.