Learning path: Serve a Model in Production: Docker, Latency and Scaling · Step 7 of 9
Measuring Latency of an ML API: Timing Inside with OpenTelemetry, Outside with a Load Test and Locust
Two stopwatches for one ML API: inside, a middleware header and OpenTelemetry spans show where the time goes; outside, an asyncio load test and Locust show how slow it gets under load. All numbers from one local run.
What you will learn
- Time every request inside FastAPI with a middleware and an X-Server-Ms header
- Wrap each stage of a prediction in an OpenTelemetry span
- Write an asyncio load test that reports throughput, p50, p95 and errors
- Run the same test with Locust and write the load, the timing point and the machine beside every number
Before you start
- Latency Math: p50, p95, p99
- A Production FastAPI for an ML Model
We've been quoting latency numbers for the rain API, and Latency Math explained what p50 and p95 mean. But a number is only as good as the way you got it. So how do you measure this yourself?
Two numbers, two stopwatches
Here are two numbers from the same API. One call, and the server says it took 14.20 ms. Sixty-four callers at once, and p95 is 878 ms, with zero errors.
Notice that the error count told us nothing here. You can't just wait for something to fail.
The first number comes from a stopwatch inside the server. The second comes from a stopwatch outside, with the caller. Outside tells you how slow it is. Inside tells you where the time went.
Diners and kitchen tickets
Think about checking how fast a restaurant is. You send in diners, more and more of them, and each one times how long the plate takes. That's a load test. But diners can't see why it's slow. So inside, each kitchen station stamps the ticket when it starts and when it's done. That's tracing.
Diners tell you the wait got worse. The ticket tells you the grill is where it's stuck. You want both. In Python, a load test (our own, or Locust) plays the diners, and OpenTelemetry stamps the tickets.
Inside: a header and a log line
The simplest thing that works is a middleware in app.py:
@app.middleware("http")
async def trace(request: Request, call_next):
start = time.perf_counter()
response = await call_next(request)
ms = (time.perf_counter() - start) * 1000
response.headers["X-Server-Ms"] = f"{ms:.2f}"
return response
@app.post("/v1/predict")
def predict(day: Weather):
t0 = time.perf_counter()
row = pd.DataFrame([day.model_dump()])
chance = float(model.predict_proba(row)[0, 1])
model_ms = (time.perf_counter() - t0) * 1000
log.info("model_ms=%.2f", model_ms)
return {"probability": round(chance, 2)}
The middleware wraps every request. It notes the time, lets the request through with call_next, works out the milliseconds and puts them on the response in a header called X-Server-Ms. One call:
One call came back with the body {"probability":0.63} and the header X-Server-Ms set to 14.20.
Inside predict, we time just the model part and send it to the log as model_ms. There's no value to show for that one: the server ran at warning level in this run, so the info line never printed.
That's the whole idea of tracing in two small lines: a time for the whole request, and a time for one stage inside it.
Spans: one stamp per stage
OpenTelemetry gives each of those timings a proper name. Each one is called a span. Here's traced.py:
import pandas as pd
from fastapi import FastAPI
from opentelemetry import trace
from opentelemetry.instrumentation.fastapi import (
FastAPIInstrumentor)
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import (
ConsoleSpanExporter, SimpleSpanProcessor)
from app import Weather, model
provider = TracerProvider()
provider.add_span_processor(
SimpleSpanProcessor(ConsoleSpanExporter()))
trace.set_tracer_provider(provider)
tracer = trace.get_tracer("rain")
app = FastAPI(title="Rain Predictor, traced")
FastAPIInstrumentor.instrument_app(
app, exclude_spans=["receive", "send"])
@app.post("/v1/predict")
def predict(day: Weather):
with tracer.start_as_current_span("build_row"):
row = pd.DataFrame([day.model_dump()])
with tracer.start_as_current_span("predict"):
chance = float(model.predict_proba(row)[0, 1])
return {"probability": round(chance, 2)}
- A
withblock opens a span around each stage. FastAPIInstrumentor.instrument_appadds an outer span for the whole request.- The exporter decides where spans go. Here it's the console, so each request prints a little tree of spans with a time on each. A tool such as Jaeger can draw the same tree.
In one traced request from this run, the outer POST /v1/predict span took 12.657 ms, with two child spans inside it: build_row at 0.619 ms and predict at 9.7 ms. Over 2,800 calls, one at a time, with the first 200 thrown away as warm-up, the spans gave:
| Span | p50 (ms) | p95 (ms) |
|---|---|---|
| POST /v1/predict (whole request) | 12.65 | 18.88 |
| build_row | 0.92 | 1.34 |
| predict | 9.54 | 14.78 |
Building the row takes under a millisecond. The model is where the time goes. Versions used: opentelemetry-sdk==1.45.1 and opentelemetry-instrumentation-fastapi==0.66b1.
Outside: our own load test
Now the outside stopwatch, loadtest.py:
import asyncio
import time
import httpx
import numpy as np
DAY = {"Rainfall": 0.4, "Humidity3pm": 85, "Cloud9am": 7,
"Cloud3pm": 8, "RainToday": "No"}
async def worker(client, url, count, out):
for _ in range(count):
t0 = time.perf_counter()
r = await client.post(url, json=DAY)
ms = (time.perf_counter() - t0) * 1000
out.append((ms, r.status_code))
async def run(url, concurrency, total):
out = []
each = total // concurrency
limits = httpx.Limits(max_connections=concurrency)
async with httpx.AsyncClient(limits=limits) as client:
t0 = time.perf_counter()
await asyncio.gather(*[
worker(client, url, each, out)
for _ in range(concurrency)])
wall = time.perf_counter() - t0
ms = np.array([m for m, _ in out])
bad = sum(1 for _, s in out if s != 200)
return {"concurrency": concurrency,
"requests": len(out), "errors": bad,
"rps": len(out) / wall,
"p50": float(np.percentile(ms, 50)),
"p95": float(np.percentile(ms, 95)),
"samples": ms.tolist()}
A worker is a loop: start a timer, post one row of weather, wait for the reply, stop the timer. The time and the status code go into a list, and only then does it send the next one. So a worker holds one request at a time.
run starts as many workers as the concurrency we ask for and splits the total between them: 640 requests with 64 workers is 10 each. At the end we get a throughput, a p50, a p95 and an error count.
One thing to watch. Because a worker waits for each reply, the test slows itself down when the API slows down. Real users don't always wait politely, so a test like this can go easy on a struggling server.
What to write beside the number
| Callers | Requests/s | p50 (ms) | p95 (ms) | Errors |
|---|---|---|---|---|
| 1 | 58.5 | 16.6 | 25.9 | 0 |
| 4 | 69.2 | 54.8 | 87.2 | 0 |
| 16 | 74.0 | 205.9 | 334.8 | 0 |
| 64 | 86.9 | 730.1 | 877.8 | 0 |
Before you trust a row like that, write three things beside it:
- The load: how many callers at once.
- Where it was timed: here, at the caller.
- The machine: here, one uvicorn worker on a local CPU, with the load test on the same machine, competing for the same CPU.
These are this machine's numbers on this day. They differ from the run in Latency Math because it's a separate run, which is exactly why the label matters. On your target hardware, you'd run it again.
Locust: the same idea, ready made
Locust does the same job with more features. You write a user class:
from locust import HttpUser, constant, task
from loadtest import DAY
class RainUser(HttpUser):
wait_time = constant(0)
@task
def predict(self):
self.client.post("/v1/predict", json=DAY)
One task posts the same row of weather, and wait_time = constant(0) makes each user behave like our workers. One command sets the users, how quickly they ramp up, how long to run, and which host to hit:
locust -f locustfile.py --headless -u 64 -r 8 -t 1m --host http://127.0.0.1:8000
At the end of the one-minute run with 64 users, Locust printed its percentile table (times in ms; the wide Name column is shortened here):
Type Name 50% 66% 75% 80% 90% 95% 98% 99% 99.9% 99.99% 100% # reqs
POST /v1/predict 910 980 1000 1000 1100 1100 1200 1300 1400 1500 1500 4067
Zero failures, a p95 of 1,100 ms, and p99 comes for free. It's a different client from ours, so don't expect the same digits.

So why switch? Our script is short, and you can read every line. Locust gives you the ramp-up, charts in a browser like these, and load from more than one machine. Start small, and move when you need those.
Common mistakes
- Waiting for errors. At 64 callers, p95 was 878 ms with zero errors. Slow is not the same as failing.
- Measuring only outside. You'll know it's slow, not why. Add spans around the stages.
- Measuring only inside. Server time misses the queue in front of the server.
- A number with no label. Write the load, where it was timed, and the machine.
- Load test and server on one machine, read as production numbers. They compete for the same CPU.
Quick recap
| Stopwatch | Tool | What it told us |
|---|---|---|
| Inside, whole request | middleware, X-Server-Ms | 14.20 ms for one call |
| Inside, per stage | OpenTelemetry spans | predict 9.54 ms at p50; build_row under 1 ms |
| Outside | loadtest.py | p95 from 25.9 ms (1 caller) to 877.8 ms (64), 0 errors |
| Outside, ready made | Locust | 64 users, p95 1,100 ms, p99 1,300 ms, 0 failures |
Try it yourself
Turn on info logging in app.py, then compare model_ms at one caller and at 64. Did the model get slower, or was the request waiting?
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Latency Math: p50, p95, p99 and Why the Tail Reaches Your Users
Next →Making ML Inference Fast: ONNX, Micro-Batching and Quantisation, Measured
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
Python Virtual Environments: One Project, One Toolbox
Why every Python project gets its own virtual environment: two projects that need different versions of requests, python -m venv .venv, activation, pip install and the PyCharm setting that activates it for you.
Git and GitHub Fundamentals: Commits, Branches, Push and Pull
The Git you use every day, on a tiny hello-ml project: commits as save points, the staging area, a branch merged with a fast-forward, then push, clone, pull and pull requests with a teammate.
Testing a FastAPI App with pytest: Three Small Tests
A tiny FastAPI app with a Hello World route and a name route that refuses numbers, three pytest tests that check it, and what happens when the validation is deleted by mistake.
Config and Logging Instead of Hard-Coded Values in ML Training
Take the hard-coded values out of a car price training script: one config.toml read with tomllib, logging with levels and a run id on every line, and secrets read from the environment. Same RMSE, 2195, before and after.