Use an async engine and driver (SQLAlchemy asyncio with asyncpg for PostgreSQL) and await every database call, so the event loop stays free while queries run.
Set expire_on_commit=False to avoid lazy-loading surprises after commit, and avoid implicit lazy loading in async code (use eager loading).
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
engine = create_async_engine("postgresql+asyncpg://user:pass@host/db",
pool_size=10, max_overflow=20, pool_pre_ping=True)
AsyncSessionLocal = async_sessionmaker(engine, expire_on_commit=False)
async def get_session():
async with AsyncSessionLocal() as session:
yield session
@app.get("/items/{item_id}", response_model=ItemOut)
async def read_item(item_id: int, session: AsyncSession = Depends(get_session)):
row = await session.get(ItemRow, item_id)
if row is None:
raise HTTPException(status_code=404, detail="Item not found")
return row