API & Backend
SQLAlchemy 2.0 Async & Alembic: Non-Blocking PostgreSQL ORM in FastAPI
Learn modern SQLAlchemy 2.0 async engine, async_sessionmaker, connection pooling, and seamless Alembic database migrations.
3 min
Asynchronous Database Sessions with asyncpg
SQLAlchemy 2.0 introduces native 2.0-style queries with `select()` syntax and full non-blocking `asyncpg` drivers.
database.py
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker
DATABASE_URL = "postgresql+asyncpg://user:password@localhost/production_db"
engine = create_async_engine(DATABASE_URL, pool_size=20, max_overflow=10)
AsyncSessionFactory = async_sessionmaker(engine, expire_on_commit=False)