---
title: Real-time card-payment fraud scoring
url: https://gurkanozkan.ai/learn/design/mle-real-time-card-payment-fraud-scoring-02/
markdown: https://gurkanozkan.ai/learn/design/mle-real-time-card-payment-fraud-scoring-02.md
kind: design
role: ML engineering
json: https://gurkanozkan.ai/api/learn/design/mle-real-time-card-payment-fraud-scoring-02.json
---

# Real-time card-payment fraud scoring

Design a model-driven system that approves, challenges (step-up) or declines each card authorisation in real time.

## 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

- **Requirements**: Design a model-driven system that approves, challenges (step-up) or declines each card authorisation in real time.
- **Estimates**: 5k 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**
- **Architecture**: Streaming 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-offs**: fraud 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.
- **Evaluation**: Offline: 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

### 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

- **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 ─► champion
```


### Deep 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

- **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.

---

*Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.*
