Learning path: End-to-End ML Use Cases: Fraud, Recommendations, Forecasting and Ticket Routing · Step 4 of 16
Fraud Scoring, Part 4: Release and Monitoring With Shadow, Drift and Late Labels
A challenger fraud model runs in shadow beside the champion. Background shadow costs about a millisecond at p50, simulated drift takes PSI from 0.007 to 0.181, and a recall of 1.00 on day 35 turns into 0.41 by day 80 once the chargebacks arrive.
What you will learn
- Run a challenger fraud model in shadow, inline or in the background, and measure what it costs
- Watch score drift with PSI before any labels arrive
- Grade only mature transactions so late chargebacks don't fake a perfect recall
- Decide whether to promote a challenger from shadow results
Before you start
- Fraud Scoring, Part 3: Serving It With FastAPI, Docker and a 50 ms Budget
- Shadow, Canary and Rollback
- When Labels Arrive Weeks Late
The fraud service from Part 3 is up, and the champion (a scaled logistic regression) is answering. A new model, the challenger (histogram gradient boosting), wants in. On validation it looks better: average precision 0.229 against the champion's 0.198. We still won't just switch it on.
The plan has three steps. The challenger runs in shadow, scoring everything and deciding nothing. We watch the scores for drift, which needs no labels. Then we wait for the chargebacks and grade it properly. The data is synthetic and the drift is simulated, so read the numbers that way.
Think about a trainee beside a senior for a month. The senior makes every call. The trainee writes her own call in a notebook, and nobody at the counter hears it. If the customers start looking different, you'd notice before you knew whose calls were right. And who was right only comes out weeks later.
A result that looks fantastic
Let's start at the end. It's day 35, and we run python evaluate.py 35:
day 35, all rows: 1835 txns, 1 fraud labels
champion: recall 1.00, precision 0.02
challenger: recall 1.00, precision 0.03
Both models show a recall of 1.00. Now look at the line above: 1,835 transactions and one fraud label. This data is synthetic, so we can peek at the truth, and 25 of those rows are fraud. The other 24 haven't come back as chargebacks yet, so the table calls them honest. That perfect score means both models caught the one fraud we've heard about. We'll fix it below.
Shadow: one answer, two scores
First the shadow, in service.py. The response only uses the champion, so the challenger has no say in what the customer gets:
def shadow(t, champion):
row = {"txn_id": t.txn_id, "champion": champion,
"challenger": prob(M["challenger"], t)}
with lock, open(LOG, "a") as f:
f.write(json.dumps(row) + "\n")
@app.post("/score")
def score(t: Txn, bg: BackgroundTasks):
s = prob(M["champion"], t)
if MODE == "inline":
shadow(t, s)
elif MODE == "background":
bg.add_task(shadow, t, s)
return {"score": s, "alert": s >= M["thr"]["champion"]}
shadow scores the same transaction with the challenger and writes one row with both scores to shadow.jsonl. That's the trainee's notebook. In inline mode it runs before the return, so the response waits. In background mode, FastAPI's background tasks run it after the response has left. One environment variable picks the mode, and the code stays the same.
What the watching costs
Each mode was replayed with 400 requests, one client, uvicorn on one machine, no container:
| SHADOW | p50 | p99 |
|---|---|---|
| off | 2.0 ms | 3.8 ms |
| inline | 4.5 ms | 13.8 ms |
| background | 3.2 ms | 15.1 ms |
At p50 it's neat: background shadow costs about a millisecond more than off, and inline costs more. The p99 column isn't so neat. Background is worse than inline, but a p99 over 400 requests rests on about four requests, and this run doesn't show why. A full replay of 6,000 in background mode gave 3.3 ms at p50 and 8.3 ms at p99, and the other modes weren't run at that size. So background shadow cost about a millisecond at p50. Check the tail before you trust it. (Why the tail matters is in Latency Math.)
Drift: no labels needed
Drift we can watch from day one. drift.py compares the champion's scores this week with its scores on the validation data, using PSI:
WATCH = 0.2 # common rule of thumb, not from this run
def psi(ref, now, bins=10):
edges = np.quantile(ref, np.linspace(0, 1, bins + 1))
edges[0], edges[-1] = -np.inf, np.inf
a = np.histogram(ref, edges)[0] / len(ref)
b = np.histogram(now, edges)[0] / len(now)
a, b = a.clip(1e-4), b.clip(1e-4)
return float(((b - a) * np.log(b / a)).sum())
The 10,000 validation scores set ten bins, and we see how this window's scores fall into them. To have something to find, the script also simulates a change: from day 40, every transaction gets two more transactions in the last hour (txn_1h + 2).
days 30-34: 1529 txns, PSI 0.004, alerts 0.026
simulated shift: PSI 0.004, alerts 0.026
days 35-39: 1492 txns, PSI 0.003, alerts 0.016
simulated shift: PSI 0.003, alerts 0.016
days 40-44: 1469 txns, PSI 0.011, alerts 0.025
simulated shift: PSI 0.167, alerts 0.044
days 45-49: 1510 txns, PSI 0.007, alerts 0.028
simulated shift: PSI 0.181, alerts 0.049
On the unshifted traffic, PSI stays between 0.003 and 0.011. That's expected, because this synthetic traffic doesn't change. With the simulated shift, PSI jumps to 0.167 and then 0.181, and the alert rate in the last window goes from 0.028 to 0.049, close to double.
A common rule of thumb says worry above 0.2, and we didn't reach it. We still saw the jump, so watch the trend, not only the line. And drift tells you something changed. It doesn't tell you the model got worse. PSI bin by bin is covered in Drift Detection in Code.
Late labels: wait for the answer
In this data, a chargeback lands 3 to 28 days after the payment, with a median of 15. Here's the join in evaluate.py:
def join(log, as_of, mature_only):
"""Join shadow scores to the labels known on as_of."""
truth = make(6000, 30, 20, 2)
d = log.merge(truth, on="txn_id")
d = d[d.day <= as_of].copy()
d["known"] = (d.label_day <= as_of).astype(int)
d["y"] = d.known
if mature_only:
d = d[d.day + MATURE <= as_of].copy()
d["y"] = d.is_fraud
return d
d["y"] = d.known is where the perfect score came from: a fraud whose label hasn't arrived quietly becomes 0. The fix is mature_only. A transaction only counts once 30 days (MATURE) have passed, and then y is the true flag. That's safe here because every delay is under 30 days.
On day 35 that leaves zero rows:
day 35, mature only: 0 txns, 0 fraud labels
champion: recall 0.00, precision 0.00
challenger: recall 0.00, precision 0.00
That 0.00 comes from the max(..., 1) guard in metrics. It means "no answer yet", not a bad model. On day 65, the same 1,835 rows now have 25 labels, and champion recall falls from 1.00 to 0.44.
The challenger led, then it lost
Now let the wait run to day 80:
The all-rows line starts at 1.00 and is 0.41 by day 50. The mature line starts on day 60, on just 3 labels, and then the counts build: 25, 45, 56, 69. On day 80:
day 80, mature only: 6000 txns, 69 fraud labels
champion: recall 0.41, precision 0.20
challenger: recall 0.29, precision 0.17
On validation, the challenger led on average precision, 0.229 against 0.198. On day 80, recall is 0.41 for the champion and 0.29 for the challenger. It flipped.
That gap is about eight frauds, on one synthetic data set, so it's not proof the challenger is worse. It gives us no case to promote it, so we keep the champion. And the challenger lost without touching a single customer. That's what shadow buys you. If it had won, the next step would be a canary, as in Shadow, Canary and Rollback.
Common mistakes
- Grading before the labels mature. Missing chargebacks look like honest transactions, and recall looks perfect. Only count rows older than the label wait.
- Reading 0.00 on an empty window as a bad model. No mature rows means no answer yet.
- Treating drift as a quality alarm. PSI says the scores moved. Only labels say whether the model got worse.
- Trusting a p99 from 400 requests. It rests on about four of them. Replay more before deciding on the mode.
- Promoting on validation alone. 0.229 against 0.198 looked like a win, and shadow said otherwise.
Recap
| Step | Result |
|---|---|
| Shadow, background | p50 2.0 to 3.2 ms; p99 untidy (3.8 off, 15.1 background) |
| Drift, simulated shift | PSI in the last window 0.007 to 0.181, under the 0.2 rule of thumb |
| Late labels | day 35 recall 1.00 on 1 label; day 80 recall 0.41 on 69 |
| Decision | challenger 0.29 vs champion 0.41: keep the champion |
Try it yourself: in drift.py, change the simulated shift from += 2 to += 4 and see if PSI passes 0.2. The project files are in the community, free to join.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (paid course, opens in a new tab)Related posts
Project: Car Price Predictor End to End, from CSV to a FastAPI Price API
The whole ML workflow on 205 cars: clean the brand out of CarName, split first, audition five regressors on the same folds, tune the random forest, test once (RMSE 2,195, R2 0.939), save it and serve prices with FastAPI.
Fraud Scoring, Part 1: The Problem, the Metric and the Baseline
Before training a fraud model, write down what good means. On 6,000 synthetic validation transactions, a rule that never flags is 96.13% accurate and costs 23,200, flagging everyone costs 28,840, and a small contract.py fixes the rules first.
Fraud Scoring, Part 2: Training With Time Splits, Leak-Free Features and a Cost-Picked Threshold
Train the fraud model against its contract: a time split of 30,000 synthetic transactions, a card_n_1h feature that never looks ahead, XGBoost that pays 23,200 at 0.5, and a cost-picked threshold of 0.045 that brings validation to 14,955 and test to 16,765.
Fraud Scoring, Part 3: Serving It With FastAPI, Docker and a 50 ms Budget
A payment is waiting on the fraud score. Time each stage (the model takes 0.43 ms of a 3.3 ms request), then load test: p99 is 6.1 ms with one client and 163.3 ms with 32, against an example 50 ms budget. Then a Dockerfile, built and run once.