Async Python and blocking work in FastAPI
Choose between async routes, sync routes, thread pools and workers for a given kind of work.
By Invicly Tech, , in FastAPI with Python for AI Backends. About 13 minutes to read.
In short
FastAPI runs async def routes on one event loop, which handles many requests at once as long as each one awaits its slow network calls. Plain def routes run in a thread pool so blocking code does not freeze the loop. CPU-heavy work belongs in separate processes or worker services, and limits on concurrency protect the service when traffic outruns capacity.
Think of it like this: The event loop is one waiter serving many tables: fine while each kitchen order cooks on its own, but if the waiter stops to cook a dish himself, every table waits.
Explained simply
A web service spends most of its time waiting: for the database, for another API, for a model to answer. Async Python lets one process use that waiting time to work on other requests instead of sitting idle.
In FastAPI, a route written with async def runs on the event loop. The event loop is a scheduler. Every time your code says await, for example await client.get(url), the loop parks that request and moves on to another one until the answer arrives.
The catch is that the loop can only switch at an await. If your async code calls something slow that does not await, such as time.sleep or the requests library, the whole loop stops. Every other user waits too. This is called blocking the event loop.
If you must use a blocking library, write the route with plain def. FastAPI then runs it in a pool of threads, so the loop stays free. For heavy calculation, such as parsing big PDFs, use separate processes or a background worker.
Even async code has limits. If too many requests arrive at once, you should queue them, slow them down or politely refuse some. That is called backpressure, and it keeps the service healthy instead of letting it fall over.
Press Play on a diagram to walk through it one step at a time.
- Runs on the event loop
- Use for awaited network I/O
- httpx.AsyncClient, async DB drivers
- One blocking call stalls everyone
- Runs in a thread pool
- Use for blocking libraries
- Thread pool has about 40 slots by default
- Fine for short blocking I/O
- Separate process or service
- Use for CPU-heavy work
- Parsing PDFs, embeddings on CPU
- Job queue gives retries and limits
- Request A to Model API: A awaits a slow model call1A awaits a slow model call
- Request A to Event loop: A yields control at await2A yields control at await
- Event loop to Request B: Loop runs B while A waits3Loop runs B while A waits
- Request B to Event loop: B finishes its quick work and returns4B finishes its quick work and returns
- Model API to Event loop: Model answer arrives for A5Model answer arrives for A
- Event loop to Request A: Loop resumes A after its await6Loop resumes A after its await
In depth
What await really does
An async def function returns a coroutine, an object that can pause and resume. When it reaches await on a network call, it hands control back to the event loop and says wake me when this socket has data. The loop then runs any other task that is ready. When the data arrives, the loop resumes the first task right after the await.
This is cooperative multitasking. No task is interrupted; each one must give control back by awaiting. That is efficient, since thousands of requests can wait on one thread, but it means one task that never awaits can starve all the rest. It also means await only helps when the thing you await is real asynchronous I/O. Wrapping a slow synchronous function in async def does not make it non-blocking.
- 1Run a ready task
Execute until it reaches an await
- 2Park the task
Register the socket or timer it waits on
- 3Pick the next task
Run any other task that is ready
- 4Check I/O
Ask the OS which sockets have data
- 5Wake waiting tasks
Mark them ready to resume after await
- Back to step 1
How FastAPI decides where to run your code
FastAPI looks at how each route and dependency is declared. async def functions are awaited directly on the event loop. Plain def functions are sent to a thread pool, managed by AnyIO underneath Starlette, so they can block without stopping the loop. By default that pool allows about 40 threads at once per process; extra sync calls wait for a free slot.
Inside an async route you sometimes need one blocking call, for example a library with no async version. Wrap it with await asyncio.to_thread(func, arg) or Starlette's run_in_threadpool so it runs in a thread while the loop keeps going. A good rule: use async def when every slow call inside can be awaited; use def when you rely on blocking libraries; never mix blocking calls into async def.
- async def: runs on the loop, must await I/O
- def: runs in the thread pool
- Same rules apply to dependencies
- asyncio.to_thread offloads one blocking call
Spotting blocking calls
Common offenders inside async def are time.sleep, the requests library, synchronous database drivers such as psycopg2, reading large files with open, and big loops doing calculation or JSON parsing. The symptom is distinctive: one slow request makes unrelated fast requests slow too, and latency rises in steps under load.
To find them, run the app with asyncio debug mode. Setting the environment variable PYTHONASYNCIODEBUG=1 makes asyncio log a warning whenever a single step holds the loop longer than 100 milliseconds by default. Another simple test: call a slow route and a fast health route at the same time. If health waits for the slow one, something is blocking. Swap in async libraries such as httpx.AsyncClient, asyncpg or psycopg 3 async, and asyncio.sleep, or move the call to a thread.
CPU-bound work and dedicated workers
Threads help with blocking I/O because the waiting thread releases the GIL, the global interpreter lock that lets only one thread run Python bytecode at a time in the standard build. For pure calculation, threads do not add speed: they take turns on one core. Python 3.13 added an optional free-threaded build, but most deployments still use the standard build.
For short CPU bursts, use a ProcessPoolExecutor through loop.run_in_executor, which runs the function in another process with its own interpreter. For long or heavy jobs, such as extracting text from hundreds of PDFs or computing embeddings on a CPU, do not do the work in the API at all. Store a job, return 202 Accepted, and let a separate worker process it from a queue. That keeps API latency predictable and lets you scale workers independently.
- Step 1Mostly waiting on I/O?
Yes with an async library: await it in async def
- Step 2Blocking library only?
Use def or asyncio.to_thread
- Step 3Short CPU burst?
ProcessPoolExecutor via run_in_executor
- Step 4Long or heavy job?
Queue it; a separate worker processes it
Backpressure: saying not now
Async makes it cheap to accept requests, so without limits a service happily starts more work than its dependencies can handle. The database pool runs dry, the model provider returns 429, memory grows and everything times out together. Backpressure means limiting work at each layer and telling callers when you are full.
Useful tools: an asyncio.Semaphore around expensive calls such as model requests; connection limits on your HTTP client with httpx.Limits; a bounded database pool; Uvicorn's --limit-concurrency, which answers 503 once a set number of connections or tasks is reached; and per-user quotas that return 429 with a Retry-After header. Pick limits from measured capacity, not guesses, and prefer failing fast with a clear error over making users wait for a timeout.
- Semaphore around model and upstream calls
- httpx.Limits on outgoing connections
- Bounded DB connection pool
- uvicorn --limit-concurrency returns 503 when full
- 429 with Retry-After for per-user quotas
Learn it in 5 short steps
About 35m each. Track them with a timer in your plan.
- 1Await network I/O in async routes~35m
- 2Know when FastAPI uses a thread pool~35m
- 3Spot blocking calls in async code~35m
- 4Move CPU-bound work to workers~35m
- 5Apply backpressure with limits~35m
Key points
- await gives control back to the event loop while waiting for I/O, so other requests can progress.
- A blocking call such as time.sleep or requests.get inside async def freezes every request on that worker.
- FastAPI runs def routes and def dependencies in a thread pool automatically.
- Threads do not speed up CPU-bound Python because of the GIL; use processes or a worker queue.
- Backpressure means saying no or waiting when busy: semaphores, connection limits and 503 or 429 responses.
Key terms
Tap a card to flip it. 0/6 known
Examples
import asyncio, httpx
from fastapi import FastAPI
app = FastAPI()
limit = asyncio.Semaphore(10) # at most 10 upstream calls at once
@app.get("/v1/status")
async def status() -> dict:
async with limit:
async with httpx.AsyncClient(timeout=5.0) as client:
r = await client.get("https://example.com/")
return {"upstream": r.status_code}Awaited I/O plus a semaphore as simple backpressure. Later modules reuse one shared client.
Measure the cost of a blocking call
Run this app, then fire five requests at /bad at once and time them; repeat for /good. With time.sleep inside async def the requests run one after another, taking about 5 seconds in total. With asyncio.sleep they overlap and finish in about 1 second. The same evidence appears for any blocking call. Expected output from the timing loop: roughly 5 s for bad and 1 s for good.
import asyncio, time
from fastapi import FastAPI
app = FastAPI()
@app.get("/bad")
async def bad() -> dict:
time.sleep(1) # blocks the loop
return {"ok": True}
@app.get("/good")
async def good() -> dict:
await asyncio.sleep(1) # yields to the loop
return {"ok": True}
# time (for i in 1 2 3 4 5; do curl -s localhost:8000/bad & done; wait)Offload CPU work to a process pool
Hashing many times stands in for any heavy calculation. Running it in a ProcessPoolExecutor keeps the event loop free, so /health still answers instantly while fingerprints are computed. Two processes cap how much CPU this route can take. For long-running jobs you would go further and use a queue and worker, which the ingestion module builds.
import asyncio, hashlib
from concurrent.futures import ProcessPoolExecutor
from fastapi import FastAPI
app = FastAPI()
pool = ProcessPoolExecutor(max_workers=2)
def heavy_hash(data: bytes) -> str:
for _ in range(200_000):
data = hashlib.sha256(data).digest()
return data.hex()
@app.post("/v1/fingerprint")
async def fingerprint(text: str) -> dict:
loop = asyncio.get_running_loop()
return {"digest": await loop.run_in_executor(pool, heavy_hash, text.encode())}Quick reference
- async def + await for network I/O; def for blocking libraries.
- FastAPI runs def routes and def dependencies in a thread pool (about 40 threads by default).
- Never call time.sleep or requests inside async def; use asyncio.sleep and httpx.AsyncClient.
- await asyncio.to_thread(fn, arg) runs one blocking call off the loop.
- CPU-heavy work: ProcessPoolExecutor or a separate worker, not threads.
- PYTHONASYNCIODEBUG=1 logs steps that hold the loop over 100 ms.
- Backpressure: Semaphore, httpx.Limits, bounded pools, 503 or 429 with Retry-After.
Common mistakes
- Calling requests.get or time.sleep inside async def; use httpx.AsyncClient and asyncio.sleep, or make the route def.
- Making everything async def by habit while calling only synchronous libraries.
- Running CPU-heavy parsing in a route, which hurts latency for every other user.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Find the blocking calls in this route and rewrite it so it no longer blocks: async def route that calls time.sleep(0.5) then requests.get("https://example.com").
- Exercise 2medium
A route must call legacy_report(customer_id), a slow blocking function, and also await an async lookup. Keep the route async and run the blocking part off the loop.
- Exercise 3hard
Allow at most 5 concurrent model calls. If a request cannot get a slot within 0.5 seconds, return 503 with a Retry-After header of 1 instead of waiting.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Should every FastAPI route be async def?
- No. Use async def when everything slow inside it can be awaited. If you call blocking libraries, plain def is safer because FastAPI runs it in a thread pool.
- Is async Python faster than sync Python?
- Not per request. Async lets one process handle many waiting requests at once, which raises throughput for I/O-heavy services. It does nothing for CPU-heavy work.
- How many Uvicorn workers should I run?
- Each worker is a separate process with its own event loop. A common start is one per CPU core, then adjust from load tests; in Kubernetes or Cloud Run you often run one worker per container and scale containers instead.
- What is the difference between 429 and 503?
- 429 Too Many Requests means this caller has gone over its limit. 503 Service Unavailable means the service as a whole is overloaded or down right now.