Sub topic 4
Latency versus throughput
This chapter assumes you can read Python, know the terms model, feature and prediction, and have a rough idea of what an HTTP API and a scheduled job are. It defines latency and throughput, shows how to measure them, and explains why batch and real-time serving optimize different one.
Two different questions
Latency and throughput answer different questions about a serving system.
- Latency is the time one prediction takes, from the moment a request is sent to the moment the answer comes back. It is measured in milliseconds for an online service.
- Throughput is the number of predictions the system completes per unit of time, such as rows per second.
A system can have good numbers on one and poor numbers on the other. A batch job that scores 10 million rows in 20 minutes has high throughput, but any single row may wait 20 minutes for its score. An API that answers one request in 15 ms has low latency, but it may handle only a few hundred requests per second per instance.
Real-time prediction is judged mainly on latency, and usually on throughput as a second constraint. Batch prediction is judged mainly on throughput, or more precisely on whether the whole job finishes inside its time window.
How the two relate
Latency and throughput are linked by three mechanisms.
Batching raises throughput and lengthens waits
Most models run faster per row on many rows at once. Vectorized math, fewer Python calls, and better use of CPU caches or GPU hardware all reward large inputs. Scoring one row pays a fixed overhead for each call, and scoring 10,000 rows pays it once.
The cost is waiting. If a service collects requests into groups of 32 before running the model, the first request in the group waits for the other 31 to arrive. Throughput improves, and the latency of each individual request gets worse.
Concurrency connects the two numbers
Little's law describes the average state of a stable system:
concurrency = throughput × latencyIf each request takes 50 ms (0.05 s) and you must serve 400 requests per second, then on average 400 × 0.05 = 20 requests are in progress at once. You need capacity for about 20 simultaneous predictions. This tells you how many workers, threads or instances to provision before you test anything.
Load turns latency into a curve
Latency is not a fixed property of a model. At low load, a request starts immediately and takes its base time. As utilization approaches 100%, requests queue behind each other, and latency rises sharply. A service that answers in 20 ms at 30% utilization can take seconds at 95%. This is why online services are run with spare capacity, and why "maximum throughput" is not a safe operating point for them.
Measuring latency correctly
An average hides the requests that users complain about. Report percentiles:
- p50 (median): half of requests are faster than this.
- p95: 95% of requests are faster. One in twenty is slower.
- p99: one in a hundred is slower.
The slowest requests are called the tail. In a service with several steps (feature lookup, model call, post-processing), a request is slow if any step is slow, so tail latency grows as you add steps. Set service targets on a percentile, for example "p99 under 200 ms", and not on the mean.
Two measurement errors are common:
- Averaging percentiles. The mean of p99 values from ten servers is not the p99 of the whole fleet. Aggregate raw measurements or histograms instead.
- Measuring only the model call. Users experience network time, request parsing, feature fetching and queueing as well. Measure latency at the edge where the caller sees it, and also time each internal step so you can find the slow one.
A runnable measurement
The script below trains a small random forest on synthetic data. It then scores rows one at a time, the way an online service would, and scores the same rows in one call, the way a batch job would. You need numpy and scikit-learn installed.
import time
import numpy as np
from sklearn.ensemble import RandomForestClassifier
rng = np.random.default_rng(0)
X = rng.normal(size=(5000, 3))
y = (X[:, 0] + X[:, 1] > 0).astype(int)
model = RandomForestClassifier(n_estimators=100, random_state=0).fit(X, y)
rows = rng.normal(size=(2000, 3))
# Online style: one row per call, record each call's latency.
latencies = []
for row in rows[:300]:
start = time.perf_counter()
model.predict_proba(row.reshape(1, -1))
latencies.append(time.perf_counter() - start)
latencies_ms = np.array(latencies) * 1000
single_throughput = len(latencies) / sum(latencies)
# Batch style: all rows in a single call.
start = time.perf_counter()
model.predict_proba(rows)
batch_seconds = time.perf_counter() - start
batch_throughput = len(rows) / batch_seconds
print(f"single-row p50: {np.percentile(latencies_ms, 50):.1f} ms")
print(f"single-row p99: {np.percentile(latencies_ms, 99):.1f} ms")
print(f"single-row throughput: {single_throughput:,.0f} rows/s")
print(f"batch call took {batch_seconds * 1000:.1f} ms for {len(rows)} rows")
print(f"batch throughput: {batch_throughput:,.0f} rows/s")On most machines the batch throughput is many times higher than the single-row throughput. The exact numbers depend on your hardware and model, so run it yourself. Also note that the batch call's latency, in the sense of "time until you have the answer for row 1", is the full duration of the call.
What each pattern optimizes
| Aspect | Batch prediction | Real-time prediction |
|---|---|---|
| Main goal | Finish all rows inside a time window | Answer each request under a latency target |
| Metric that matters | Rows per second, job duration | p95 and p99 latency, requests per second |
| Typical batch size | Thousands to millions of rows | One row, or a small group |
| Hardware use | Run hot, then release | Keep spare capacity for traffic spikes |
| Effect of slowness | Job runs late, downstream tasks wait | Users see delays or timeouts |
| Tuning direction | Larger batches, more parallelism | Smaller work per request, warm models, caching |
Techniques for each side
Raising batch throughput
- Score in chunks that fit in memory. Reading a 50 GB file into one array fails, so process it in pieces, such as one partition at a time.
- Use vectorized calls on arrays or DataFrames instead of Python loops over rows.
- Split the data and score the pieces in parallel across processes or machines. This works because scoring each row is independent.
- Avoid doing feature computation row by row inside the loop. Compute features in bulk first, then score.
Lowering online latency
- Load the model once at startup, not on each request. Loading a large model per call can add seconds.
- Warm up after startup by sending a few dummy requests. The first call is often slower because of lazy initialization and cache misses. This is the cold start problem.
- Keep the model small enough, or use a simpler one, if the latency target requires it. A tree ensemble with 1,000 trees costs more per request than one with 100.
- Cache results for inputs that repeat.
- Set timeouts on feature lookups, so one slow dependency does not stall the whole request.
Dynamic batching: a middle path
Some online services, especially ones running on GPUs, group requests that arrive within a few milliseconds and run them as one batch. You set two limits: a maximum batch size and a maximum wait time. The group is sent to the model when either limit is reached.
The maximum wait time is the price you pay in latency. If your latency target is 100 ms and the model takes 40 ms, a wait limit of 5 to 10 ms is affordable. A wait limit of 100 ms is not.
Common mistakes
- Optimizing the wrong number. Pushing a nightly job to lower per-row latency gains nothing if it already finishes before the morning deadline. Pushing an API's throughput gains nothing if p99 latency is already over target.
- Load testing with one client. A single sequential client never builds a queue, so it hides the latency curve. Test with concurrent clients at several load levels.
- Testing with unrealistic inputs. Identical or tiny inputs hit caches and fast paths. Use a sample of production-like data.
- Ignoring the tail. The mean can look fine while p99 is ten times higher.
How this feeds later decisions
Latency and throughput limits decide what each approach costs and which one a use case needs. A requirement like "the answer must be shown while the user waits" forces real-time serving and a latency budget. A requirement like "score all customers before the 7 a.m. report" is a throughput and deadline problem, which batch handles well. Later chapters on cost, pipeline design and the decision framework build on these numbers.
Exercise
A fraud check service must handle 500 requests per second at peak. Each prediction takes 40 ms on one worker, and you want average utilization at peak to stay at or below 50%. Roughly how many workers do you need, and why is running exactly enough workers for 100% utilization risky?
Show answer
By Little's law, concurrency = 500 × 0.04 s = 20 requests in progress on average. At 50% target utilization you need about 20 / 0.5 = 40 workers. At 100% utilization any short burst or slow request builds a queue, and latency rises sharply, so p95 and p99 targets are missed even though average capacity looks sufficient.
Exercise
A team's API collects requests into groups of up to 64 before calling the model, with no maximum wait time. Throughput in load tests is excellent, but users report slow responses at night. What is the likely cause, and what change fixes it?
Show answer
At night traffic is low, so a group takes a long time to reach 64 requests, and each request waits for the group to fill. Adding a maximum wait time of a few milliseconds makes the batcher send whatever has arrived, which bounds the added latency while still batching at busy times.