Design: real-time fraud detection
Score every payment in under ~100 ms: streaming velocity and graph features feed hard rules and a calibrated GBDT; an expected-cost policy picks approve, step-up, review or decline, and chargebacks weeks later retrain the model.
Fundamentals you'll use
How it works
- Scale: ~5k payments/s at peak, with decisions under ~100 ms p99 inside the payment path.
- Increment short-window counters in the request path: streaming jobs lag seconds, enough for a card-testing burst.
- Choose by expected cost: a $200 order needs less certainty to decline than a $20 one.
- The worst failure is two-sided: missed fraud costs goods and fees; false declines quietly lose customers.
- Declines never reveal their label, so let a small random share through and weight outcomes by 1/probability.
Check yourself
Answer to mark it learned; your answers aren't scored.
A card-testing bot fires 40 attempts in 20 seconds at one merchant from one IP. All are approved. Logs show the per-IP attempts-in-the-last-minute feature read 0 for every attempt. Root cause and fix?
Go deeper
Full explanation
Requirements
Functional: score every card-not-present payment at authorization and return approve, step-up (3-D Secure), hold for review or decline, with reason codes; let analysts ship rules in minutes; turn reviews, issuer reports and chargebacks into labels. Non-functional: decision p99 under ~100 ms inside the payment path; ~5k payments/s at peak (assumed); if the model is down, fall back to rules with conservative limits rather than block everything; every decision auditable.
Questions I'd ask:
- Who eats the loss: are we the merchant, the payment processor or the issuer? That sets what fraud and a false decline each cost.
- Which attacks matter most: stolen cards, card testing, account takeover, friendly fraud?
- Is 3-D Secure available, and where is strong customer authentication (SCA) mandatory?
- What is the review team's capacity, and how long can an order wait?
- Which signals may we use: device fingerprint, IP, email age, data across merchants?
The highest-cost failure is two-sided: miss a fraud ring and you pay for the goods, chargeback fees and, above card-network thresholds, monitoring-program fines; decline good customers and you lose the sale and often the customer, a loss no fraud dashboard shows.
High-level design
Online path: the payment API calls the risk service synchronously. It reads hundreds of features in one parallel fetch from the online Feature stores: velocity (payments per card, device, IP and email over 1 minute to 30 days), amount aggregates, device and IP reputation, and graph features (cards seen on this device, fraud rate of its cluster). Short windows are incremented in the request itself; long windows come from Kafka → Flink jobs (Queues vs streams (Kafka)). Hard rules run first (blocklists, sanctions, card-testing bursts), then a Gradient-boosted trees (GBDT) returns a calibrated P(fraud) (Class imbalance & calibration). An expected-cost policy turns P(fraud) and the amount into an action. Every decision is logged with the exact features served (Training–serving skew).
Offline: labels arrive from reviewers (hours), issuer fraud reports (days) and chargebacks (weeks, up to ~120 days). Training joins logged features with matured labels; the model retrains weekly, analysts tune rules daily, and Data drift & concept drift monitors watch scores and decision rates per segment.
Code Expected-cost decision policy
from dataclasses import dataclass
@dataclass
class Econ: # assumptions: set them with finance, per merchant segment
fee: float = 15.0 # chargeback fee per fraud
margin: float = 0.30 # margin lost when a good order is declined
churn: float = 20.0 # future value lost when a good customer is declined
review: float = 5.0 # analyst cost per case
hold_drop: float = 0.05 # good buyers who cancel while held for review
sca_drop: float = 0.08 # good buyers who abandon a 3DS challenge
sca_leak: float = 0.20 # fraud still ours after 3DS (no liability shift)
miss: float = 0.10 # fraud that reviewers approve
def decide(p: float, amount: float, e: Econ, sca_ok: bool, queue_full: bool) -> str:
# p must be calibrated: the policy multiplies it by dollars
fraud = amount + e.fee # cost of approving a fraudster
false_decline = e.margin * amount + e.churn # cost of declining a good customer
cost = {
"approve": p * fraud,
"decline": (1 - p) * false_decline,
"step_up": (1 - p) * e.sca_drop * false_decline + p * e.sca_leak * fraud,
"review": e.review + (1 - p) * e.hold_drop * false_decline + p * e.miss * fraud,
}
if not sca_ok:
cost.pop("step_up")
if queue_full:
cost.pop("review")
return min(cost, key=cost.get)
decide(0.12, 180.0, Econ(), sca_ok=True, queue_full=False) # "step_up": $9.89 vs review $10.60Real example
A $180 headphones order arrives at 2:13 am. The risk service reads ~300 features in one parallel fetch (~12 ms): the card is new to the network, the device fingerprint touched 6 other cards in 24 h, the IP belongs to a hosting provider and the billing ZIP is 900 km away from it. No hard rule fires: it is the card's first attempt. The GBDT returns a calibrated P(fraud) = 0.12 (~2 ms). With the code's assumed economics, expected costs are approve $23.40, decline $65.10, review $10.60 and step-up $9.90, so the policy asks for 3-D Secure. The challenge fails; the attempt is logged, and the device counter, now at 7 cards, raises the next attempt's score. Decision in ~35 ms.
Trade-offs +4 · −4
+ You gain
- Rules plus a GBDT: analysts react in minutes, the model generalizes, and feature contributions explain each decision.
- The expected-cost policy turns a score into money, so thresholds move with amount, margin and queue capacity.
- Step-up turns uncertainty into a liability shift instead of a coin-flip decline.
- Streaming and graph features catch bursts and rings that single-payment features miss.
− You pay
- Labels lag by up to ~120 days, so the model learns last quarter's attacks and leans on rules for new ones.
- Two feature paths (in-request counters and Flink) must stay consistent with each other and with training.
- Selective labels: every block hides its own outcome, and the randomized allow budget costs real fraud dollars.
- The policy depends on cost estimates that finance must own and revisit.
Use it when
Costly or irreversible actions decided in real time (payments, payouts, signups, promo abuse), where attackers adapt weekly and both missed fraud and false declines have a dollar cost.
Avoid it when
Low volumes where reviewing every case by hand is cheaper, or after-the-fact investigations (AML, insider fraud) where batch graph analytics over days beats a 100 ms decision.
Numbers to know 5
- Load: 5k payments/s at peak (assumed) × ~6 entities (card, device, IP, email, account, merchant) = ~30k key-value multi-gets/s.
- Latency p99 ~100 ms (assumed): network 10 + features 15 + graph 10 + rules 5 + GBDT ~2 + policy 3 ms; logging async; ~55 ms headroom.
- Break-even (30% margin, $20 churn cost, $15 fee, assumed): $200 order p* = 80 / (80 + 215) ≈ 0.27; $20 order p* = 26 / (26 + 35) ≈ 0.43.
- Base rate: at 0.1% fraud and 80% recall (assumed), a 1% false-positive rate declines ~12 good payments per fraud caught; Stripe reports Radar wrongly blocks ~0.1% of legitimate payments.
- EU PSD2 transaction-risk-analysis exemption: PSP fraud rate ≤ 0.13% for ≤ €100, ≤ 0.06% for ≤ €250, ≤ 0.01% for ≤ €500; not available above €500.
Common pitfalls 4
- Recomputing features at training time instead of logging what was served: counts absorb later events, offline AUC soars, production doesn't move.
- Velocity only from the async stream: a card-testing bot's 40 attempts in 20 s are all scored before the counter moves. Count short windows in the request path.
- Evaluating only on approved payments: blocks have no labels, so each model looks great on what its predecessor let through and forgets what it blocked. Keep a randomized allow budget.
- One global threshold for $5 and $2,000 orders, and rules that never expire: both decline good customers silently. Use the expected-cost policy; give rules owners and TTLs.
Interview questions 3
Answer out loud first, then reveal.
Chargebacks arrive up to 120 days later. How does your model keep up with new attacks?Show answer
I accept that the model learns slowly and make the system around it fast. Labels come in layers: reviewer verdicts in hours, issuer fraud reports in days, chargebacks over months. I train on matured data plus recent rows labeled by the fast sources, down-weighted because they're noisier. New attacks are caught first by monitoring and rules, which analysts ship in minutes through shadow mode. The model retrains weekly, and I track a label-maturity curve so I know what share of each week's eventual fraud I've already seen. The trade-off: fast labels are biased toward what reviewers looked at.
How do you choose the decline threshold?Show answer
I don't choose one threshold; I minimize expected cost per payment. Approving costs P(fraud) times the amount plus fees; declining costs (1 − P) times the lost margin plus the customer's future value; step-up and review have their own costs. That gives amount-dependent cut-offs: with my assumed economics, decline beats approve above ~0.27 for a $200 order but ~0.43 for a $20 one. It only works if P is calibrated, so I recalibrate on matured labels. Then I add constraints, such as review capacity, card-network fraud ratios and an approval-rate SLO, and check the policy offline on counterfactual data before shipping it.
Fraud jumps 5× overnight at one merchant. Walk me through your response.Show answer
First I characterize it: many small authorizations with high issuer decline rates means card testing; large orders from new accounts means stolen cards or account takeover. Containment within the hour: a scoped rule, such as velocity caps per IP and BIN for that merchant or forced 3-D Secure, runs in shadow for 15 minutes to size the false declines, then enforces. Then root cause: which feature didn't fire and why, often a lagging counter or a spoofed device. The fix goes into features and the next retrain, the emergency rule gets an expiry, and the postmortem reports both fraud stopped and good customers declined.
Deep dive 5
Streaming features and the velocity race
Velocity features are counts and sums per entity over sliding windows: payments per card in 1 minute, 1 hour and 24 hours; distinct cards per device in 24 hours; distinct emails per IP; amount per BIN. Flink computes them from the payment stream with keyed windows and writes them to a low-latency key-value store, typically seconds behind. That lag is the hole: a card-testing bot fires 40 attempts in 20 seconds, and every one is scored before the counter moves. So the request path itself atomically increments short-window counters (per-minute buckets with TTLs) and reads them back, while Flink owns long windows and distinct counts (HyperLogLog). Make the increment idempotent per payment ID, or a client retry counts twice (Idempotency). Log every served value: rebuilding counts at training time leaks future events.
Graph signals
Fraud rings reuse infrastructure: one device, a few IPs and a shipping address behind hundreds of stolen cards. Model entities (card, account, device, IP, email, address) as nodes and their co-occurrence in a payment as edges. Cheap 1-hop features update in streaming: cards per device in 24 hours, accounts per address, whether any neighbor is confirmed fraud. Expensive ones run in batch every hour or day: connected-component size and fraud rate, and node embeddings from a graph model, served as plain features to the GBDT. Watch for supernodes: a mobile carrier's NAT IP or a corporate proxy links thousands of honest users, so cap degree and type your IPs (residential, mobile, hosting). A new account whose device sits two hops from a confirmed fraud cluster is a signal no single-payment feature can see.
Labels: delay, selection bias and evaluation
Labels arrive in layers: reviewer verdicts in hours, issuer fraud reports in days, chargebacks over weeks to ~120 days. Train on matured windows (payments 60–90+ days old, say) and add recent rows labeled by the fast sources, down-weighted. The deeper problem is selective labels: a declined payment never reveals whether it was fraud, so each new model is graded only on what the old one let through. Stripe's answer is counterfactual evaluation: let a small, budgeted random share of would-be-blocked payments through, with a known probability per score, and weight their outcomes by 1/probability. Evaluate on a time split: recall at a fixed false-positive rate, dollar-weighted recall and false-decline rate, and PR-AUC over ROC-AUC, because at ~0.1% fraud a useless model can still post a high ROC-AUC (Precision, recall, F1, ROC-AUC).
Thresholds, step-up and review
Pick the action with the lowest expected cost. Approving costs P(fraud) × (amount + fees); declining costs (1 − P) × (lost margin + lost future value). Approve and decline break even at p* = false-decline cost / (false-decline cost + fraud cost), so a $200 order needs less certainty to decline than a $20 one. Step-up is the middle action: 3-D Secure shifts fraud liability to the issuer, but some good buyers abandon it. In the EU, SCA is the default; the transaction-risk-analysis exemption lets a PSP skip it only while its fraud rate stays under 0.13% (≤ €100), 0.06% (≤ €250) or 0.01% (≤ €500): a better model buys frictionless checkout. Review is capacity-bound: rank the queue by expected loss avoided, and treat verdicts as fast but biased labels (Human-in-the-loop & approvals).
Adversarial drift and operations
Fraudsters adapt within days of a block: new BINs, new merchants, velocity kept just under your rule. Monitor hourly: score distribution shift (PSI), approve, step-up and decline rates by merchant, BIN, country and channel, issuer decline codes and early fraud reports (Monitoring models in production). Analysts respond first with rules: every new rule runs in shadow mode on live traffic, reporting hits and would-be false declines, before it enforces, and every rule has an owner and an expiry date. The model retrains weekly; a challenger runs in shadow, then on a small share of traffic, and is compared on matured labels. Give analysts and support decision reasons from feature contributions (SHAP, for example). If the model or the feature store fails, a rules-only path with lower amount limits keeps payments flowing.