Sub topic 3
Operational Health: Latency, Errors and Throughput
This chapter covers the first monitoring layer, which asks whether the service is up and answering fast enough. It assumes you can deploy a model as an API or a batch job and that you know what a percentile is. Data quality, drift and performance come in later chapters. Operational metrics come first because a model that does not respond cannot be wrong in any interesting way.
Why operational metrics come first
Operational problems are the easiest production failures to detect and the most urgent. They need no labels and no reference data. They are also the same for every model, so you can reuse the tooling from ordinary web services.
Operational metrics also help later. If prediction volume drops to zero, a drift test on the empty window tells you nothing. If latency jumps because a feature lookup times out, you may see missing values in the data quality layer. Read the layers together, starting from the bottom.
The three signals
Track three signals for every serving path.
| Signal | What it measures | Typical metric | Common causes of trouble |
|---|---|---|---|
| Latency | How long a request takes | p50, p95, p99 in milliseconds | Large payloads, slow feature lookups, cold starts, CPU contention |
| Errors | How many requests fail | Error rate per status class or exception type | Bad input, timeouts, out-of-memory, dependency outage |
| Throughput | How much work arrives and completes | Requests per second, rows per batch run | Traffic spikes, upstream outages, retry storms |
Add one more measure, saturation, which is how close the service is to its limits. CPU, memory, GPU utilization and queue depth are all saturation measures. Saturation often rises before latency and errors do, so it gives you early warning.
The next diagram shows where to measure on a typical request path.
Measure at each stage, not only end to end. End-to-end latency tells you that something is slow. Per-stage latency tells you where.
Latency: use percentiles, not averages
Latency distributions are skewed. Most requests are fast and a few are very slow. The mean hides the slow tail, and the tail is what users and downstream timeouts notice.
- p50 (the median) shows typical behavior.
- p95 and p99 show the slow tail. p99 is the latency that 1 request in 100 exceeds.
Never average percentiles across servers or time windows. The average of two p99 values is not the p99 of the combined traffic. Aggregate the raw samples or histogram buckets, then compute the percentile.
Set a latency budget from the caller's needs. If a checkout page waits at most 300 ms in total and the other calls use 200 ms, your model gets about 100 ms at p99. Alert against that budget, not against a number that looks nice.
Errors: separate the kinds
A single "error rate" hides the cause. Split errors into at least these groups:
- Client errors, such as malformed requests or failed schema validation. These point at callers, or at an upstream change in what they send.
- Server errors, such as exceptions in your code or model loading failures.
- Timeouts, from your service or from a dependency such as a feature store.
- Fallbacks, where the service catches a failure and returns a default prediction.
Compute error rate as a ratio of failed requests to total requests over a window. A raw count of errors rises with traffic and tells you little by itself.
Throughput and saturation
Throughput is the number of requests (or batch rows) completed per unit of time. Watch it for two reasons.
A sudden drop usually means the callers stopped sending traffic, a deploy broke routing, or an upstream job did not run. Your service may report healthy while doing no work. For batch jobs, track rows scored per run and run duration, and alert when a scheduled run does not finish by its deadline.
A sudden rise can exhaust capacity. When requests queue up, latency climbs first, then timeouts, then errors. Retries from clients then add more load, which is a retry storm. Track queue depth and concurrent requests alongside requests per second.
Compare throughput with the same hour of the previous week as well as with the previous hour. Traffic has daily and weekly cycles, and a comparison with the last hour will raise false alarms every morning.
Instrumenting a prediction service
Use a metrics library such as Prometheus client libraries or your cloud provider's agent in production. The sketch below uses only NumPy and the standard library to show the logic: a sliding window of events, and a snapshot of rate, error rate and latency percentiles.
import time
from collections import deque
import numpy as np
class ServiceMetrics:
"""Sliding-window metrics for a prediction service."""
def __init__(self, window_seconds=60):
self.window = window_seconds
self.events = deque() # (timestamp, latency_ms, ok)
def record(self, latency_ms, ok, now=None):
now = time.time() if now is None else now
self.events.append((now, latency_ms, ok))
self._evict(now)
def _evict(self, now):
while self.events and self.events[0][0] < now - self.window:
self.events.popleft()
def snapshot(self, now=None):
now = time.time() if now is None else now
self._evict(now)
if not self.events:
return {"requests_per_s": 0.0, "error_rate": None}
latency = np.array([e[1] for e in self.events])
ok = np.array([e[2] for e in self.events], dtype=float)
return {
"requests_per_s": len(latency) / self.window,
"error_rate": float(1.0 - ok.mean()),
"mean_ms": float(latency.mean()),
"p50_ms": float(np.percentile(latency, 50)),
"p95_ms": float(np.percentile(latency, 95)),
"p99_ms": float(np.percentile(latency, 99)),
}
rng = np.random.default_rng(0)
metrics = ServiceMetrics(window_seconds=60)
timestamps = np.linspace(0, 59.9, 600)
latencies = rng.lognormal(mean=np.log(40), sigma=0.6, size=600)
successes = rng.random(600) > 0.02
for t, lat, ok in zip(timestamps, latencies, successes):
metrics.record(float(lat), bool(ok), now=float(t))
for name, value in metrics.snapshot(now=60.0).items():
print(f"{name}: {value:.3f}")The simulated latencies are lognormal, so the mean lands above the median and p99 sits several times higher than p50. That gap is the reason to alert on percentiles.
Pass the timestamp in explicitly, as the example does, so the class can be tested without waiting in real time.
What is different for ML services
Model services have failure modes that ordinary web services lack.
- Cold starts. Loading a large model on the first request can take seconds. Warm the model at startup and exclude warm-up from latency alerts, or track it separately.
- Input-dependent latency. Inference time can grow with input size, such as text length or number of items to rank. Log input size beside latency so you can tell "slow because inputs grew" from "slow because the machine is overloaded".
- Batching effects. Dynamic batching trades higher latency per request for higher throughput per GPU. If you change batch settings, expect both curves to move.
- Dependency latency. Feature stores, embedding services and databases often cost more time than the model. Measure them separately.
- Resource limits. Memory leaks and GPU memory fragmentation show up as slow growth in saturation metrics. A flat error rate does not rule them out.
- Version labels. Tag every metric with the model version and the deployment. After a release, you can then compare the new version with the old one on the same traffic.
Common mistakes
- Alerting on the mean latency. A tail problem that affects 2% of requests leaves the mean almost unchanged.
- Averaging percentiles from several instances. Merge histograms or raw samples instead.
- Treating HTTP 200 as success. Count fallbacks and validation rejections separately.
- Alerting on a fixed threshold copied from another service. Derive thresholds from the caller's latency budget and from your own history.
- Ignoring low traffic. With 5 requests in a window, a single failure is a 20% error rate. Require a minimum request count before an error-rate alert can fire.
- Missing the silent stop. Alert on "no requests received" as well as on high error rates.
Threshold design and false-alarm control for all layers, including these, get their own chapter later in the tutorial.
Exercises
Exercise
A service has a mean latency of 45 ms, and the dashboard shows green. Users still complain about slow responses. Which statistic should you check first, and why?
Show answer
Check p95 and p99 latency. The mean is pulled down by the many fast requests and hides the slow tail. If 2% of requests take several seconds, the mean barely moves, but those requests are the ones users notice.
Exercise
Your fraud model's API reports a 0% error rate and normal latency, but analysts notice that almost every score is exactly 0.05. What probably happened, and which operational metric would have caught it?
Show answer
The service is likely catching an exception, such as a failed feature lookup, and returning a default score with HTTP 200. A fallback counter, reported as a rate of fallback responses per window, would have caught it. A second sign is the constant score itself, which the prediction-distribution checks in a later chapter would also show.
Exercise
Two instances report p99 latencies of 120 ms and 400 ms. A teammate reports the service p99 as 260 ms, their average. Why is this unreliable, and what should be done instead?
Show answer
The p99 of combined traffic depends on how many requests each instance served and on the shape of both distributions, so the average of the two p99 values has no fixed relationship to it. Merge the raw latency samples or histogram buckets from both instances and compute the percentile on the merged data.