All articles
FastAPIPythonasyncioPerformance

Why One Slow FastAPI Endpoint Freezes All the Others

Blocking calls inside async def endpoints stall FastAPI's event loop. How to spot them and fix them with threads, async libraries or processes.

Tushar Pachouri14 min read

Your FastAPI app is snappy when you click around alone. Put real traffic on it and everything slows down at once: fast endpoints start taking seconds, /health times out, and the orchestrator restarts a container that isn't even busy on CPU. The cause is almost always the same: a synchronous, blocking call inside an async def function, which stops the event loop for every request on that worker.

This post shows how to reproduce the problem, why FastAPI behaves this way, and the fixes that work for each kind of blocking code.

TL;DR

  • An async def endpoint runs on the event loop. Any blocking call inside it (time.sleep, requests, psycopg2, sync SQLAlchemy, pymongo, file I/O, heavy CPU work) freezes all requests on that worker.
  • A plain def endpoint runs in a threadpool, so blocking code there is fine. If your code is sync, just use def.
  • If you need async def, offload blocking calls with await asyncio.to_thread(...) or use async libraries (httpx.AsyncClient, asyncpg, SQLAlchemy's async engine, an async Mongo client).
  • CPU-bound work belongs in a ProcessPoolExecutor or a task queue, not a thread.
  • Find the culprit with asyncio debug mode, a loop-lag monitor, or py-spy dump.

The symptom

There's usually no error message, which is what makes this hard to spot. What you see instead:

  • Latency for every endpoint rises together under load, including trivial ones.
  • One slow endpoint (a report, an external API call, an upload) makes unrelated requests wait until it finishes.
  • /health or a Kubernetes liveness probe times out and the pod gets restarted.
  • CPU usage stays low while requests pile up.
  • Under Gunicorn with Uvicorn workers, a long enough block can produce [CRITICAL] WORKER TIMEOUT and a killed worker, because the worker can't report its heartbeat while the loop is stuck.

If you turn on asyncio debug mode (covered below), you'll see warnings like this one (paths trimmed):

Text
Executing <Task pending name='Task-7' coro=<RequestResponseCycle.run_asgi() running at uvicorn/protocols/http/httptools_impl.py> created at asyncio/tasks.py> took 2.004 seconds

That line means a single step of a single task held the loop for two seconds. Nothing else on that worker ran during that time.

Why it happens

One event loop per worker

Uvicorn runs one asyncio event loop per worker process. The loop is a single thread that switches between tasks only at await points. When a coroutine awaits I/O, the loop parks it and runs something else. When a coroutine calls a function that blocks without awaiting, the loop can't switch. It sits inside that call until it returns.

time.sleep(2) and await asyncio.sleep(2) both take two seconds, but the first one takes those two seconds away from every other request.

One worker's event loop: blocking calls run back to back, awaits overlap.

How FastAPI runs def vs async def

FastAPI treats the two kinds of path operation differently:

  • async def endpoints are awaited directly on the event loop. FastAPI assumes you know what you're doing and only use non-blocking code inside.
  • def endpoints are run with Starlette's run_in_threadpool, which hands them to a worker thread through AnyIO. The loop stays free while the thread blocks.

The same rule applies to dependencies: def dependencies go to the threadpool, async def dependencies run on the loop. Middleware written with @app.middleware("http") is always async and always runs on the loop.

So the dangerous combination is specifically blocking code inside async def. Ironically, adding async to a sync endpoint "to make it faster" is what causes the problem.

Request FastAPI checks the def async def def EVENT LOOP THREAD, ONE PER WORKER async def endpoints and dependencies @app.middleware("http") functions A blocking call here stalls every request THREADPOOL, 40 THREADS BY DEFAULT def endpoints and def dependencies run via Starlette's run_in_threadpool Blocking is fine: the loop stays free
FastAPI awaits async def code on the event loop and sends def code to a threadpool.

Common blocking calls

Blocking callNon-blocking alternative
time.sleep()await asyncio.sleep()
requests, urllibhttpx.AsyncClient, aiohttp
psycopg2, sync SQLAlchemy Sessionasyncpg, psycopg 3 async, SQLAlchemy AsyncSession
pymongo.MongoClientPyMongo's AsyncMongoClient, Motor
redis.Redisredis.asyncio.Redis
open().read() on large filesasyncio.to_thread, aiofiles
boto3 and most vendor SDKsasyncio.to_thread or the SDK's async client
pandas, image processing, PDF generationProcessPoolExecutor or a task queue
bcrypt or argon2 password hashingasyncio.to_thread

Reproduce it

Seeing the stall yourself makes the rest of this post click. Save this as main.py:

Python
import asyncio
import time

from fastapi import FastAPI

app = FastAPI()


@app.get("/blocking")
async def blocking() -> dict[str, str]:
    time.sleep(2)  # blocks the event loop
    return {"mode": "blocking"}


@app.get("/async")
async def non_blocking() -> dict[str, str]:
    await asyncio.sleep(2)  # yields to the loop while waiting
    return {"mode": "async"}


@app.get("/threadpool")
def threadpool() -> dict[str, str]:
    time.sleep(2)  # plain def: runs in a worker thread
    return {"mode": "threadpool"}


@app.get("/health")
async def health() -> dict[str, str]:
    return {"status": "ok"}

And this as bench.py. It fires five concurrent requests at one endpoint, then checks how long /health takes while they're in flight:

Python
import asyncio
import sys
import time

import httpx

BASE_URL = "http://127.0.0.1:8000"


async def timed_get(client: httpx.AsyncClient, path: str) -> float:
    start = time.perf_counter()
    response = await client.get(path)
    response.raise_for_status()
    return time.perf_counter() - start


async def main(path: str, concurrency: int = 5) -> None:
    async with httpx.AsyncClient(base_url=BASE_URL, timeout=60) as client:
        start = time.perf_counter()
        slow = [asyncio.create_task(timed_get(client, path)) for _ in range(concurrency)]
        await asyncio.sleep(0.1)  # let the slow requests reach the server first
        health = await timed_get(client, "/health")
        await asyncio.gather(*slow)
        total = time.perf_counter() - start
    print(f"{path:<12} {concurrency} requests: {total:4.1f}s total, /health took {health:.2f}s")


if __name__ == "__main__":
    asyncio.run(main(sys.argv[1] if len(sys.argv) > 1 else "/blocking"))

Run the server with a single worker, then the benchmark against each endpoint:

Terminal
pip install fastapi uvicorn httpx
uvicorn main:app --port 8000
# in a second terminal
python bench.py /blocking
python bench.py /async
python bench.py /threadpool

What to expect:

EndpointTotal for 5 requests/health while they run
/blockingabout 10 s (one at a time)several seconds
/asyncabout 2 smilliseconds
/threadpoolabout 2 smilliseconds

The /blocking requests run strictly one after another, and /health has to wait its turn behind them. That's the production symptom in miniature.

TOTAL TIME FOR 5 CONCURRENT REQUESTS 0 s2 s4 s6 s8 s10 s /blocking /health: seconds about 10 s /async /health: milliseconds about 2 s /threadpool /health: milliseconds about 2 s
Five two-second requests: /blocking runs them in sequence, the other two overlap them.

The same effect in plain asyncio

If you don't want to install anything, this script shows the same thing with only the standard library. A heartbeat task tries to tick every 100 ms while five fake "requests" run:

Python
import asyncio
import time


async def blocking_handler() -> None:
    time.sleep(1)  # blocks the whole event loop


async def async_handler() -> None:
    await asyncio.sleep(1)  # yields to the loop while waiting


async def offloaded_handler() -> None:
    await asyncio.to_thread(time.sleep, 1)  # runs in a worker thread


async def heartbeat(stop: asyncio.Event) -> int:
    beats = 0
    while not stop.is_set():
        await asyncio.sleep(0.1)
        beats += 1
    return beats


async def run(name: str, handler) -> None:
    stop = asyncio.Event()
    hb = asyncio.create_task(heartbeat(stop))
    start = time.perf_counter()
    await asyncio.gather(*(handler() for _ in range(5)))
    elapsed = time.perf_counter() - start
    stop.set()
    print(f"{name:<10} 5 handlers: {elapsed:4.1f}s, heartbeats: {await hb}")


async def main() -> None:
    await run("blocking", blocking_handler)
    await run("async", async_handler)
    await run("to_thread", offloaded_handler)


asyncio.run(main())
Text
blocking   5 handlers:  5.0s, heartbeats: 1
async      5 handlers:  1.0s, heartbeats: 10
to_thread  5 handlers:  1.0s, heartbeats: 10

In the blocking case the heartbeat barely runs at all. That heartbeat is your /health endpoint.

Fixes

1. Use plain def for sync code

The simplest fix is often deleting one word. If an endpoint only calls sync libraries, declare it with def and FastAPI will run it in the threadpool:

Diff
 @app.get("/users/{user_id}")
-async def get_user(user_id: int, db: Session = Depends(get_db)):
+def get_user(user_id: int, db: Session = Depends(get_db)):
     user = db.query(User).filter(User.id == user_id).first()
     if user is None:
         raise HTTPException(status_code=404, detail="User not found")
     return user

This catches a subtle case too. A sync get_db dependency runs in a thread, but if the endpoint is async def, every db.query(...) inside it runs on the loop. The dependency being def doesn't protect the endpoint body.

2. Offload blocking calls to a thread

When an endpoint needs to await something and call a blocking library, keep it async def and push only the blocking part to a thread:

Python
import asyncio

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

app = FastAPI()


def fetch_rates_sync(base: str) -> dict:
    response = requests.get(
        "https://api.example.com/rates", params={"base": base}, timeout=10
    )
    response.raise_for_status()
    return response.json()


@app.get("/rates/{base}")
async def rates(base: str) -> dict:
    # Standard library. Uses the event loop's default ThreadPoolExecutor.
    return await asyncio.to_thread(fetch_rates_sync, base)


@app.get("/rates-alt/{base}")
async def rates_alt(base: str) -> dict:
    # Starlette helper. Uses the same AnyIO thread limiter as def endpoints.
    return await run_in_threadpool(fetch_rates_sync, base)

Both work. The difference is which pool the work lands in, which matters once you start tuning (see fix 6).

Warning: Always set timeouts on sync clients you offload. A requests.get with no timeout against a hung upstream holds a thread forever, and enough of those will exhaust the pool.

3. Switch to async libraries

Threads are a bridge. For I/O that happens on every request, a native async client is cheaper and scales further.

HTTP calls. Create one httpx.AsyncClient per process in the lifespan and reuse it, so you get connection pooling instead of a new TLS handshake per request:

Python
from contextlib import asynccontextmanager
from typing import AsyncIterator

import httpx
from fastapi import FastAPI, Request


@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
    app.state.http = httpx.AsyncClient(
        timeout=httpx.Timeout(10.0, connect=5.0),
        limits=httpx.Limits(max_connections=100, max_keepalive_connections=20),
    )
    yield
    await app.state.http.aclose()


app = FastAPI(lifespan=lifespan)


@app.get("/rates/{base}")
async def rates(base: str, request: Request) -> dict:
    response = await request.app.state.http.get(
        "https://api.example.com/rates", params={"base": base}
    )
    response.raise_for_status()
    return response.json()

SQL databases. SQLAlchemy's async engine with asyncpg gives you the same ORM with awaitable queries:

Python
from typing import AsyncIterator

from fastapi import Depends, FastAPI, HTTPException
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine

engine = create_async_engine(
    "postgresql+asyncpg://app:app@localhost:5432/app",
    pool_size=10,
    max_overflow=10,
    pool_pre_ping=True,
)
SessionLocal = async_sessionmaker(engine, expire_on_commit=False)

app = FastAPI()


async def get_session() -> AsyncIterator[AsyncSession]:
    async with SessionLocal() as session:
        yield session


@app.get("/users/{user_id}")
async def get_user(user_id: int, session: AsyncSession = Depends(get_session)) -> dict:
    result = await session.execute(
        text("SELECT id, email FROM users WHERE id = :id"), {"id": user_id}
    )
    row = result.mappings().first()
    if row is None:
        raise HTTPException(status_code=404, detail="User not found")
    return dict(row)

Note: Async SQLAlchemy can't lazy-load relationships implicitly. Accessing an unloaded relationship raises MissingGreenlet. Load what you need up front with selectinload() or joinedload() in the query.

MongoDB. Use an async client and await every operation. MongoDB now points new projects at PyMongo's native async API rather than Motor, but both work the same way from FastAPI's point of view:

Python
from fastapi import FastAPI, HTTPException
from pymongo import AsyncMongoClient

client = AsyncMongoClient("mongodb://localhost:27017")
db = client["app"]

app = FastAPI()


@app.get("/orders/{order_id}")
async def get_order(order_id: str) -> dict:
    doc = await db.orders.find_one({"order_id": order_id}, {"_id": 0})
    if doc is None:
        raise HTTPException(status_code=404, detail="Order not found")
    return doc

4. Move CPU-bound work to processes

Threads don't help with pure-Python CPU work. On the standard CPython build the GIL lets only one thread execute Python bytecode at a time, so a CPU-heavy thread still slows the event loop thread down. Use a process pool instead, created once in the lifespan:

Python
import asyncio
import hashlib
from concurrent.futures import ProcessPoolExecutor
from contextlib import asynccontextmanager
from typing import AsyncIterator

from fastapi import FastAPI, Request


def expensive_hash(data: bytes, rounds: int) -> str:
    # Must be a top-level function so it can be pickled and sent to a worker.
    digest = data
    for _ in range(rounds):
        digest = hashlib.sha256(digest).digest()
    return digest.hex()


@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
    app.state.process_pool = ProcessPoolExecutor(max_workers=2)
    yield
    app.state.process_pool.shutdown()


app = FastAPI(lifespan=lifespan)


@app.post("/hash")
async def hash_body(request: Request, rounds: int = 200_000) -> dict[str, str]:
    body = await request.body()
    loop = asyncio.get_running_loop()
    digest = await loop.run_in_executor(
        request.app.state.process_pool, expensive_hash, body, rounds
    )
    return {"digest": digest}

Arguments and return values are pickled across the process boundary, so keep them small. Pass a file path, not a 200 MB DataFrame.

If the job takes more than a few seconds, it shouldn't be tied to an HTTP request at all. Push it to a task queue (Celery, RQ or arq), return a job ID immediately, and let the client poll or receive a webhook when it's done. That also survives worker restarts, which an in-process pool does not.

5. Check dependencies and middleware

Blocking code hides in places that run on every request, which makes it worse than a single slow endpoint. Two common ones:

Python
# Broken: async dependency doing a sync DB lookup on every authenticated request
async def get_current_user(token: str = Depends(oauth2_scheme)) -> User:
    payload = decode_token(token)
    return user_repository.get_by_id_sync(payload["sub"])


# Fixed: make it def, and FastAPI runs it in the threadpool
def get_current_user(token: str = Depends(oauth2_scheme)) -> User:
    payload = decode_token(token)
    return user_repository.get_by_id_sync(payload["sub"])

Middleware has no def escape hatch, so offload explicitly:

Python
import asyncio
import json
import time

from fastapi import FastAPI, Request

app = FastAPI()


def append_audit_line(line: str) -> None:
    with open("audit.log", "a", encoding="utf-8") as f:
        f.write(line + "\n")


@app.middleware("http")
async def audit_log(request: Request, call_next):
    start = time.perf_counter()
    response = await call_next(request)
    line = json.dumps({
        "method": request.method,
        "path": request.url.path,
        "status": response.status_code,
        "ms": round((time.perf_counter() - start) * 1000, 1),
    })
    # Was: append_audit_line(line), a disk write on the event loop for every request
    await asyncio.to_thread(append_audit_line, line)
    return response

6. Tune the threadpool carefully

def endpoints, def dependencies and run_in_threadpool all share AnyIO's default thread limiter, which allows 40 concurrent threads. If 40 requests are stuck in a slow sync call, the 41st def endpoint waits for a free slot even if its own work is trivial. Async endpoints are unaffected.

You can raise the limit at startup:

Python
from contextlib import asynccontextmanager
from typing import AsyncIterator

import anyio.to_thread
from fastapi import FastAPI


@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
    limiter = anyio.to_thread.current_default_thread_limiter()
    limiter.total_tokens = 100
    yield


app = FastAPI(lifespan=lifespan)

Before you do, consider:

  • More threads means more memory and more GIL contention. It helps with I/O waits, not CPU work.
  • Each thread may hold a database connection. Your DB pool (and the database's own connection limit) must keep up, or threads just queue on the pool instead.
  • asyncio.to_thread doesn't use this limiter. It uses the loop's default ThreadPoolExecutor, sized min(32, os.cpu_count() + 4). Replace it with loop.set_default_executor(ThreadPoolExecutor(max_workers=...)) if you need more.
  • Usually the better fix is a timeout on the slow call, not a bigger pool.

How to find the blocking call

Asyncio debug mode

Debug mode logs any task step that holds the loop longer than slow_callback_duration (0.1 seconds by default). Run Uvicorn with the standard asyncio loop so you get the stdlib's instrumentation:

Terminal
PYTHONASYNCIODEBUG=1 uvicorn main:app --loop asyncio
PowerShell
$env:PYTHONASYNCIODEBUG = "1"; uvicorn main:app --loop asyncio

To catch shorter stalls, lower the threshold in the lifespan:

Python
import asyncio
from contextlib import asynccontextmanager
from typing import AsyncIterator

from fastapi import FastAPI


@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
    loop = asyncio.get_running_loop()
    if loop.get_debug():
        loop.slow_callback_duration = 0.05
    yield


app = FastAPI(lifespan=lifespan)

Hit your endpoints and watch stderr for lines that start with Executing <Task and end with how long the step took. Debug mode adds overhead, so use it locally or in staging, not in production.

A loop-lag monitor for production

A cheap background task can measure how late the loop wakes it up. If it oversleeps, something blocked the loop:

Python
import asyncio
import logging
from contextlib import asynccontextmanager
from typing import AsyncIterator

from fastapi import FastAPI

logger = logging.getLogger("app")


async def monitor_loop_lag(interval: float = 0.5, threshold: float = 0.1) -> None:
    loop = asyncio.get_running_loop()
    while True:
        start = loop.time()
        await asyncio.sleep(interval)
        lag = loop.time() - start - interval
        if lag > threshold:
            logger.warning("Event loop was blocked for %.3fs", lag)


@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
    task = asyncio.create_task(monitor_loop_lag())
    yield
    task.cancel()


app = FastAPI(lifespan=lifespan)

It tells you that the loop was blocked and when, which you can line up with request logs to find which endpoint did it.

py-spy dump

When a worker is stuck right now, py-spy shows you exactly where, without restarting or changing code:

Terminal
pip install py-spy
pgrep -f "uvicorn main:app"
py-spy dump --pid 12345

Look at the MainThread stack. If the event loop thread is sitting in time.sleep, a socket recv, an SSL read, or a database driver's execute call, you've found it. Run it a few times during a slowdown; the frame that keeps appearing is your blocker.

Tip: In Docker, py-spy needs the SYS_PTRACE capability (docker run --cap-add SYS_PTRACE my-api-image, or cap_add: [SYS_PTRACE] in Compose). On Linux hosts you may also need sudo.

Checklist

  • Every async def endpoint only awaits async calls; there are no requests, time.sleep, sync DB sessions or sync SDK calls inside.
  • Endpoints that use sync libraries are declared with plain def.
  • Sync calls that must live in async code are wrapped in asyncio.to_thread or run_in_threadpool, with timeouts.
  • HTTP clients are shared httpx.AsyncClient instances created in the lifespan.
  • Database access uses an async driver, or the endpoints using a sync session are def.
  • CPU-heavy work runs in a ProcessPoolExecutor or a task queue.
  • async def dependencies and @app.middleware("http") functions contain no blocking calls.
  • The threadpool size matches your DB pool, and you've raised it only after adding timeouts.
  • Asyncio debug mode is clean in staging, and a loop-lag monitor is logging in production.

Wrap-up

async def is a promise to the event loop that your code will never block. FastAPI takes you at your word, so breaking that promise in one place stalls everything else on the worker. The fix is rarely complicated: use def for sync code, offload the odd blocking call to a thread, use async clients for hot paths, and send CPU work to processes. The hard part is finding the call, and debug mode, a lag monitor and py-spy make that a matter of minutes rather than guesswork.

Stuck on something like this?

I build and fix full-stack products for startups and indie founders. Tell me what's broken.

Get in touch