Sub topic 11
Concurrency and blocking work
This chapter assumes you have the service from the earlier chapters: a FastAPI main.py that loads the model in lifespan and serves /predict. It also assumes you know basic Python async/await syntax. You will learn why one slow prediction can freeze an entire service, and how to prevent it.
How FastAPI runs your code
FastAPI runs on an asyncio event loop, a single thread that switches between tasks whenever one of them waits. The switching only works if tasks wait cooperatively with await. A task that does CPU work or calls a blocking function never gives control back, so every other request stalls until it finishes.
FastAPI handles the two kinds of endpoint functions differently:
- An
async defendpoint runs directly on the event loop. - A plain
defendpoint runs in a threadpool, a set of worker threads. By default this pool allows about 40 threads at once.
model.predict(...) is a blocking, CPU-bound call. It has no await inside it. If you call it from an async def endpoint, the event loop is stuck for the whole prediction.
The /predict endpoint you wrote earlier is a plain def, so it already runs in the threadpool. That is why it behaves well. The usual bug is changing it to async def because "async is faster."
Seeing the problem
This small app uses time.sleep to stand in for a slow model call.
import time
from fastapi import FastAPI
app = FastAPI()
@app.get("/slow-async")
async def slow_async():
time.sleep(2) # blocks the event loop
return {"ok": True}
@app.get("/slow-sync")
def slow_sync():
time.sleep(2) # blocks one threadpool thread only
return {"ok": True}
@app.get("/ping")
async def ping():
return {"pong": True}Save it as demo.py, start it with uvicorn demo:app --port 8001, and try both cases:
# Case 1: ping while /slow-async is running
curl -s localhost:8001/slow-async &
sleep 0.2
time curl -s localhost:8001/ping
wait
# Case 2: ping while /slow-sync is running
curl -s localhost:8001/slow-sync &
sleep 0.2
time curl -s localhost:8001/ping
waitIn case 1, /ping takes about 2 seconds because the event loop is blocked. In case 2, it returns almost immediately. A health check behaves like /ping. If predictions block the loop, the orchestrator's health probe times out and may restart a service that is only busy.
Option 1: keep the endpoint synchronous
For a scikit-learn model, the simplest correct design is a plain def endpoint, as in the earlier chapters. FastAPI moves it to a thread, and no extra code is needed. Choose this unless you have a reason not to.
Option 2: async endpoint that offloads the model call
Sometimes the endpoint must be async def, for example because it awaits a feature store or database before predicting. In that case, move only the blocking call to a thread:
import asyncio
MAX_IN_FLIGHT = 8
gate = asyncio.Semaphore(MAX_IN_FLIGHT)
@app.post("/predict", response_model=Prediction)
async def predict(features: IrisFeatures):
row = [[
features.sepal_length,
features.sepal_width,
features.petal_length,
features.petal_width,
]]
async with gate:
prediction = await asyncio.to_thread(models["iris"].predict, row)
return Prediction(class_index=int(prediction[0]))The semaphore caps how many predictions run at once. Without it, a traffic spike can start up to 40 threads that all compete for the same CPU cores. Each one then runs slower, and latency grows for everyone. Requests beyond the cap wait on the semaphore, which costs almost nothing.
Threads and the GIL
Python's Global Interpreter Lock (GIL) lets only one thread run Python bytecode at a time. Threads still help here because NumPy and scikit-learn's compiled code often release the GIL during heavy computation. That release is not guaranteed for every model or library. A pure-Python preprocessing step, such as a loop over rows, holds the GIL. Several of those running in threads execute one after another.
Two further cautions:
- Thread safety. Calling
predicton a fitted scikit-learn estimator from many threads is generally safe because prediction only reads the model. This is not a documented guarantee for every estimator. Check any model or library that keeps internal state, such as caches or GPU handles. - Oversubscription. If the model was created with
n_jobs=-1, eachpredictcall can start its own threads. Eight concurrent requests on an 8-core machine then produce dozens of busy threads. Setn_jobs=1for serving, or lowerMAX_IN_FLIGHT. The same problem occurs with multithreaded math libraries. SettingOMP_NUM_THREADS=1is a common remedy.
Option 3: process pool for heavy CPU work
When prediction is slow and holds the GIL, use separate processes. Each process has its own interpreter and its own copy of the model. Load the model once per process with an initializer:
import asyncio
from concurrent.futures import ProcessPoolExecutor
from contextlib import asynccontextmanager
import joblib
from fastapi import FastAPI
_worker_model = None
def _init_worker():
global _worker_model
_worker_model = joblib.load("model.joblib")
def _predict_rows(rows):
return [int(p) for p in _worker_model.predict(rows)]
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.pool = ProcessPoolExecutor(max_workers=2, initializer=_init_worker)
yield
app.state.pool.shutdown(wait=True)
app = FastAPI(lifespan=lifespan)
@app.post("/predict/heavy")
async def predict_heavy(rows: list[list[float]]):
loop = asyncio.get_running_loop()
result = await loop.run_in_executor(app.state.pool, _predict_rows, rows)
return {"class_indices": result}The function passed to the pool must be defined at module level so it can be pickled. Inputs and outputs are pickled too, so each call pays a copying cost. For the small iris model, that cost is larger than the prediction itself, so a process pool would slow it down. It pays off only when a single call takes tens of milliseconds or more.
Option 4: more server processes
Uvicorn can start several worker processes, each running a full copy of the app:
uvicorn main:app --workers 4 --port 8000Each worker runs lifespan, so each loads its own copy of the model. Memory use is roughly the model size times the worker count. A 500 MB model with 4 workers needs about 2 GB. This option also does not work with --reload. Matching workers to CPU cores is a reasonable starting point, and the next chapters on scaling build on this.
Choosing an approach
| Situation | Approach | Main cost |
|---|---|---|
| Fast model, simple endpoint | Plain `def` endpoint | None to speak of |
| `async def` needed for other awaits | `asyncio.to_thread` plus a semaphore | Threads share the GIL |
| Slow, GIL-holding Python code | `ProcessPoolExecutor` | Pickling and extra memory |
| Need to use all cores | `--workers N` | N copies of the model |
Limits and failure modes
- Queueing hides overload. A threadpool or semaphore holds extra requests without rejecting them, so latency climbs instead of errors appearing. Pair a concurrency cap with a client timeout, and return HTTP 503 when the wait is too long.
- Cancelled requests keep running. If a client disconnects, a prediction already running in a thread or process is not interrupted. It finishes and its result is discarded.
- Shared mutable state. The
modelsdict is only read after startup, which is safe. Do not add per-request counters or caches to shared objects without a lock. - Measure before tuning. Use a load tool such as
hey,wrk, or Locust, and compare p50 and p99 latency. Do not guess thread or worker counts.
Exercise
A teammate changes /predict from def to async def "to make it faster" and leaves the body unchanged, including the call to models["iris"].predict(row). Under load, /health starts timing out. Explain why, and give two different fixes.
Show answer
An async def endpoint runs on the event loop, and predict is blocking CPU work with no await. While one prediction runs, the loop cannot serve any other request, including /health, so requests queue and the health probe times out. Fix 1: change the endpoint back to a plain def, so FastAPI runs it in the threadpool. Fix 2: keep async def and call await asyncio.to_thread(models["iris"].predict, row), optionally behind an asyncio.Semaphore to cap concurrent predictions. Running several uvicorn --workers or using a process pool would also reduce the problem, but they do not fix the blocking call itself.
Exercise
A service runs uvicorn main:app --workers 4, and each worker loads a 750 MB model in lifespan. Roughly how much memory do the model copies use, and why?
Show answer
About 3 GB (4 × 750 MB). Each worker is a separate process with its own memory, and each runs the lifespan startup code, so each loads its own copy of the model.