Sub topic 10
Batch prediction and latency
This chapter assumes you have the /predict endpoint from the earlier chapters. It also assumes you can read a FastAPI route with Pydantic models and know what a scikit-learn predict call returns. The chapter adds an endpoint that scores many rows per request and explains when that helps and when it hurts.
Why one row per request is expensive
A single call to /predict pays several costs besides the model's arithmetic:
- A network round trip between the client and the service.
- HTTP parsing and JSON decoding.
- Pydantic validation of the body.
- Python function-call and framework overhead.
- A fixed cost inside
model.predictitself, such as input conversion and, for a random forest, looping over the trees.
For a small model like the iris forest, these fixed costs are much larger than the time spent computing one answer. If a client has 5,000 rows to score, 5,000 separate requests pay those costs 5,000 times. One request with 5,000 rows pays most of them once.
Many scikit-learn models also work on whole arrays. A single call on a matrix is usually much cheaper per row than many calls on one-row matrices. Neural network libraries show the same effect more strongly, because GPUs only run efficiently on large inputs.
Measuring the difference
Check the claim before building anything. This script loads the model saved earlier and compares 1,000 one-row calls with one 1,000-row call:
import time
import joblib
model = joblib.load("model.joblib")
row = [5.1, 3.5, 1.4, 0.2]
n = 1000
start = time.perf_counter()
for _ in range(n):
model.predict([row])
single_seconds = time.perf_counter() - start
start = time.perf_counter()
model.predict([row] * n)
batch_seconds = time.perf_counter() - start
print(f"{n} single calls: {single_seconds:.3f} s")
print(f"one batch of {n}: {batch_seconds:.3f} s")
print(f"speed-up: {single_seconds / batch_seconds:.0f}x")The numbers depend on your machine, but the batch call is normally many times faster. This script leaves out the network, so the gap over HTTP is usually even larger.
Adding a batch endpoint
Add this to main.py. It reuses IrisFeatures, so every row gets the same validation as a single request.
MAX_BATCH_SIZE = 1000
class BatchRequest(BaseModel):
instances: list[IrisFeatures] = Field(min_length=1, max_length=MAX_BATCH_SIZE)
@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]}This version adds two limits to the plain batch endpoint, and both matter.
min_length=1rejects an empty list. scikit-learn raises aValueErrorwhen it receives zero samples, and without this check the client would see a 500 error instead of a clear 422.max_length=MAX_BATCH_SIZEcaps the work one request can demand. Without a cap, one client can send a million rows and exhaust memory or hold a worker for minutes.
Send a request with two rows:
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}
]}'The response is {"class_indices": [0, 2]}. The output list has the same length and order as the input list, so the first prediction belongs to the first row. This ordering guarantee is part of the contract, and clients depend on it.
Design decisions in the batch contract
One bad row fails the whole batch
Pydantic validates every item in instances. If row 700 has a negative value, the whole request returns 422 and no predictions come back. The error body includes the location of the bad item, for example ["body", "instances", 700, "sepal_length"], so the client can find it.
That behavior is simple and predictable. The alternative is partial success, where the service returns a result or an error for each row. It is more work for both sides, so adopt it only if clients really need it.
Keep the response shape stable
A response that is a bare list is hard to extend. An object like {"class_indices": [...]} lets you add model_version or per-row probabilities later without breaking clients. Versioning is covered in a later chapter.
Cap by rows and by bytes
A row limit does not bound the request size if rows can be large. Iris rows are four numbers, so the row cap is enough. For models that take text or images, also limit the request body size at the reverse proxy or server.
The latency trade-off
Batching improves throughput, which is rows scored per second. It can make latency worse, which is the time one caller waits for an answer. These are different goals.
| Row | Single requests | One large batch |
|---|---|---|
| Time until the first answer | Short | Longer, because you wait for the whole batch |
| Total time for 1,000 rows | Long, since fixed costs repeat | Short |
| Cost per row | Higher | Lower |
| Effect of a bad row | Only that request fails | The whole request fails |
| Memory per request | Small | Grows with batch size |
| Fit | Interactive use, such as a user clicking a button | Offline jobs, nightly scoring, bulk imports |
A user-facing page that needs one answer in 50 ms should call /predict. A job that scores a table of customers should call /predict/batch in chunks. A client with a large table should split it into chunks of a few hundred rows, instead of sending one request with every row. Chunks keep each request under the cap and the timeout. They also allow progress reporting and retries of only the failed chunk.
Batching also affects tail latency. While a large batch runs, the worker is busy, and other requests on that worker queue behind it. Small batches reduce this effect.
Where batching does not help
Batching only pays off when the fixed costs dominate. Check these cases:
- Validation still runs per row. Pydantic validates each
IrisFeaturesobject in Python, so a batch of 1,000 rows does 1,000 validations. For large numeric batches, consider accepting a plainlist[list[float]]and checking the shape and values with NumPy. You trade readable error messages for speed. - The model may not vectorize. If your
predictis a Python loop over rows, a bigger batch only moves the loop. Measure before assuming a gain. - The work is CPU-bound. The route is a plain
def, so FastAPI runs it in a thread pool. A longpredicton a big batch keeps one thread busy, and Python threads share the interpreter lock unless the library releases it. NumPy and scikit-learn often release it inside native code, but you should not count on that. The next chapter covers this. - Memory grows with batch size. The request body, the list of Pydantic objects, the row lists, and the model's intermediate arrays all exist at once. For heavy models, the cap should come from a memory measurement, not a guess.
Server-side micro-batching
Some clients send single rows, but the service could still group them. Micro-batching, also called dynamic batching, holds incoming single requests for a few milliseconds, combines them into one model call, and sends each caller its own result. It gives high throughput with only a small added delay.
Writing this by hand means managing queues, timeouts, futures, and error handling per caller. It is easy to get wrong. Dedicated model servers implement it with settings for maximum batch size and maximum wait time, which is one of the reasons to use them. The last chapter returns to this.
Testing the batch endpoint
Use the context-manager form of TestClient so the startup code loads the model. Test the ordering, the empty case, and the cap:
from fastapi.testclient import TestClient
from main import MAX_BATCH_SIZE, app
ROW = {"sepal_length": 5.1, "sepal_width": 3.5, "petal_length": 1.4, "petal_width": 0.2}
def test_batch_returns_one_result_per_row():
with TestClient(app) as client:
response = client.post("/predict/batch", json={"instances": [ROW, ROW, ROW]})
assert response.status_code == 200
assert len(response.json()["class_indices"]) == 3
def test_batch_rejects_empty_list():
with TestClient(app) as client:
response = client.post("/predict/batch", json={"instances": []})
assert response.status_code == 422
def test_batch_rejects_oversized_request():
with TestClient(app) as client:
response = client.post(
"/predict/batch", json={"instances": [ROW] * (MAX_BATCH_SIZE + 1)}
)
assert response.status_code == 422Choosing between the two endpoints
Keep both endpoints. Use /predict for interactive callers and /predict/batch for bulk work. Use these rules when deciding:
- If a person is waiting, use single requests, or small batches of a few rows.
- If a job processes a table, use batches in chunks sized by measurement, usually tens to hundreds of rows for a small model.
- Set a hard cap on rows and on body size.
- Measure latency at the 95th and 99th percentile, not only the average, because large batches mostly hurt the tail.
Exercise
A client needs to score 50,000 rows overnight. The service caps batches at 1,000 rows. The client first tries sending 50,000 single requests, then switches to one request holding all 50,000 rows. Neither works well. What should the client do instead, and why?
Show answer
Split the rows into chunks (for example 500 to 1,000 rows each) and send each chunk to /predict/batch. The single-request approach repeats network, parsing, and validation costs 50,000 times, so total time is long. The single giant request is rejected with 422 because it exceeds the 1,000-row cap, and even without a cap it would risk memory pressure and timeouts. Chunking keeps each request within the cap, amortizes the fixed costs, lets the client retry only a failed chunk, and keeps the service responsive to other callers.
Exercise
A batch of 200 rows contains one row with a negative petal_width. What status code does the service return, and what does the client receive for the other 199 rows?
Show answer
It returns 422, and the client receives no predictions for any row. Pydantic validates the whole request body before the route function runs, so one invalid item rejects the entire batch. The error detail points to the bad item's position in the instances list, so the client can fix that row and resend.