← Back to FastAPI, page 2

fastapi-0035 · Hard senior

What are the common async pitfalls in FastAPI, and how do you handle blocking or CPU-heavy code safely?

The main pitfall is blocking the event loop: calling synchronous I/O (requests, sync database drivers, time.sleep, large file reads) or CPU-heavy code inside async def, which stalls every request on that worker. Offload blocking I/O with run_in_threadpool or asyncio.to_thread, remember the default thread pool has about 40 slots shared by all def endpoints and dependencies, and send CPU-heavy work to a process pool or task queue. Also bound concurrency for outbound calls and never create unbounded background tasks.

Full answer

An async worker has one event loop thread. Anything that runs without awaiting holds that thread.

Pitfalls and fixes:

  1. Blocking I/O in async def. requests.get(), psycopg2, sync SQLAlchemy, boto3, open().read() on big files. Fix: use async libraries (httpx.AsyncClient, asyncpg, async SQLAlchemy, aiofiles), or make the endpoint def, or wrap calls with await run_in_threadpool(fn, *args) / await asyncio.to_thread(fn, *args).

  2. CPU-heavy work. JSON parsing of huge payloads, image resizing, PDF generation, ML inference in pure Python. Threads do not help much because of the GIL. Fix: loop.run_in_executor(ProcessPoolExecutor(), fn, ...), a task queue, or a separate service. (Free-threaded CPython builds from 3.13/3.14 change this picture, but most deployments still run with the GIL.)

  3. Thread pool exhaustion. def endpoints, def dependencies and run_in_threadpool share AnyIO's default limiter of 40 threads per process. If 40 requests block on a slow sync call, the 41st waits even for a trivial def endpoint. Fix: avoid long blocking calls, use async drivers, or raise the limit at startup (anyio.to_thread.current_default_thread_limiter().total_tokens = 100) after measuring.

  4. Unbounded concurrency. asyncio.gather(*[call(x) for x in 10_000 items]) opens 10,000 connections. Fix: asyncio.Semaphore(20) or anyio task groups with limits.

  5. Fire-and-forget tasks. asyncio.create_task() without keeping a reference can be garbage collected, and exceptions vanish. Fix: keep references, use task groups, or use BackgroundTasks / a queue.

  6. Async libraries used without timeouts. One stuck upstream can hold coroutines forever. Fix: always set timeouts.

How to detect blocking: run with PYTHONASYNCIODEBUG=1 (asyncio logs callbacks slower than 100 ms), watch event loop lag metrics, or profile with py-spy dump to see what the loop thread is doing.

python
import asyncio
import threading
import time

import anyio
from fastapi import FastAPI
from fastapi.concurrency import run_in_threadpool
from fastapi.testclient import TestClient

app = FastAPI()


def legacy_sms_sdk(number: str) -> str:   # a sync SDK we cannot change
    time.sleep(0.3)
    return f"sent to {number}"


@app.post("/notify-blocking")
async def notify_blocking():
    return {"result": legacy_sms_sdk("98xxxxxx01")}            # blocks the event loop


@app.post("/notify-threadpool")
async def notify_threadpool():
    return {"result": await run_in_threadpool(legacy_sms_sdk, "98xxxxxx01")}


limit = asyncio.Semaphore(3)
active = {"now": 0, "peak": 0}


async def call_upstream(i: int) -> int:
    async with limit:
        active["now"] += 1
        active["peak"] = max(active["peak"], active["now"])
        await asyncio.sleep(0.01)
        active["now"] -= 1
        return i


@app.post("/fan-out")
async def fan_out():
    results = await asyncio.gather(*(call_upstream(i) for i in range(20)))
    return {"count": len(results), "peak_concurrency": active["peak"]}


@app.get("/thread-limit")
async def thread_limit():
    return {"default_thread_limit": anyio.to_thread.current_default_thread_limiter().total_tokens}


def run_parallel(client, path, n=3):
    start = time.perf_counter()
    threads = [threading.Thread(target=client.post, args=(path,)) for _ in range(n)]
    [t.start() for t in threads]
    [t.join() for t in threads]
    return "concurrent" if time.perf_counter() - start < 0.6 else "serialised"


with TestClient(app) as c:
    print("blocking in async def:", run_parallel(c, "/notify-blocking"))
    print("run_in_threadpool:", run_parallel(c, "/notify-threadpool"))
    print(c.post("/fan-out").json())
    print(c.get("/thread-limit").json())

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. The 40-slot limit printed at the end is AnyIO's default thread limiter, which FastAPI uses for sync code. 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 def: serialised run_in_threadpool: concurrent {'count': 20, 'peak_concurrency': 3} {'default_thread_limit': 40}

Key points

  • Never block the event loop in async def
  • run_in_threadpool or asyncio.to_thread for blocking I/O
  • Process pools or queues for CPU-heavy work
  • Default thread pool is about 40 slots shared by all sync code
  • Bound concurrency with semaphores; set timeouts

Common mistakes

  • Calling sync SDKs or requests inside async def
  • Using threads for CPU-heavy Python code and expecting a speedup
  • Ignoring the shared 40-thread limit when many def endpoints block
  • Launching thousands of concurrent outbound calls without a semaphore
  • Creating tasks with asyncio.create_task and dropping the reference

Follow-ups

  • How would you find out which code is blocking the event loop in production?
  • When would you raise the thread pool limit, and what are the risks?
  • How would you run a CPU-heavy model inside a FastAPI service?

Tips

  • Name several pitfalls, not only blocking I/O
  • Mention the shared thread pool and its default size
  • Give detection techniques, not only fixes