← Back to FastAPI, page 1

fastapi-0008 · Easy fresher

In FastAPI, when should you write an endpoint with async def and when with plain def?

Use async def when the endpoint awaits async libraries (httpx.AsyncClient, asyncpg, async SQLAlchemy). Use plain def when it calls blocking code (requests, sync database drivers, file I/O); FastAPI runs def endpoints in a thread pool so they do not block the event loop. The mistake to avoid is calling blocking code inside async def, which freezes every other request on that worker.

Full answer

FastAPI runs on an event loop: one thread that switches between tasks whenever a task is waiting (await). This is how one process serves many slow I/O requests at once.

How FastAPI treats each kind of endpoint:

  • async def: called directly on the event loop. While it awaits I/O, other requests run. While it does non-awaiting work, nothing else on that worker runs.
  • def: FastAPI sends it to a thread pool (via AnyIO, default 40 threads). Blocking calls inside only block that thread.

The rule:

  • Calling async libraries with await? Use async def.
  • Calling blocking libraries (requests, psycopg2, sync SQLAlchemy, time.sleep, heavy file reads)? Use def.
  • Not sure, or no I/O at all? Either works; def is the safer default if you might add blocking calls later.

The worst case is blocking inside async def:

python
@app.get("/report")
async def report():
    time.sleep(2)          # blocks the whole event loop for 2 seconds

Every request on that worker waits. The snippet shows three such requests taking about three times as long as three def requests.

Fixes when you must call blocking code from async code: await run_in_threadpool(func, args) (from Starlette) or await asyncio.to_thread(func, args).

CPU-heavy work (image processing, ML inference without a native async API) blocks in both styles because of the GIL and the thread pool size. Move it to a process pool, a task queue, or a separate service.

The same rules apply to dependencies: they can be async def or def and FastAPI treats them the same way.

python
import asyncio
import threading
import time

from fastapi import FastAPI
from fastapi.testclient import TestClient

app = FastAPI()


@app.get("/blocking-in-async")
async def bad():
    time.sleep(0.3)               # blocks the event loop
    return {"ok": True}


@app.get("/blocking-in-def")
def good_sync():
    time.sleep(0.3)               # runs in the thread pool
    return {"ok": True}


@app.get("/awaiting")
async def good_async():
    await asyncio.sleep(0.3)      # yields while waiting
    return {"ok": True}


def timed(path, n=3):
    with TestClient(app) as c:
        start = time.perf_counter()
        threads = [threading.Thread(target=c.get, args=(path,)) for _ in range(n)]
        [t.start() for t in threads]
        [t.join() for t in threads]
        return time.perf_counter() - start


for path in ("/blocking-in-async", "/blocking-in-def", "/awaiting"):
    took = timed(path)
    print(f"{path}: {'concurrent' if took < 0.6 else 'serialised'}")

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Timing thresholds are generous so the output is stable; three 0.3 s requests take about 0.9 s when serialised and about 0.3 s when concurrent. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): /blocking-in-async: serialised /blocking-in-def: concurrent /awaiting: concurrent

Key points

  • async def runs on the event loop; def runs in a thread pool
  • Use async def only with awaitable libraries
  • Blocking calls in async def freeze the worker
  • run_in_threadpool or asyncio.to_thread for blocking code
  • CPU-heavy work needs processes or a task queue

Common mistakes

  • Calling requests.get or time.sleep inside async def
  • Marking everything async def because it sounds faster
  • Assuming def endpoints are slow; they run concurrently in threads
  • Running CPU-heavy work in either style and starving the server

Follow-ups

  • How large is FastAPI's default thread pool and can you change it?
  • What happens to async dependencies used by a def endpoint?
  • How would you call a sync SDK from an async endpoint?

Tips

  • State the rule in one sentence, then explain the event loop
  • Describe the blocking-in-async failure concretely
  • Mention run_in_threadpool or asyncio.to_thread as the fix