How does SQLAlchemy async work with FastAPI?

Answer

FastAPI's async support is best paired with SQLAlchemy 1.4+ async engine and asyncpg (PostgreSQL async driver). Setup: from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine; engine = create_async_engine("postgresql+asyncpg://user:pass@localhost/db"); async_session = sessionmaker(engine, class_=AsyncSession). Create a dependency: async def get_db(): async with async_session() as session: yield session. Use in routes: result = await db.execute(select(User).where(User.id == id)); user = result.scalar_one_or_none(). The async SQLAlchemy style uses explicit SQL expressions rather than the ORM query API. Key difference from sync SQLAlchemy: db.query(User) becomes await db.execute(select(User)). With async SQLAlchemy + asyncpg, FastAPI can handle thousands of concurrent DB queries per second without thread pool exhaustion.