Learning path: End-to-End ML Use Cases: Fraud, Recommendations, Forecasting and Ticket Routing · Step 3 of 16
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.
What you will learn
- Put a fraud model behind a FastAPI /score endpoint that returns a score and an alert
- Time each stage of a request against a latency budget
- Load test with 1, 8 and 32 clients and read p50, p99 and throughput
- Package the service in a Dockerfile and know what one container run does and doesn't prove
Before you start
- Fraud Scoring, Part 2: Training With Time Splits, Leak-Free Features and a Cost-Picked Threshold
- Production FastAPI for an ML Model
- Latency Math: p50, p95, p99
We have a fraud model from Part 2, and now a payment is waiting on it. The contract from Part 1 set an example target of 50 ms at p99. Today we put a model behind an API and find out where the time goes.
This part has its own small synthetic data set and its own two models, so the numbers are new. The service holds a champion (a scaled logistic regression) and a challenger (a histogram gradient boosting classifier). Each one's alert threshold is set so the top 2% of validation scores raise an alert. Only the champion answers today. Fifty milliseconds is an example target, and every measurement here comes from uvicorn on one machine, with no container.
Work, and the queue
Think about a checkout till. One customer, the card goes in, and the answer comes back before she's put her wallet away. Now it's Saturday and there's a queue. Each payment takes the same time as before, but everyone waits behind somebody else.
So the wait is the work plus the queue. That gives us two things to measure: how long the work takes, and what happens when the queue builds up.
service.py: the model behind FastAPI
The service has the same FastAPI shape as Production FastAPI for an ML Model, so here are just the parts that matter for this use case:
import json
import os
import sys
import threading
import time
import joblib
import numpy as np
from fastapi import BackgroundTasks, FastAPI
from pydantic import BaseModel
from data import FEATS
MODE = os.environ.get("SHADOW", "background")
LOG = os.environ.get("SHADOW_LOG", "shadow.jsonl")
M = joblib.load("models.joblib")
app = FastAPI()
lock = threading.Lock()
class Txn(BaseModel):
txn_id: int
amount: float
hour: int
new_device: int
risk: float
txn_1h: int
def prob(model, t):
x = np.array([[getattr(t, f) for f in FEATS]])
return float(model.predict_proba(x)[0, 1])
@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"]}
joblib.loadruns once, when the service starts, so no request pays for loading the models.- The
Txnpydantic model checks every field of the incoming transaction. problines the features up in the right order and asks for a probability.- The response is the score, and an alert if the score reaches the champion's threshold.
The shadow function it calls (it scores the challenger and writes a log row) is shown in Part 4. There's a shadow switch in this file too. For timing we run with SHADOW=off, so we measure the model on its own. Part 4 switches it on.
Stage by stage: where the time goes
Instead of one stopwatch on the whole request, budget.py puts a mark between every stage, for 2,000 transactions:
def stages(n=2000):
names = ["validate", "features", "model", "respond"]
ms = {k: [] for k in names}
now = time.perf_counter
for r in rows(n):
t0 = now()
t = Txn(**r)
t1 = now()
x = np.array([[getattr(t, f) for f in FEATS]])
t2 = now()
s = float(M["champion"].predict_proba(x)[0, 1])
t3 = now()
json.dumps({"score": s, "alert": s >= 0.13})
t4 = now()
for k, a, b in zip(names, [t0, t1, t2, t3],
[t1, t2, t3, t4]):
ms[k].append((b - a) * 1000)
budget 50 ms (example target)
validate: p50 0.01 ms, p99 0.05 ms
features: p50 0.01 ms, p99 0.03 ms
model: p50 0.43 ms, p99 1.17 ms
respond: p50 0.01 ms, p99 0.04 ms
The model is the big one among our stages, 0.43 ms at p50. Together the four stages add up to about 0.46 ms. But the whole request, with one client, took 3.3 ms at p50. So about 2.8 ms sits outside these stages, in the HTTP work, the framework and the client. The run didn't split that part, so we can't say which of those it is.
That's the insight: with one client, a faster model wouldn't help much.
The load test: when the queue builds
The load function in the same file takes 3,000 synthetic transactions and splits them across clients, each on its own thread:
def load(clients, data):
out = []
parts = [data[i::clients] for i in range(clients)]
t0 = time.perf_counter()
with ThreadPoolExecutor(clients) as pool:
for p in parts:
pool.submit(post_all, p, out)
secs = time.perf_counter() - t0
p50, p99 = np.percentile(out, [50, 99])
rate = len(out) / secs
print(f"{clients} clients: p50 {p50:.1f} ms, "
f"p99 {p99:.1f} ms, {rate:.0f} req/s")
1 clients: p50 3.3 ms, p99 6.1 ms, 293 req/s
8 clients: p50 16.9 ms, p99 38.5 ms, 397 req/s
32 clients: p50 60.3 ms, p99 163.3 ms, 350 req/s
Read the three rows together:
- 1 client: p99 is 6.1 ms, well under budget, 293 requests a second.
- 8 clients: p50 jumps to 16.9 ms and p99 to 38.5 ms, still under budget. Throughput climbs to 397.
- 32 clients: p50 is 60.3 ms and p99 is 163.3 ms, more than three times the budget. Throughput falls to 350.
More clients stopped adding work done and only added waiting. That's the queue from the till. One client tells you about the work. It tells you nothing about the queue.
One caution: the load client and uvicorn share one machine here, so the client eats into the server's CPU. Treat this as the shape of the problem, not as your capacity. For proper load tools and tracing, see Measuring Latency with OpenTelemetry and Locust, and for how many replicas a load needs, Sizing and Autoscaling.
A Dockerfile, built and run once
FROM python:3.13-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY data.py service.py models.joblib ./
ENV SHADOW=off
EXPOSE 8000
CMD ["uvicorn", "service:app", "--host", "0.0.0.0"]
A slim Python image, the requirements, then only the three files the service needs. Shadow is off, and uvicorn starts on port 8000. The walkthrough of each line is in Containerise a Model API.
The build took 46.7 seconds and the image is 685 MB. One POST to /score with this transaction:
{"txn_id": 200038, "amount": 98.4, "hour": 14, "new_device": 0, "risk": 0.916, "txn_1h": 0}
came back with:
{"score":0.0019066392854874918,"alert":false}
That's a single request, so it says nothing about speed. The p99 numbers above came from the run without a container. To compare, build it yourself and run the same load test against it.
Common mistakes
- Timing one request and calling it done. One client measures the work, not the queue. 6.1 ms became 163.3 ms with only the crowd changing.
- Optimising the model first. Here the model was 0.43 of 3.3 ms. Measure the stages before you pick what to speed up.
- Loading the model inside the route. Load once at startup, so no request pays for it.
- Trusting a load test where client and server share a CPU. Use it for the shape, then test on a setup like production.
Recap
| What we measured | Result |
|---|---|
| Model stage, p50 | 0.43 ms (all four stages about 0.46 ms) |
| Whole request, 1 client, p50 / p99 | 3.3 ms / 6.1 ms |
| 8 clients, p99 | 38.5 ms, 397 req/s |
| 32 clients, p99 | 163.3 ms, 350 req/s, over the 50 ms example budget |
| Docker image | built in 46.7 s, 685 MB, one request answered |
Try it yourself: add 16 to the client list in budget.py and see where p99 passes 50 ms.
Next: Part 4, release and monitoring with shadow, drift and late labels.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Fraud Scoring, Part 2: Training With Time Splits, Leak-Free Features and a Cost-Picked Threshold
Next →Fraud Scoring, Part 4: Release and Monitoring With Shadow, Drift and Late Labels
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
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 (opens in a new tab)Related articles
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 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.