FastAPI Async Performance Tuning
FastAPI leverages Starlette and Pydantic for high speed. However, unoptimized DB connections or blocking I/O will starve event loop workers.
1. Async PostgreSQL Connection Pooling with AsyncPG
from fastapi import FastAPI
from asyncpg import create_pool
app = FastAPI()
@app.on_event("startup")
async def startup():
app.state.pool = await create_pool(
dsn="postgresql://user:pass@localhost/db",
min_size=10,
max_size=50,
timeout=10.0
)
@app.get("/api/v1/users/{user_id}")
async def get_user(user_id: int):
async with app.state.pool.acquire() as conn:
user = await conn.fetchrow("SELECT id, email FROM users WHERE id = $1", user_id)
return dict(user)
2. Production Uvicorn Run Configuration
gunicorn main:app \
--workers 4 \
--worker-class uvicorn.workers.UvicornWorker \
--bind 0.0.0.0:8000 \
--timeout 30 \
--keep-alive 5