Backend
Alembic with SQLAlchemy 2.0 Async — Migrations That Hold in Production
SQLAlchemy async models and Alembic fight each other until you wire them correctly. This post covers the full setup: env.py for async engines, autogenerate that actually catches your changes, and a safe rollback strategy.
- Published
- Reading
- 7 min
- Author
- Fidelis Uwem Joseph
Series · Part 2 of 9FastAPI in Production
- FastAPI Layered Architecture — Routes, Services, and Repositories
- Alembic with SQLAlchemy 2.0 Async — Migrations That Hold in Production
- Alembic Async Migrations and Idempotent Database Seeding in FastAPI
- Stateless OTP Login in FastAPI with JWT and Redis
- Async Email Delivery in FastAPI — Two SMTP Paths, One Jinja2 Template System
- Celery + Redis in Production — Task Reliability with acks_late and Retry Backoff
- Monitoring Celery with Flower — Local Setup and SSH Tunnel for Remote Servers
- Mailpit as a Dev SMTP Catch-All Behind Traefik
- MinIO as a Self-Hosted S3 Backend in Docker
Most SQLAlchemy migration guides assume you are using the synchronous engine.
The moment you switch to asyncpg and AsyncEngine, the standard Alembic
env.py can’t connect at all — and the usual workaround, a second synchronous
database URL just for migrations, drifts from the app’s configuration until a
migration runs against the wrong database. This post fixes that properly.
By the end you will have an Alembic setup that autogenerates correctly against
an async SQLAlchemy 2.0 model base, runs safely in CI, and handles rollbacks
without manual SQL.
Prerequisites
Python 3.12, SQLAlchemy 2.0, Alembic 1.13, and an async-capable PostgreSQL
driver (asyncpg). The project should already have a working FastAPI app with
at least one SQLAlchemy model defined using the Mapped[] annotation syntax.
Familiarity with DeclarativeBase and AsyncSession is assumed.
Background
Alembic’s env.py runs migrations using a synchronous connection by default.
SQLAlchemy 2.0’s async engine wraps an underlying sync engine, but Alembic
cannot call run_migrations_online() against it directly — it raises
MissingGreenlet at runtime because asyncpg requires an event loop context
that the default env.py never provides.
The fix is not complicated, but it is non-obvious: open an async connection
inside asyncio.run() and hand Alembic a sync view of it with
connection.run_sync(). Everything else — autogenerate, version
history, downgrade — works identically once this is wired correctly.
Implementation
1. Project structure
Establish the layout before running alembic init. Keeping migrations inside
the app package rather than at the project root makes the database URL import
cleaner and avoids path hacks in env.py.
project/├── app/│ ├── db/│ │ ├── base.py # DeclarativeBase lives here│ │ ├── models/│ │ │ ├── __init__.py # imports every model — critical for autogenerate│ │ │ ├── user.py│ │ │ └── item.py│ │ └── session.py # AsyncEngine and AsyncSession factory│ └── core/│ └── config.py # Settings with DATABASE_URL├── migrations/│ ├── env.py│ ├── script.py.mako│ └── versions/└── alembic.ini2. DeclarativeBase and model definitions
SQLAlchemy 2.0 replaces declarative_base() with DeclarativeBase. All
models inherit from this single class, and Base.metadata is what Alembic
reads during autogenerate.
from sqlalchemy.orm import DeclarativeBase
class Base(DeclarativeBase): passimport uuidfrom datetime import datetimefrom sqlalchemy import String, DateTime, funcfrom sqlalchemy.orm import Mapped, mapped_columnfrom app.db.base import Base
class User(Base): __tablename__ = "users"
id: Mapped[uuid.UUID] = mapped_column( primary_key=True, default=uuid.uuid4 ) email: Mapped[str] = mapped_column(String(255), unique=True, nullable=False) created_at: Mapped[datetime] = mapped_column( DateTime(timezone=True), server_default=func.now() )Autogenerate compares the Column objects in Base.metadata, so the older
Column(...) style is detected just as well. Mapped[] is about typing: it
gives your editor and mypy real types for every attribute, and lets
nullable be inferred from Optional[...].
# Every model must be imported here. Alembic calls this module before# reading Base.metadata. A model that is never imported is invisible# to autogenerate, even if it inherits from Base.from app.db.models.user import User # noqa: F401from app.db.models.item import Item # noqa: F4013. Async session factory
The AsyncEngine is created once at startup and reused. The DATABASE_URL
must use the postgresql+asyncpg scheme — the standard postgresql:// scheme
routes through psycopg2 and will not work with AsyncSession.
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_enginefrom app.core.config import settings
engine = create_async_engine( settings.DATABASE_URL, # postgresql+asyncpg://user:pass@host/db pool_size=10, max_overflow=20, echo=False,)
AsyncSessionLocal = async_sessionmaker( bind=engine, class_=AsyncSession, expire_on_commit=False,)expire_on_commit=False prevents SQLAlchemy from expiring all attributes
after a commit. Without it, accessing a model attribute after await session.commit() triggers an implicit lazy load that fails in an async
context with MissingGreenlet.
4. Configure alembic.ini
Run alembic init migrations to generate the skeleton, then update
alembic.ini to point at the correct migration directory. Leave
sqlalchemy.url blank — the URL comes from the application settings at
runtime, not from the ini file.
[alembic]script_location = migrationsfile_template = %%(year)d%%(month).2d%%(day).2d_%%(rev)s_%%(slug)s
# Leave empty — URL is set programmatically in env.pysqlalchemy.url =The file_template setting produces date-prefixed filenames like
20250407_a1b2c3d4_add_users_table.py. Alembic orders migrations by each
file’s down_revision, not its name, but sorted filenames make the history
readable in a directory listing and in code review.
5. env.py — the async-aware configuration
This is where most async setups break. The key is run_async_migrations():
it runs inside asyncio.run(), connects the async engine, and passes the
underlying sync connection to context.configure().
import asynciofrom logging.config import fileConfig
from sqlalchemy import poolfrom sqlalchemy.engine import Connectionfrom sqlalchemy.ext.asyncio import async_engine_from_config
from alembic import context
# Import Base and all models so metadata is fully populatedfrom app.db.base import Baseimport app.db.models # noqa: F401 — triggers __init__.py importsfrom app.core.config import settings
config = context.configconfig.set_main_option("sqlalchemy.url", settings.DATABASE_URL)
if config.config_file_name is not None: fileConfig(config.config_file_name)
target_metadata = Base.metadata
def run_migrations_offline() -> None: url = config.get_main_option("sqlalchemy.url") context.configure( url=url, target_metadata=target_metadata, literal_binds=True, dialect_opts={"paramstyle": "named"}, ) with context.begin_transaction(): context.run_migrations()
def do_run_migrations(connection: Connection) -> None: context.configure( connection=connection, target_metadata=target_metadata, compare_type=True, # detects column type changes compare_server_default=True, # detects server_default changes ) with context.begin_transaction(): context.run_migrations()
async def run_async_migrations() -> None: connectable = async_engine_from_config( config.get_section(config.config_ini_section, {}), prefix="sqlalchemy.", poolclass=pool.NullPool, # migrations never need a connection pool ) async with connectable.connect() as connection: await connection.run_sync(do_run_migrations) await connectable.dispose()
def run_migrations_online() -> None: asyncio.run(run_async_migrations())
if context.is_offline_mode(): run_migrations_offline()else: run_migrations_online()compare_type has defaulted to True since Alembic 1.12; on older versions,
leaving it out meant changing String(100) to String(255) produced an empty
migration. Setting it explicitly documents the intent either way.
compare_server_default=True is still off by default, so changes to
server_default values are silently skipped without it.
NullPool on the migration engine is deliberate. Migrations are short-lived
processes that should open a connection, run, and close cleanly. A connection
pool in this context wastes resources and occasionally holds connections open
after the migration process exits.
6. Generate and apply the first migration
With env.py wired correctly, autogenerate now reads the full model metadata.
# Generate a migration from the current model statealembic revision --autogenerate -m "add users and items tables"
# Review the generated file before applying itcat migrations/versions/20250407_a1b2c3d4_add_users_and_items_tables.py
# Apply to the databasealembic upgrade headAlways read the generated file before running upgrade head. Autogenerate
is a starting point, not a guarantee. It cannot detect table renames (it sees
a drop and a create), and it misses constraints that are not reflected in
SQLAlchemy’s metadata model.
def upgrade() -> None: op.create_table( "users", sa.Column("id", postgresql.UUID(), nullable=False), sa.Column("email", sa.String(length=255), nullable=False), sa.Column( "created_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=True, ), sa.PrimaryKeyConstraint("id"), sa.UniqueConstraint("email"), )
def downgrade() -> None: op.drop_table("users")7. Running migrations in a FastAPI startup event
For a single-instance deployment, applying pending migrations at startup is the
simplest option (with several instances, use the pre-deploy job described under
Production considerations). Use a lifespan handler rather than
@app.on_event("startup"), which is deprecated in favour of lifespan.
import asynciofrom contextlib import asynccontextmanagerfrom alembic.config import Configfrom alembic import commandfrom fastapi import FastAPI
def run_migrations() -> None: alembic_cfg = Config("alembic.ini") command.upgrade(alembic_cfg, "head")
@asynccontextmanagerasync def lifespan(app: FastAPI): await asyncio.to_thread(run_migrations) yield
app = FastAPI(lifespan=lifespan)The to_thread call is not optional. The lifespan handler already runs inside
the server’s event loop, and our env.py calls asyncio.run(), which raises
RuntimeError: asyncio.run() cannot be called from a running event loop.
Running the migration in a worker thread gives asyncio.run() a thread with
no loop of its own, and keeps the server’s loop free while it runs.
Testing
Verify the full cycle with a round-trip test against a real database. SQLite in-memory does not behave identically to PostgreSQL for constraint and type checking, so use a throwaway PostgreSQL instance in CI.
# Check current migration statealembic current
# Output:# INFO [alembic.runtime.migration] Context impl PostgresqlImpl.# INFO [alembic.runtime.migration] Will assume transactional DDL.# 20250407_a1b2c3d4 (head)
# Fail if the models and the database have drifted (Alembic 1.9+)alembic check# No new upgrade operations detected.alembic check runs autogenerate without writing a file and exits non-zero
if it finds differences, which makes it a one-line CI gate. A failure when
nobody changed a model usually means target_metadata is stale — a model is
not being imported in __init__.py.
import pytestfrom alembic.config import Configfrom alembic import command
def test_migrations_up_and_down(): cfg = Config("alembic.ini") command.upgrade(cfg, "head") command.downgrade(cfg, "base") command.upgrade(cfg, "head")This test catches downgrade functions that reference objects no longer present after rollback, which is the most common failure mode when migrations are written manually rather than autogenerated.
Pitfalls
Production considerations
For teams deploying behind a load balancer, migrate before scaling up new
instances. The cleanest pattern is a dedicated migration container in the
deployment pipeline that runs alembic upgrade head as a pre-deploy job,
with the application containers blocked from starting until the migration
container exits cleanly.
Zero-downtime schema changes follow a specific sequence: add nullable columns
first (compatible with the running code), deploy the application, backfill
data, then add constraints in a subsequent migration. Adding a NOT NULL
column with no default to a populated table simply fails. Adding NOT NULL
to an existing column scans the whole table while holding an
ACCESS EXCLUSIVE lock, blocking reads and writes for as long as the scan
takes. On large tables add CHECK (col IS NOT NULL) NOT VALID, run
VALIDATE CONSTRAINT (which takes a weaker lock), then set NOT NULL —
PostgreSQL 12+ skips the scan when a valid check constraint already proves
it.
Keep the alembic_version table in the same schema as your application tables.
Some teams move it to a separate schema to keep things tidy, but this requires
additional --schema flags on every Alembic command and breaks autogenerate
unless the schema is explicitly configured in env.py.
Wrapping up
You now have an Alembic setup that speaks async, autogenerates reliably against
a fully-imported model base, and runs safely in both CI and production startup.
The env.py pattern here — asyncio.run() wrapping connection.run_sync() —
is the canonical approach documented in SQLAlchemy’s own async migration guide,
but it takes reading three different pages to piece together. This is that in
one place.
The next problem you will hit is data migrations: moving data between columns
or transforming values as part of a schema change. Alembic’s op.execute() and
op.bulk_insert() handle this, but the sequencing with zero-downtime deployments
requires a different approach than DDL-only migrations. That, together with
idempotent seeding, is the next part.
Going deeper
Set a lock timeout in every migration. The danger in a production
migration is rarely the DDL itself; it is waiting for a lock. An ALTER TABLE
queued behind one long-running query blocks every query that arrives after
it, so a two-millisecond change takes the site down. Start migrations with
SET lock_timeout = '5s' so they fail fast and can be retried, instead of
stalling all traffic.
Indexes without downtime. op.create_index(..., postgresql_concurrently=True)
builds an index without blocking writes, but CREATE INDEX CONCURRENTLY can’t
run inside a transaction. Wrap it in with op.get_context().autocommit_block():
in that migration.
Name your constraints. Autogenerate can only drop or alter a constraint it
can name. Give Base.metadata a naming_convention
("uq": "uq_%(table_name)s_%(column_0_name)s", and so on) before your first
migration, so every unique, foreign key and check constraint gets a
predictable name across environments.
Merge heads in review, not in production. Two branches that each add a
migration create two heads, and alembic upgrade head refuses to run. Make
alembic heads returning more than one line fail CI, and resolve it with
alembic merge in the branch, not during a deploy.