Sub topic 13
Logging and monitoring predictions
A service that returns correct answers on day one can still go wrong later without any error. Traffic changes, inputs drift, or a new model version behaves differently. This chapter adds logging and metrics to the FastAPI service so you can see what it is doing and notice when it degrades.
This chapter assumes you have the main.py service from the earlier chapters (a /predict endpoint, a model loaded at startup, and a /health endpoint). You should also be comfortable reading JSON and running commands in a terminal.
What to observe
An inference service has three kinds of signals.
| Signal | Question it answers | Typical tool |
|---|---|---|
| Logs | What happened on this specific request? | Structured JSON lines |
| Metrics | How is the service behaving in aggregate? | Counters and histograms, scraped by Prometheus |
| Model quality | Are the inputs and outputs still like the training data? | Drift checks on logged data |
Logs and metrics are the same for any web service. The third row is specific to machine learning. A model never raises an exception when its inputs drift. It keeps returning confident-looking answers that are wrong more often.
Structured logs
Plain text such as predicted 1 in 3 ms is easy to write and hard to query. A structured log writes one JSON object per line, so a log system can filter on fields like status or model_version.
Every log line for a request should carry a request ID. If the client sends an x-request-id header, reuse it. Otherwise, generate one. The ID lets you find all log lines for one request, and the client can quote it in a bug report.
The middleware below logs one line per request with the path, status code, and total latency. It also sets the ID on the response.
import json
import logging
import time
import uuid
from fastapi import FastAPI, Request
logging.basicConfig(level=logging.INFO, format="%(message)s")
logger = logging.getLogger("inference")
MODEL_VERSION = "iris-rf-1"
def log_event(**fields):
logger.info(json.dumps(fields))
@app.middleware("http")
async def log_requests(request: Request, call_next):
request_id = request.headers.get("x-request-id", str(uuid.uuid4()))
request.state.request_id = request_id
start = time.perf_counter()
response = await call_next(request)
latency_ms = (time.perf_counter() - start) * 1000
response.headers["x-request-id"] = request_id
log_event(
event="request",
request_id=request_id,
method=request.method,
path=request.url.path,
status=response.status_code,
latency_ms=round(latency_ms, 2),
)
return responsePlace this after app = FastAPI(lifespan=lifespan) in main.py. The imports go at the top of the file.
Because the middleware wraps the whole request, it also logs requests that fail validation. A 422 response appears in the log with its status, which shows how often clients send bad input.
Logging the prediction itself
The request line says a call was made. It does not say what the model decided. Add a second event inside the endpoint that records the model version, the inputs, and the output, tied to the same request ID.
Metrics with Prometheus
Logs are good for single requests. For rates and percentiles, use metrics. A counter only goes up, such as the number of predictions. A histogram counts observations in buckets, such as how many model calls took under 10 ms, so you can estimate percentiles like p95.
Install the client with pip install prometheus-client. The updated endpoint below records a metric, writes the prediction log event, and exposes a /metrics endpoint that Prometheus can scrape.
from prometheus_client import Counter, Histogram, make_asgi_app
PREDICTIONS = Counter(
"predictions_total",
"Predictions served, by predicted class",
["class_index"],
)
MODEL_LATENCY = Histogram(
"model_latency_seconds",
"Time spent inside model.predict",
buckets=(0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0),
)
app.mount("/metrics", make_asgi_app())
@app.post("/predict", response_model=Prediction)
def predict(features: IrisFeatures, request: Request):
row = [[
features.sepal_length,
features.sepal_width,
features.petal_length,
features.petal_width,
]]
with MODEL_LATENCY.time():
prediction = int(models["iris"].predict(row)[0])
PREDICTIONS.labels(class_index=str(prediction)).inc()
log_event(
event="prediction",
request_id=request.state.request_id,
model_version=MODEL_VERSION,
class_index=prediction,
features=features.model_dump(),
)
return Prediction(class_index=prediction)This replaces the earlier /predict function. Run the service, send a few requests, then open http://localhost:8000/metrics/. You will see lines such as predictions_total{class_index="0"} 3.0 and the histogram buckets.
Two design choices matter here:
- Time the model call separately from the request.
MODEL_LATENCYmeasures onlypredict. The middleware measures everything, including validation and serialization. If total latency rises but model latency does not, the problem is outside the model. - Keep label values to a small, fixed set. The class index has three values. Never use a request ID, user ID, or a raw feature value as a label. Each distinct value creates a new time series, and thousands of them can overload your monitoring system.
The four numbers to watch
Start with a small set of service-level metrics, often called the golden signals:
- Traffic. Requests per second, from the request counts.
- Errors. The share of
5xxresponses. Track422separately, because a spike usually means a client changed its payload, not that your service is broken. - Latency. p50 and p95 of total request time. Averages hide slow tails.
- Saturation. CPU, memory, and queue depth. A model service is often CPU-bound, so high CPU with rising latency means you need more replicas.
For ML, add the predicted class distribution. If the service predicted all three classes about equally for weeks and suddenly returns class 2 for 90% of requests, something changed in the inputs or in the model.
Detecting drift from logged inputs
Data drift means the live inputs no longer resemble the training data. You can check it with the prediction events you already log. This script compares the mean of each logged feature with the training mean, measured in training standard deviations.
uvicorn main:app 2>&1 | grep --line-buffered '"event": "prediction"' > predictions.logimport json
import statistics
from sklearn.datasets import load_iris
NAMES = ["sepal_length", "sepal_width", "petal_length", "petal_width"]
X, _ = load_iris(return_X_y=True)
train_mean = X.mean(axis=0)
train_std = X.std(axis=0)
recent = {name: [] for name in NAMES}
with open("predictions.log") as f:
for line in f:
event = json.loads(line)
for name in NAMES:
recent[name].append(event["features"][name])
for i, name in enumerate(NAMES):
if recent[name]:
shift = (statistics.mean(recent[name]) - train_mean[i]) / train_std[i]
print(f"{name}: shift {shift:+.2f} std")A shift above about 1 standard deviation on a feature deserves a look. This is a crude check. It ignores changes in spread and in relationships between features, and it needs enough requests to be stable. Dedicated drift libraries use stronger statistical tests, but the principle is the same: compare live data with a reference.
Accuracy needs labels
Drift tells you the inputs changed. It does not tell you the predictions are wrong. To measure accuracy you need the true outcome, and that often arrives late or never. A fraud label may arrive weeks after the transaction.
Plan for this by logging the request_id and the prediction. When the true label arrives, join it to the logged prediction by that ID and compute accuracy over a time window. Without the ID, you cannot link the two.
Privacy and volume
Volume matters too. Logging every feature of every request at high traffic is expensive. A common approach is to log the request line for every call and the full prediction event for a sample, for example one request in ten.
Common mistakes
- Using
print. Output is unstructured, has no level, and is hard to route. - Logging only failures. You cannot compute a baseline error rate without the successes.
- Forgetting the model version. After a deploy, you cannot tell which model produced which predictions. The
model_versionfield in the prediction event solves this. - Alerting on every spike. Alert on sustained conditions, such as p95 above a threshold for five minutes, so the alerts stay useful.
- Per-process metrics with several workers. With
uvicorn --workers 4, each process has its own counters, and the default client does not merge them. Theprometheus_clientlibrary has a multiprocess mode for this, and running one process per container avoids the problem.
Exercise
Your /metrics output shows model_latency_seconds unchanged, but the request log shows latency_ms doubling over the last hour. Where should you look first, and why?
Show answer
Look at work outside model.predict. The histogram times only the model call, so a stable value rules out a slower model. The extra time is in validation, serialization, the middleware, or queuing. Check saturation (CPU, memory, request queue depth) and whether the service is receiving more traffic than its workers can handle. Adding replicas or checking for blocking work in the event loop are the next steps.
Exercise
A teammate suggests adding the raw sepal_length value as a Prometheus label so you can graph it. Why is this a bad idea, and what should you do instead?
Show answer
Each distinct value of a label creates a separate time series. A continuous feature has an almost unlimited number of values, so memory use in Prometheus grows without bound. Log the feature value in the structured prediction event instead, and compute summaries such as a mean or a histogram of bucketed values. A fixed-bucket histogram metric is acceptable because the number of buckets is fixed.