Contents
Constraints
- 5k TPS peak
- ~0.1–0.3% fraud rate
- p99 budget 50 ms for the whole decision
- chargeback labels arriving 30–90 days late
What to cover
Sketch your own design first. A complete answer has these parts; the notes say what each should settle.
- RequirementsDesign a model-driven system that approves, challenges (step-up) or declines each card authorisation in real time.
- Estimates5k TPS peak; ~0.1–0.3% fraud rate; p99 budget 50 ms for the whole decision; chargeback labels arriving 30–90 days late.
- API
- Data model
- ArchitectureStreaming feature pipeline: velocity counts per card, merchant and device over sliding windows; distance from home; merchant risk; device/IP signals.; Online feature store plus a precomputed customer profile.; GBDT baseline, then sequence or embedding features.; Rules engine for hard constraints; a decision layer with cost-based thresholds and step-up flows.; Case-management feedback; nightly retraining including false declines and missed fraud.; Rate-limited action applier with safety limits (decline-rate caps, circuit breaker to rules-only).
- Deep dives
- Trade-offsfraud loss vs false-decline friction; model complexity vs latency; rules (fast, explainable) vs ML (adaptive); retraining frequency vs label maturity; selection bias from blocked transactions.
- EvaluationOffline: out-of-time split with a label-maturity gap; value-weighted recall at a fixed FPR; precision at the operating point.; Online: shadow mode → canary → champion/challenger; fraud basis points of volume, decline rate, customer contacts.; Small randomised holdout to measure blocked-transaction outcomes.; Monitoring: score drift, decline rate per merchant category, feature freshness.
Reference design
One way to answer it, part by part. Open a part once you have your own version of it.
Requirements
Functional: for every card authorisation (card-present, online, contactless, recurring), return approve, challenge (in-app confirmation or 3-D Secure step-up) or decline, with reason codes; feed outcomes from disputes, customer reports and investigations back into training; let fraud operations change rules quickly.
Non-functional
- p99 ≤ 50 ms for the whole decision inside the authorisation flow; if scoring times out, fall back to a rules-only decision rather than failing the payment.
- 99.99% availability — this sits on the payment path.
- Explainable reason codes for customers, operations and the regulator; decisions reproducible from logged features.
Objective: minimise total cost = fraud losses + cost of false declines (lost interchange, customer friction, churn) + cost of challenges (drop-off, contact-centre calls). Not raw accuracy: at a 0.2% base rate, approving everything is 99.8% accurate.
Assumptions to confirm: we are the issuer; liability rules per scheme and channel; whether some merchant categories (gambling, crypto) carry stricter policy; chargeback and customer-report label sources and delays.
Estimates
Stack · 6 layersHow the 50 ms latency budget is spent
5 ms
Single round trip: online store counters + customer profile, merchant risk, device/IP signals
GBDT on hand-built features; sequence model adds 5 ms
Hard constraints
Cost-based decision layer
5 + 8 + 2 + 2 + 1 = 18 ms (23 ms with sequence model); ~25 ms budget, ~25 ms for tails; logging asynchronous
- Volume: 5k TPS peak, ~1.7k TPS average → 1,700 × 86,400 ≈ 147M authorisations/day. At 0.1–0.3% fraud ≈ 147k–440k fraudulent attempts/day — plenty of positives, but very imbalanced.
- Training data: 30 days ≈ 4.4B rows; keep all positives and ~2% of negatives with weight 50 → ~100M rows per training window, workable for GBDT on one large machine or a small cluster.
- Online feature store: ~300M cards × ~2 KB of counters and profile ≈ 600 GB, plus merchant and device keys; an in-memory KV cluster (Aerospike/Redis) with replication.
- Streaming updates: every authorisation updates ~20 sliding-window counters (card, merchant, device, IP × 1 min/1 h/24 h/7 d) → ~100k counter updates/s at peak.
- Latency budget (p99 50 ms): ingress and parsing 5 ms, single-round-trip feature fetch 8 ms, GBDT inference 2 ms (sequence model +5 ms), rules 2 ms, decision and reason codes 1 ms → 5 + 8 + 2 + 2 + 1 = 18 ms (23 ms with the sequence model); budget ~25 ms and keep ~25 ms for tails; logging is asynchronous.
- Label timing: chargebacks arrive 30–90 days late, customer reports in days. A model trained tonight has mature labels only up to ~3 months ago.
- Holdout cost: if the model declines ~0.3% of authorisations (~440k/day), approving a random 0.1% of would-be declines ≈ 440 transactions/day; capped at £50 each, the worst-case exposure is 440 × £50 ≈ £22k/day, and the real loss is lower because only part of them are fraud — a bounded cost that buys unbiased labels.
API
POST /v1/score (gRPC in production, from the authorisation service)
{auth_id, card_token, amount, currency, merchant_id, mcc, merchant_country,
channel: "card_present"|"ecom"|"contactless"|"recurring", entry_mode,
device_id?, ip?, wallet_token?, timestamp}
→ {decision: "approve"|"challenge"|"decline", score, reason_codes: ["VELOCITY_1H", ...],
model_version, rules_fired[], latency_ms}
POST /v1/labels {auth_id, label: "fraud"|"genuine", source: "chargeback"|"customer_report"|
"investigation", reported_at}
POST /v1/rules {expression, action, scope, expiry, author} (versioned, audited, canaried)
Scoring is idempotent on auth_id, so a retried authorisation does not double-count velocity features.
Reason codes map to customer-facing explanations and scheme response codes. Rules have their own audited API so fraud operations can react to a new attack within minutes without a model release.
Data model
- AuthorisationEvent: auth_id, card token, amount, merchant, MCC, channel, device/IP, timestamp, response code.
- FeatureSnapshot: auth_id → exact feature vector used at decision time (point-in-time correctness for training and audit).
- Decision: auth_id, score, action, thresholds version, model version, rules fired, holdout flag and propensity.
- Counters (online): per card, merchant, device, IP — counts and sums over sliding windows; last-seen location and merchant.
- CustomerProfile (batch, daily): home location, typical spend by MCC and hour, usual devices, account age.
- Label: auth_id, label, source, reported_at, maturity status (immature < 90 days).
- Case: investigation outcome, analyst notes, linked auth_ids.
- Rule: versioned expression, action, scope, author, expiry, performance stats.
Architecture
Card network ─► Authorisation service ─► Fraud decision service (p99 50 ms)
├─ Feature fetch (one round trip): online store counters + customer profile
│ + merchant risk + device/IP signals; current transaction folded in
├─ Model: GBDT on hand-built features; later sequence/embedding features
│ from recent transaction history (precomputed or a small model)
├─ Calibration ─► cost-based decision layer: approve | challenge | decline
├─ Rules engine: hard constraints (blocked merchants, sanctions, travel
│ notices, scheme mandates) can override
└─ Action applier with safety limits: rate caps on declines per MCC and
merchant, circuit breaker to rules-only on anomalies
Async: decisions + feature snapshots ─► Kafka ─► lake
Stream processor (Flink) ─► sliding-window counters ─► online store
Labels (chargebacks, reports, cases) ─► label store ─► nightly retraining
─► evaluation ─► shadow ─► canary ─► championDeep dives
Choosing thresholds by cost. With calibrated p(fraud), compare expected costs: approve = p × amount × loss rate; challenge = p × amount × (1 − catch rate) + (1 − p) × friction cost; decline = (1 − p) × false-decline cost. A £20 transaction and a £2,000 one with the same score deserve different actions. Thresholds are set per segment and reviewed monthly.
Delayed labels and selection bias. Train on an out-of-time window ending ~90 days ago for chargeback-mature labels, adding recent customer-reported fraud with care. Declined transactions never get labels, so the model can never learn that it was wrong to decline; the randomised holdout (approve a small capped fraction, or challenge instead of decline) provides unbiased outcomes, used with inverse-propensity weights in evaluation.
Safety limits. A bad deploy or a broken feature (counters returning zero) can decline thousands of genuine payments in minutes. The action applier caps decline rates per merchant category against a baseline and falls back to rules-only on breach, paging on-call.
Trade-offs
- Fraud loss vs false-decline friction: every point of recall costs genuine customers; false declines also lose interchange and trust. Express both in money and pick the operating point by cost; use challenges to soften the trade-off where the channel allows.
- Model complexity vs latency: GBDT on good features is fast, strong and explainable; sequence models add a few points of recall but need precomputation or tight serving to stay in budget. Add them as features before replacing the GBDT.
- Rules (fast, explainable) vs ML (adaptive): rules respond to a new attack in minutes and encode hard policy; ML generalises. Keep both, but retire rules that the model subsumes, or the rule set grows unmanageable.
- Retraining frequency vs label maturity: nightly retraining tracks new patterns but on immature labels; weight recent confirmed fraud, and compare against a model trained only on mature labels.
- Selection bias from blocked transactions: the holdout costs money but without it evaluation is biased towards the incumbent.
Evaluation
Sequence · 5 stepsHow evaluation rolls a model to champion
- Offline evaluation Out-of-time split with a label-maturity gap; value-weighted recall at a fixed false-positive rate; precision at the operating point.
- Shadow mode Shadow mode scores and logs with no action.
- Canary Canary runs on a small share of traffic.
- Champion/challenger Compare fraud basis points of volume, decline rate, challenge rate and completion, customer contacts and complaints.
- Monitoring Watch score drift, decline rate per MCC and merchant, feature freshness, latency p99, fallback activations and label arrival rates.
Data
| Step | From | To | Message |
|---|---|---|---|
| 1 | Offline eval | Offline eval | out-of-time split |
| 2 | Offline eval | Shadow mode | pass offline |
| 3 | Shadow mode | Canary | pass shadow |
| 4 | Canary | Champion | champion/challenger split |
| 5 | Monitoring | Monitoring | score drift |
Source: This page's text
- Offline: out-of-time split with a label-maturity gap (train on months 1–6, test on month 8 once labels mature); value-weighted recall (fraud £ caught / fraud £ total) at a fixed false-positive rate; precision at the operating point; calibration plots; results by channel, MCC and amount band.
- Online: shadow mode (score, log, no action) → canary on a small share of traffic → champion/challenger split; compare fraud basis points of volume, decline rate, challenge rate and completion, customer contacts and complaints.
- Randomised holdout: small, capped and documented, to measure outcomes of would-be declines.
- Monitoring: score distribution drift, decline rate per MCC and merchant, feature freshness and null rates, latency p99 and timeouts, fallback activations, label arrival rates; alert on any sudden shift.
What a strong design shows
- Frames the decision as expected cost with calibrated probabilities and per-transaction amounts, including the challenge option.
- Engineers point-in-time features with sliding windows and logs feature snapshots at decision time.
- Handles 30–90-day label delay with out-of-time evaluation and a maturity gap, and fixes selection bias with a randomised holdout.
- Keeps rules and ML together and protects the payment path with timeouts, fallbacks and rate-limited actions.
- Rolls out via shadow, canary and champion/challenger with money-denominated metrics.