Sub topic 11
Concurrency and blocking work
This chapter assumes you have the main.py service from the earlier chapters, with /predict and a model loaded at startup. It explains how FastAPI runs your endpoint code and how a slow prediction can stall every other request.
Two ways FastAPI runs your code
FastAPI handles requests in one of two ways, depending on how you define the endpoint:
defendpoints run in a pool of worker threads. While one thread waits on a prediction, other requests run on other threads.async defendpoints run directly on the event loop, a single thread that switches between requests. It switches only when your code reaches anawait.
The /predict endpoint you wrote uses plain def. That is why it works well: model.predict is ordinary blocking code, and the threadpool keeps it off the event loop.
The common error
A frequent mistake is to add async to an endpoint without changing its body:
@app.post("/predict", response_model=Prediction)
async def predict(features: IrisFeatures):
row = [[
features.sepal_length,
features.sepal_width,
features.petal_length,
features.petal_width,
]]
prediction = models["iris"].predict(row)[0] # blocks the event loop
return Prediction(class_index=int(prediction))Nothing in this function awaits, so the event loop is frozen until predict returns. Every other request waits, including /health. With a 5 ms model you will not notice. With a 500 ms model, a health check can time out and an orchestrator may restart a healthy container.
Fixing it
You have two options. The simplest is to keep def, as in the earlier chapters. If the endpoint must be async, for example because it also awaits a database call, move only the model call into a thread:
from fastapi.concurrency import run_in_threadpool
@app.post("/predict", response_model=Prediction)
async def predict(features: IrisFeatures):
row = [[
features.sepal_length,
features.sepal_width,
features.petal_length,
features.petal_width,
]]
prediction = await run_in_threadpool(models["iris"].predict, row)
return Prediction(class_index=int(prediction[0]))Threads have limits
The threadpool stops blocking, but it does not add CPU capacity. Python's global interpreter lock (GIL) lets only one thread run Python bytecode at a time. NumPy and scikit-learn release the GIL in many compiled routines, so threads often do overlap. Pure-Python preprocessing does not overlap. Also, the default pool holds about 40 threads, so a burst of slow predictions queues behind them.
For more parallelism, run several processes:
uvicorn main:app --port 8000 --workers 4Each worker is a separate process with its own copy of the model, so memory use grows with the worker count. A good starting point is one worker per CPU core. Check that the model's own thread use (for example n_jobs) does not oversubscribe the cores.
Quick comparison
| Approach | Best for | Cost |
|---|---|---|
| `def` endpoint | Most model APIs | Limited by thread count and GIL |
| `async def` plus `run_in_threadpool` | Endpoints that also await I/O | Slightly more code |
| Multiple Uvicorn workers | CPU-heavy models | Model memory per process |
Exercise
Your /predict endpoint is declared with async def and calls model.predict directly. Under load, /health starts timing out even though CPU use is low. Why, and what are two fixes?
Show answer
The blocking predict call holds the event loop, so no other request, including /health, can run until it returns. Fixes: change the endpoint to plain def so FastAPI runs it in a worker thread, or keep async def and wrap the call with await run_in_threadpool(models["iris"].predict, row).