Sub topic 14
Metrics to watch for batching and scaling
This chapter assumes you know what p50 and p99 mean, can read basic Python and YAML, and have met the dynamic batcher and the Kubernetes autoscaler from earlier chapters. It covers which numbers to record, how to read them, and which ones should drive scaling decisions.
Why end-to-end latency is not enough
A single latency number tells you that something is slow. It does not tell you where. A request in a batched service passes through several stages, and each stage fails differently:
- Queue wait. The time a request sits before its batch starts. It grows when the batcher waits for a full batch or when replicas are saturated.
- Execution time. The time the model spends on a batch. It grows with batch size and with hardware contention.
- Everything else. Network, serialization, and load balancer time.
If p99 rises because of queue wait, you add replicas or lower the batching delay. If it rises because of execution time, adding replicas will not help. You may need a smaller maximum batch size or a faster model. Measuring each stage separately is what lets you choose the right fix.
The core metrics
| Metric | Type | What it shows | Typical action |
|---|---|---|---|
| Request rate | Counter | Offered load | Compare with capacity |
| End-to-end latency | Histogram | What clients experience | Alert against the SLO |
| Queue wait | Histogram | Time spent before batching and execution | Tune max queue delay, add replicas |
| Execution time | Histogram | Model compute per batch | Tune max batch size, optimize model |
| Batch size | Histogram | How full batches actually are | Tune delay and batch limit |
| Queue depth | Gauge | Requests waiting right now | Scaling signal |
| In-flight requests | Gauge | Concurrency per replica | Scaling signal |
| Accelerator utilization | Gauge | Busy fraction of the device | Capacity check only |
| Error and timeout rate | Counter | Rejections, deadline misses | Alert, check for overload |
Use histograms for anything you want a percentile of. Averages hide the tail. Choose bucket boundaries around your latency objective. If your target is 100 ms, you need several buckets between 10 ms and 250 ms, or the interpolated p99 will be coarse.
Instrumenting a batcher
The following script exposes the stage metrics from a simulated batch loop. In a real server, you would call record_batch from the batcher's run loop after each batch completes. It needs pip install prometheus-client.
import random
import time
from prometheus_client import Gauge, Histogram, start_http_server
BATCH_SIZE = Histogram(
"inference_batch_size", "Requests per executed batch",
buckets=[1, 2, 4, 8, 16, 32],
)
QUEUE_WAIT = Histogram(
"inference_queue_wait_seconds", "Time a request waited before execution",
buckets=[0.001, 0.002, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1],
)
EXEC_TIME = Histogram(
"inference_execution_seconds", "Model execution time per batch",
buckets=[0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1],
)
QUEUE_DEPTH = Gauge("inference_queue_depth", "Requests currently waiting")
def record_batch(waits_s, exec_s, depth_after):
"""Record one executed batch. waits_s has one entry per request."""
BATCH_SIZE.observe(len(waits_s))
for wait in waits_s:
QUEUE_WAIT.observe(wait)
EXEC_TIME.observe(exec_s)
QUEUE_DEPTH.set(depth_after)
if __name__ == "__main__":
start_http_server(8000) # metrics at http://localhost:8000/metrics
while True:
size = random.randint(1, 16)
waits = [random.uniform(0.001, 0.02) for _ in range(size)]
record_batch(waits, exec_s=0.01 + 0.002 * size, depth_after=random.randint(0, 12))
time.sleep(0.05)Queue wait is recorded per request, not per batch. The first request in a batch waits the longest, and a per-batch number would hide that.
Queries that answer real questions
These PromQL queries assume the metric names above and a five-minute window.
# p99 queue wait across all replicas
histogram_quantile(0.99, sum by (le) (rate(inference_queue_wait_seconds_bucket[5m])))
# p99 execution time per batch
histogram_quantile(0.99, sum by (le) (rate(inference_execution_seconds_bucket[5m])))
# Mean batch size
rate(inference_batch_size_sum[5m]) / rate(inference_batch_size_count[5m])Aggregate buckets with sum by (le) before calling histogram_quantile. Averaging per-replica percentiles gives a wrong answer.
Reading batch size
Divide mean batch size by your configured maximum to get a fill ratio. Interpret it with the arrival rate in mind:
- Low fill ratio at low traffic is normal. The batcher is hitting its delay limit and sending small batches. Latency is good and the accelerator is underused, which is acceptable.
- Low fill ratio at high traffic suggests that batching is not working. Check that the request path is not serializing requests before they reach the batcher.
- Fill ratio near 1.0 with growing queue wait means the replica is saturated. Batches are always full and requests still wait. Scale out.
Reading queue wait against the delay setting
Queue wait has a floor set by your max queue delay. If max delay is 5 ms and p50 queue wait is 4 ms, the batcher is working as designed. If p99 queue wait is 200 ms, the delay setting cannot explain it. Requests are waiting behind other batches, and the replica is overloaded.
Choosing signals for the autoscaler
Not every metric is a good scaling signal. A good signal responds quickly to load, moves roughly in proportion to it, and does not depend on your own batching settings.
- Queue depth per pod. Responds immediately when load exceeds capacity and returns to near zero when replicas catch up. It is the best general choice, as in the earlier HPA example.
- In-flight requests per pod. Works well when each replica has a known concurrency limit. It is the basis of the Little's law sizing from the previous chapter.
- Accelerator utilization. This is a weak signal. A GPU can report high utilization with one request in flight, and batching can keep it busy without any queue forming. Use it to judge efficiency, not to trigger scaling.
- p99 latency. A lagging signal. By the time it rises, users are already affected, and scaling on it can oscillate because adding replicas lowers latency, which removes the reason for the replicas.
A gauge such as inference_queue_depth reaches the Horizontal Pod Autoscaler through a custom metrics adapter. This Prometheus Adapter rule exposes it as a per-pod metric:
rules:
- seriesQuery: 'inference_queue_depth{namespace!="",pod!=""}'
resources:
overrides:
namespace: {resource: "namespace"}
pod: {resource: "pod"}
metricsQuery: 'avg(<<.Series>>{<<.LabelMatchers>>}) by (<<.GroupBy>>)'Metrics that reveal scaling problems
- Replica count over time. Rapid up-and-down changes mean flapping. Increase the scale-down stabilization window or smooth the signal.
- Desired versus ready replicas. A persistent gap means pods are pending (no capacity in the cluster) or slow to become ready (cold start).
- Time from pod start to first successful request. This is your real cold start. Compare it with how fast load can rise.
- Rejections and timeouts during scale-up. These show whether
minReplicasand headroom cover the time the autoscaler needs to react.
Alerts that matter
Alert on symptoms first and causes second:
- End-to-end p99 above the SLO for several minutes (symptom).
- Queue wait p99 above a fixed share of the latency budget, for example half (early warning).
- Replicas at
maxReplicaswhile queue depth stays above target (capacity ceiling reached). - Desired replicas greater than ready replicas for longer than your expected cold start (scaling stuck).
Common mistakes
- Recording only per-batch latency, which hides how long individual requests waited.
- Using the default histogram buckets, which top out far from typical inference latencies and give coarse percentiles.
- Scaling on mean utilization and wondering why the queue grows.
- Averaging percentiles across replicas.
- Forgetting that the batcher's own max delay is part of latency. Raising it improves batch fill at the cost of every request's wait.
Exercise
Your service shows mean batch size 3 (max batch size 32), p99 queue wait 180 ms, and p99 execution time 20 ms. The max queue delay is 5 ms. Is adding more replicas or raising the max queue delay the better first step, and why?
Show answer
Add replicas. Queue wait of 180 ms is far above the 5 ms delay setting, so requests are waiting behind other work, not for a batch to fill. Raising the delay would add more waiting. The small mean batch size does not indicate a batching problem here. Batches are small because they are being sent quickly at the delay limit or because load is spread thinly. First check whether the queue is long because replicas are saturated or because requests are not reaching the batcher efficiently, then scale out on queue depth.
Exercise
Why is accelerator utilization a poor primary scaling signal for a dynamically batched model server, and what would you use instead?
Show answer
Utilization measures how busy the device is, not how much work is waiting. A device can show high utilization while serving one request at a time, or stay below 100% while a queue builds because of CPU-side preprocessing or batching delay. Use per-pod queue depth or in-flight requests, which rise directly when offered load exceeds capacity, and keep utilization as an efficiency check.