Async vs sync route handlers

Difficulty: Intermediate

Question

When should a FastAPI route handler be async def and when should it be plain def? What happens if you get it wrong?

Answer

Use async def when everything slow inside the handler is awaitable, such as httpx.AsyncClient, asyncpg or SQLAlchemy's async session. Use plain def when you call blocking libraries like requests, psycopg2 or most SDKs, because FastAPI runs def handlers in a threadpool so they do not block the event loop. The worst case is a blocking call inside async def: it freezes the event loop and every other request on that worker waits.

How FastAPI runs each kind of handler

  • async def: called directly on the event loop. While it is awaiting I/O, the loop serves other requests. One worker can hold thousands of idle connections this way.
  • def: FastAPI wraps it with Starlette's run_in_threadpool, which runs it in an AnyIO worker thread. The default thread limit is 40, so roughly 40 sync handlers can block at the same time per worker before new ones queue.
  • The same rule applies to dependencies: sync dependencies go to the threadpool, async ones run on the loop.

What goes wrong

HandlerLibraryResult
async defawait httpx.AsyncClient().get()Good: non-blocking
defrequests.get()Good: blocks only a pool thread
async defrequests.get() or time.sleep()Bad: whole worker stalls
async defHeavy CPU loop (image resize, ML inference)Bad: loop starved, even though no I/O

With the bad case, a single slow third-party call (say a 3 second KYC API) makes health checks and unrelated requests on that worker hang for 3 seconds. Under load this looks like random latency spikes and timeouts.

Mixing sync and async safely

  • Inside an async def, offload blocking calls with await run_in_threadpool(func, args) (from fastapi.concurrency) or await asyncio.to_thread(func, args).
  • For CPU-heavy work, threads do not help much because of the GIL; use a ProcessPoolExecutor, a task queue like Celery, or a separate service.
  • Never call asyncio.run() inside a handler; the loop is already running.

How to decide in an interview

  1. Does the handler call anything slow? If not, either works; async def avoids a thread hop.
  2. Are all the slow calls available as async APIs? Use async def and await them.
  3. Is any slow call blocking only? Use def, or offload it explicitly.
  4. Is the work CPU-bound? Move it out of the request path.

Real-world notes

Async shines for I/O fan-out, such as calling payment, inventory and pricing services concurrently with asyncio.gather. It does not make a single database query faster. Many production teams run sync SQLAlchemy with def handlers successfully; the important thing is consistency and never blocking the loop.

async def vs def in FastAPI. Where your handler runs decides which libraries are safe inside it.
async defdef
Runs onThe event loopA threadpool worker thread
Safe librarieshttpx async, asyncpg, aioredisrequests, psycopg2, boto3
Blocking call effectStalls every request on the workerOccupies one pool thread
Concurrency limitThousands of awaiting tasksAbout 40 threads by default

Code examples

Right and wrong ways to call external APIs

import asyncio
import time

import httpx
import requests
from fastapi import FastAPI
from fastapi.concurrency import run_in_threadpool

app = FastAPI()

@app.get("/good-async")
async def good_async():
    async with httpx.AsyncClient(timeout=5) as client:
        r = await client.get("https://api.example.com/data")   # yields to the loop
    return r.json()

@app.get("/good-sync")
def good_sync():
    r = requests.get("https://api.example.com/data", timeout=5)  # runs in threadpool
    return r.json()

@app.get("/bad")
async def bad():
    time.sleep(3)              # BLOCKS the event loop for every request
    return {"ok": True}

@app.get("/offloaded")
async def offloaded():
    await run_in_threadpool(time.sleep, 3)   # blocking work moved to a thread
    return {"ok": True}

@app.get("/fan-out")
async def fan_out():
    async with httpx.AsyncClient(timeout=5) as client:
        pay, stock = await asyncio.gather(
            client.get("https://payments.internal/status"),
            client.get("https://inventory.internal/stock"),
        )
    return {"payments": pay.status_code, "inventory": stock.status_code}

The /bad route makes all requests on that worker wait three seconds. The fan-out route shows the real win of async: concurrent I/O in one request.

Key points

  • async def runs on the event loop; def runs in a threadpool
  • Blocking code inside async def stalls the whole worker
  • Default AnyIO threadpool limit is 40 threads per process
  • Offload with run_in_threadpool or asyncio.to_thread; CPU work needs processes or a queue
  • Async helps concurrency, not the speed of an individual call

Common follow-up questions

  • How would you detect that something is blocking the event loop in production?
  • Why do threads not help much with CPU-bound Python code?
  • How does the GIL affect FastAPI with multiple Uvicorn workers?
  • How do you call three downstream services concurrently from one endpoint?

Interview tips

  • Explain the threadpool behaviour for def; many candidates think def handlers are simply 'slow'
  • Give a concrete failure story, like a blocking KYC call freezing health checks
  • Separate I/O-bound from CPU-bound work clearly

Concepts covered

async def vs def, event loop, threadpool, blocking I/O, run_in_threadpool

More FastAPI Interview questions