DEV Community

Cover image for Why Your FastAPI Endpoints Stall Under Load: The Async Def Mistake
Rahul Dubey
Rahul Dubey

Posted on

Why Your FastAPI Endpoints Stall Under Load: The Async Def Mistake

FastAPI is frequently adopted under the promise of near-Go throughput in Python. Yet teams often ship their first service to production only to discover that latency degrades rapidly under modest concurrency. P99 response times spike, health checks fail, and CPU usage stays puzzlingly low.

In almost every case, the culprit is not FastAPI or Uvicorn—it is a misunderstanding of how the ASGI event loop schedules async def routes versus synchronous def routes.

Here is how FastAPI handles execution under the hood and how to fix common blocking bottlenecks.


The FastAPI Routing Decision Engine

When a request hits a route, FastAPI checks the function signature before executing it:

Incoming Request
       │
Is route defined as "async def"?
      ╱ ╲
     ╱   ╲
   YES    NO
   ╱       ╲
  v         v
Run on Main Loop     Offload to AnyIO
(Worker Thread)     Worker Threadpool
* Non-blocking      * Max threads capped (default: 40)
* High throughput   * Context-switching overhead
* Blocked by I/O    * Safe for synchronous drivers
Enter fullscreen mode Exit fullscreen mode
  • async def endpoints run cooperatively on the main event loop thread. If code inside an async def handler invokes a synchronous blocking call (like requests.get(), time.sleep(), or a synchronous database driver), the entire worker thread freezes. No other incoming requests or scheduled coroutines can make progress until that call returns.
  • Plain def endpoints are intercepted by FastAPI and run inside an AnyIO worker threadpool. This protects the main event loop from stalling, but thread creation and context switching introduce overhead. Furthermore, the default threadpool is capped at 40 threads; if 40 requests trigger slow external I/O simultaneously, subsequent requests stall in the queue waiting for an available thread.

Pattern 1: Non-Blocking Network I/O

Calling synchronous HTTP clients or file operations inside async def is the most common cause of event loop starvation.

Anti-Pattern:

import requests
from fastapi import FastAPI

app = FastAPI()

@app.get("/data")
async def fetch_remote_data():
    # Freezes the entire worker thread for all users
    response = requests.get("https://api.external.com/items")
    return response.json()
Enter fullscreen mode Exit fullscreen mode

Production Pattern:
Use an asynchronous HTTP client such as httpx sharing a persistent client session:

import httpx
from fastapi import FastAPI, Depends

app = FastAPI()

async def get_http_client():
    async with httpx.AsyncClient(timeout=5.0) as client:
        yield client

@app.get("/data")
async def fetch_remote_data(client: httpx.AsyncClient = Depends(get_http_client)):
    # Yields control back to the event loop while waiting for network I/O
    response = await client.get("https://api.external.com/items")
    return response.json()
Enter fullscreen mode Exit fullscreen mode

If you must execute a third-party library that lacks an async interface, run it explicitly in a thread worker using AnyIO:

from anyio import to_thread
from fastapi import FastAPI

app = FastAPI()

@app.get("/sync-computation")
async def run_blocking_work():
    result = await to_thread.run_sync(legacy_sync_function, arg1, arg2)
    return {"result": result}
Enter fullscreen mode Exit fullscreen mode

Pattern 2: Connection Pooling via Modern Lifespan

Creating database connections per request is another throughput killer. Legacy FastAPI tutorials often rely on @app.on_event("startup"), but the modern, robust approach uses FastAPI's lifespan context manager combined with a native async driver like asyncpg.

from contextlib import asynccontextmanager
import asyncpg
from fastapi import FastAPI, Request

@asynccontextmanager
async def lifespan(app: FastAPI):
    # Initialize the connection pool during startup
    pool = await asyncpg.create_pool(
        dsn="postgresql://user:pass@localhost:5432/db",
        min_size=10,
        max_size=20,
        timeout=10.0
    )
    app.state.db_pool = pool
    yield
    # Gracefully terminate connections on shutdown
    await pool.close()

app = FastAPI(lifespan=lifespan)

@app.get("/users/{user_id}")
async def get_user(user_id: int, request: Request):
    async with request.app.state.db_pool.acquire() as connection:
        user = await connection.fetchrow(
            "SELECT id, email FROM users WHERE id = $1", user_id
        )
        return dict(user) if user else {"error": "Not found"}
Enter fullscreen mode Exit fullscreen mode

This pattern keeps the event loop clear, limits memory overhead by recycling socket descriptors, and guarantees safe teardown when the container receives a SIGTERM.


Build Production-Grade Async Python

Understanding the event loop is just step one. To build maintainable, enterprise-scale backends, you need end-to-end patterns covering schema design, database concurrency, and background processing.

If you want a step-by-step blueprint, check out The FastAPI & Async Backend Playbook ($27).

Inside the full playbook:

  • Pydantic v2 Deep Dive: Serialization modes, custom validators, and zero-copy JSON parsing.
  • Asyncpg & SQLAlchemy 2.0: Read-write replica routing, connection pool tuning, and transaction rollbacks.
  • Distributed Background Tasks: Offloading work cleanly using Redis and Celery/Arq with dead-letter queue handling.
  • Container & K8s Deployment: Uvicorn worker sizing formulas, Docker multi-stage builds, and graceful SIGTERM handling.

Stop debugging thread lockups and start deploying resilient, scalable async backends.

Top comments (0)