Sub topic 10
Batch prediction and latency
This chapter assumes you have the main.py service from the earlier chapters running: a FastAPI app that loads a scikit-learn model at startup and serves /predict. You should also know what a request body and a JSON response are.
Why batching exists
Every request has a fixed cost: parsing HTTP, validating JSON, calling the model, and building a response. A model call also has overhead of its own. A scikit-learn model working on one row spends much of its time on setup, such as input checks and array conversion, rather than on math.
If a client has 1,000 rows to score, it can send 1,000 requests or one request with 1,000 rows. The second option pays the fixed costs once. Batching usually lowers the cost per row. It does not lower the time until the first result.
A batch endpoint
Add this to main.py. It reuses IrisFeatures, so every row gets the same validation as a single request.
class BatchRequest(BaseModel):
instances: list[IrisFeatures]
@app.post("/predict/batch")
def predict_batch(request: BatchRequest):
rows = [
[i.sepal_length, i.sepal_width, i.petal_length, i.petal_width]
for i in request.instances
]
predictions = models["iris"].predict(rows)
return {"class_indices": [int(p) for p in predictions]}The model's predict receives all rows in one call. The response keeps the same order as the input, so the client matches results to rows by position.
Latency versus throughput
Two measures matter here:
- Latency is the time one request takes from send to response.
- Throughput is the number of rows scored per second.
Batching improves throughput, but it can hurt latency. A batch of 1,000 rows takes longer than a batch of 1, and every row in it waits for the whole batch to finish.
| Approach | Latency per request | Throughput | Good fit |
|---|---|---|---|
| Single predictions | Low | Lower | Interactive use, such as a web form |
| Batch predictions | Higher | Higher | Offline scoring, nightly jobs, bulk imports |
Common errors
- No size limit. A client can send a million rows and use all the memory. Cap the list length in the schema, for example
Field(max_length=1000)oninstances. - One bad row fails the batch. Validation is all-or-nothing. A single invalid row makes the whole request return 422. Decide whether that is acceptable, or whether you want per-row errors.
- Reordering results. Keep outputs in input order. Clients depend on it.
- Long requests hit timeouts. Proxies and clients often cut connections after 30 to 60 seconds. For very large jobs, accept the work and return a job ID that the client polls later.
Trying it
curl -X POST http://localhost:8000/predict/batch \
-H "Content-Type: application/json" \
-d '{"instances": [
{"sepal_length": 5.1, "sepal_width": 3.5, "petal_length": 1.4, "petal_width": 0.2},
{"sepal_length": 6.7, "sepal_width": 3.0, "petal_length": 5.2, "petal_width": 2.3}
]}'Expect a response such as {"class_indices": [0, 2]}.
Exercise
A mobile app sends one row at a time and users complain about slow responses, while a nightly job scores 2 million rows through the same service. Which endpoint should each client use, and what limit would you add to the batch endpoint?
Show answer
The mobile app should use /predict, because a single row returns quickly and does not wait on other rows. The nightly job should use /predict/batch, sent in chunks, because batching raises throughput. Add a maximum list length to instances, such as 1,000 rows, so one request cannot exhaust memory or hit a proxy timeout. The nightly job then sends 2,000 requests of 1,000 rows each.