← All work(03) / (04) · Case study

Fraud detection system.

Fraud decisioning tuned to what fraud actually costs a bank, not a textbook metric. With an explanation for every decline.

RoleData Scientist / ML Engineer
StackModel — Python · XGBoost · scikit-learn · SHAPMLOps — MLflow · DVC · Airflow · GitHub Actions CIServing and monitoring — BentoML · Docker · Prometheus · GrafanaStreaming — Kafka · Flink (PyFlink)Infrastructure (designed, not deployed) — Terraform for AWS (ECS Fargate, ECR, S3, IAM with GitHub OIDC)Front ends — Streamlit · GitHub Pages
Data284,807 real, anonymised card transactions over 48 hours · 492 fraud
StatusAlways-on live demo · Interactive dashboard · CI passing on GitHub · Streaming and monitoring tested locally · AWS designed, not deployed
75%Of fraud caught · 39 of 52 on the out-of-time test set, at the deployed threshold
48%Alert precision at that threshold · the leaderboard winner managed 8%
15×What a missed fraud costs versus a false alarm: £150 against £10
EveryDecline returns its own reasons, from SHAP for that transaction
01 · The problem

Why it needs to exist

With 492 frauds among 284,807 transactions, a model that never flags anything is 99.8% accurate. Accuracy is the wrong question. The right one is how much fraud you catch at a cost the bank and its customers can live with.

The UK has no equivalent of the US adverse action notice. When an automated system declines a transaction here, the customer is rarely told why in any meaningful way.

The FCA’s Consumer Duty expects communications customers can understand. So every decline this system makes carries a plain-English reason computed for that specific transaction, built into the API rather than bolted on.

02 · How it works

From transaction to explained decision

  1. 01

    Version the data

    Every dataset is versioned, so any model can be traced back to exactly what it learned from.

    DVC
  2. 02

    Split by time

    Train on the earliest 70%, validate on the next 15%, test on the final 15%. No future data leaks into training.

    Out-of-time 70/15/15
  3. 03

    Select by information value

    Optimal binning on the training set only, to find predictors that correlation misses.

    IV · 34 → 30 features
  4. 04

    Champion vs challengers

    Logistic regression, random forest and XGBoost, trained under identical out-of-time conditions.

    MLflow on DagsHub
  5. 05

    Price the threshold

    Every threshold is costed on the validate set against missed fraud and false alarms. The cheapest is frozen before the test set is opened.

    Threshold 0.0716
  6. 06

    Serve, explain, monitor

    A containerised API returns the decision with its reasons; a live dashboard tracks performance and drift.

    BentoML · Docker · Streamlit
OrchestrationThe pipeline runs end to end under Apache Airflow, with every training run, metric and model artefact logged to MLflow. A build script writes the live demo’s data from the same outputs, scoring its samples with the API’s own code, and a test checks its notices match the API word for word.
03 · Decisions

What I chose, and what I rejected

D1

A cost-priced thresholdover the F1-optimal threshold

F1 treats a missed fraud and a false alarm as equally costly. They aren’t. On the validate set, the cost threshold (0.0716) caught 12.5 points more fraud than the F1 threshold (0.9311) and cut cost by a third. On the later test window it didn’t hold up; see Results.

D2

The model I could trust at the thresholdover the leaderboard winner

Random forest beat XGBoost on test KS and AUPRC. At the real threshold its precision collapsed to 8.1%, against XGBoost’s 48.1%, because its scores weren’t calibrated to the true fraud rate. With 52 test frauds the ranking gaps are within noise; the precision gap is not. Recalibrating random forest is the first untested challenge to this choice.

D3

Out-of-time validationover a random split

Random splits let future transactions into training. The test-set fraud rate (0.122%) differed from training (0.193%): a real shift a random split would have hidden.

D4

Class weightsover SMOTE

Fraud invented by interpolation never appears in production. Weighting kept the real distribution: XGBoost’s average score (0.16%) closely matched the true fraud rate (0.131%).

D5

Information valueover Pearson correlation

Fraud isn’t linear. IV exposed amount’s U-shaped risk: card testing below €1.19 and account takeover above €237, invisible to correlation.

04 · Results

Test set, out of time

ModelKSAUPRCF1Precision at the business threshold
XGBoost · champion0.8050.7600.8320.481
Random forest0.8430.7750.8480.081
Logistic regression0.8570.6970.7870.004

How to read this. KS and AUPRC measure ranking: whether fraud tends to score higher than legitimate transactions. Precision at the business threshold measures what happens at the single operating point a bank would deploy. On ranking alone, XGBoost doesn’t win. At the threshold, it is the only usable model: logistic regression flags 31.5% of all transactions, and about 12 of every 13 random forest alerts are false alarms. At 0.0716 on the out-of-time test set (42,722 transactions, 52 frauds), XGBoost made 81 declines: 39 frauds caught and 42 false alarms, or 19 alerts per 10,000 payments.

Cost-optimal · 0.0716 · deployed£1,210 → £2,370

Validate: 91.1% caught at 52.6% precision. Test: 75.0% caught at 48.1% precision.

F1-optimal · 0.9311£1,810 → £2,150

Validate: 78.6% caught at 97.8% precision. Test: 73.1% caught at 88.4% precision.

cost = (missed fraud × £150) + (false alarms × £10)  →  tested at every threshold on validate, then frozen

Stated honestly: cost shown as validate → test. On the later test window the cost-optimal threshold caught one more fraud than the F1 threshold for 37 more false alarms, and cost £220 more. With only 56 validate frauds the cost-optimal point is unstable over time, so a production version would recalibrate it on a rolling window and monitor alert precision alongside KS.

05 · Explanations

What every decline returns

  1. A fraud probability and risk bandThe score for this transaction, not a portfolio average.
  2. The top contributing factorsRanked by SHAP values computed for this specific transaction.
  3. A plain-English noticeNaming the principal factors behind the decision.
  4. A statement that it was automatedAnd that the decision may be reviewed.
Rule 1

Only reasons that pushed towards fraud

A feature that made the transaction look safer must never appear as a reason it was blocked. That would misrepresent the model’s own reasoning.

Rule 2

Honest feature names

V1 to V28 are anonymised PCA components whose real-world meaning is unknown, so the notice calls them “behavioural risk indicators” instead of inventing a story. Only features I engineered are described concretely.

06 · What went wrong

Failures, and what changed

Explanations

The first explanations cited the wrong reasons

An earlier version ranked factors by their raw value, which surfaced large but irrelevant numbers ahead of what actually drove the decision.

What changedReasons are now ranked by SHAP values computed for that specific transaction, and only factors that pushed towards fraud are cited.
Model selection

The best-scoring model was unusable

Random forest won on test KS, AUPRC and F1. Applied at the deployment threshold, about 12 of every 13 of its alerts were false alarms.

What changedChampion selection now judges every model at the operating point the bank would actually use, not on ranking metrics alone.
Known limitation

Velocity features that meant nothing

Four rolling transaction features were engineered, and only one survived feature selection. Without customer IDs, they mixed different people’s histories.

StatusQuantified, not hidden. In production these would be computed per customer, and would be expected to rank among the strongest predictors.
07 · Version 2

Production engineering at zero cloud cost

I froze what I had measured, built the production layer around it, and proved the new layer gives the same answers as the old one. On the way, I caught my own system changing the model without anyone deciding it should.

D10

Pause my own retraining jobover letting a schedule change the model

While freezing v1, I found the weekly Airflow DAG had retrained 48 times between June and November 2026 on older libraries. That gave a different model (test KS 0.836 against v1’s 0.805), logged into the v1 experiment with no promotion gate: exactly the “model changes without governance” risk a model-risk team worries about. I paused it, corrected my own README, and made any return to scheduled retraining depend on a promotion gate.

D11

Keep XGBoost after a fair re-matchover promoting the challenger with better precision

v1 had no gate; “XGBoost” was hard-coded. The new gate judges each model at its own cost-optimal threshold, on validate first and then once on test. At its own threshold, Random Forest had better precision on validate (0.590 against 0.526) but cost £180 more (£1,390 against £1,210). The gate decides on cost, so XGBoost stays, and the result is logged to MLflow either way.

D14

Parity before speedover a fast pipeline that gives different answers

A streaming system that disagrees with the validated batch model is a new, unvalidated model. Tolerances were fixed before any run, and all 42,722 out-of-time test rows were compared: scores within 9.3e-10 and 0 decision flips in all 4 runs, including injected duplicates and late events and a forced crash restored from a checkpoint. The 1,979 rows affected by a deliberately dropped late event are reported separately (0 decision flips) and excluded from the parity claim, not hidden.

D15

Leave out the load balancer, and name the priceover the textbook architecture

The AWS design in Terraform comes to about $25.28 a month, priced from the AWS Price List API. A load balancer alone would add $25.45 a month, and a NAT gateway was also left out. The cost of that choice: no TLS and no zero-downtime deploys, which a production version would add.

ComponentStatusReal result
v1 frozen at tag v1.0-evaluateddoneA hash-checked bundle (models plus validate and test data, about 26 MB). Every CI run recomputes all 181 v1 results exactly, on Windows and Linux.
Promotion gatetested locallyEach model judged at its own cost-optimal threshold, validate first, then once on test. Both challengers lost; logged to MLflow either way.
CI · GitHub Actionspassing on GitHubLint (new code only), 29 tests, the v1 regression check, a Docker build and smoke test of the API, and a Terraform offline plan. No secrets. Coverage is 25%, stated, not padded.
Service monitoring · Prometheus + Grafanatested locallyp95 38 ms at 50 requests/s; one worker saturates at about 80/s. Model + SHAP: p50 8.2 ms, p95 18 ms, so most latency is HTTP overhead. 0 server errors; bad input now returns 400, where v1 returned 500.
Streaming · Kafka + PyFlinktested locally992 events/s against a 1,000/s target (p95 829 ms); about 2,500/s sustained at 3× overload. Exact parity with v1 batch in all 4 runs.
AWS via Terraform · ECR, ECS Fargate, S3, IAM with GitHub OIDCdesigned only, not deployedValidate and an offline plan pass (25 resources). About $25.28 a month if deployed. No AWS account exists, and terraform apply has never been run.
Helm on kindnot doneSkipped: it doesn’t fit in the laptop’s Docker memory and would add no new evidence.
Grafana service-health dashboard during a 50 requests per second replay of the out-of-time test set
Grafana during a 50 requests/s replay of the out-of-time test set · tested locally

Six failures, recorded rather than erased

  1. Flink’s watermark ran ahead of the data and wrongly marked 41,821 events late. Event-time tracking moved into the operator.
  2. The state layout was too slow (628 events/s). A dense sequence number for de-duplication took it to 992/s.
  3. Kafka ran out of direct memory at 3× load. Bounded fetch sizes fixed it.
  4. A Windows localhost delay added 2 s to every request in the first load tests. Those runs were thrown away.
  5. The cost script picked the wrong load balancer price at first, and was corrected.
  6. I broke the parity checker once while editing it.

Not proven, said plainly: the throughput figures come from one laptop running every component at once. The Terraform plan proves the configuration, not the IAM permissions. And with 52 test frauds, one case moves recall by 1.9 points. Every decision is in the decision log.

08 · Scope

What this does and doesn’t prove

It does show

  • A champion chosen for trustworthy behaviour at its deployment threshold
  • Performance measured out of time, not on a random split
  • A reason for every decline, generated at the moment of decision
  • A tracked, versioned, containerised and monitored pipeline
  • A promotion gate that kept the champion on cost, logged either way
  • Streaming that matches the validated batch model on all 42,722 test rows

It doesn’t show

  • Long-term behaviour: 48 hours of data and 52 test frauds, so every test metric has wide uncertainty
  • A stable threshold: the cost-optimal point didn’t hold on later data
  • Per-customer velocity signals: there are no customer identifiers
  • Cloud operation: AWS is designed only, not deployed
  • Production throughput: every v2 component ran on one laptop
  • Real costs: £150 and £10 are stated assumptions
  • A legal requirement: the notice anticipates regulation, it isn’t required by it
  • That a reason is right: on anonymised features a customer learns a reason exists, not what it is