← All notes

Backend

Alembic Async Migrations and Idempotent Database Seeding in FastAPI

Alembic's default env.py is synchronous. This post covers the async migration setup, auto-database creation, and an idempotent seed script that is safe to re-run at any point.

Published
Reading
8 min
Author
Fidelis Uwem Joseph
Series · Part 3 of 9FastAPI in Production
  1. FastAPI Layered Architecture — Routes, Services, and Repositories
  2. Alembic with SQLAlchemy 2.0 Async — Migrations That Hold in Production
  3. Alembic Async Migrations and Idempotent Database Seeding in FastAPI
  4. Stateless OTP Login in FastAPI with JWT and Redis
  5. Async Email Delivery in FastAPI — Two SMTP Paths, One Jinja2 Template System
  6. Celery + Redis in Production — Task Reliability with acks_late and Retry Backoff
  7. Monitoring Celery with Flower — Local Setup and SSH Tunnel for Remote Servers
  8. Mailpit as a Dev SMTP Catch-All Behind Traefik
  9. MinIO as a Self-Hosted S3 Backend in Docker

← Part 2Series overviewPart 4 →

Alembic’s default env.py uses a synchronous engine. If your FastAPI application is built entirely on asyncpg and SQLAlchemy’s async session, the mismatch surfaces immediately: autogenerate does not detect your models, or the migration runner fails to connect. Fixing it requires rewriting env.py to use an async engine with asyncio.run().

Beyond migrations, every application needs a seed script — a way to populate the database with the roles, permissions, reference data, and test accounts that make the application functional from a fresh state. This post covers both: a compact async env.py that also creates the database if it is missing, and an idempotent seed script that can run safely at any point without duplicating records. The previous part explains the async env.py line by line; here the focus is on what to add around it.

Prerequisites

Alembic 1.13 or later, SQLAlchemy 2.x with asyncpg, and an existing FastAPI project with a Base declarative base and at least one model. All models must be imported before Alembic’s autogenerate runs, or tables will appear to have been dropped.

Background

Alembic’s env.py generated by alembic init uses engine_from_config and a synchronous engine.connect() context. With asyncpg, there is no synchronous dialect — every connection goes through the async path. Swapping the engine to async_engine_from_config and wrapping the migration runner in asyncio.run() is the correct fix.

Implementation — Async env.py

1. Engine setup and model loading

alembic/env.py
import asyncio
from sqlalchemy import pool
from sqlalchemy.engine import Connection
from sqlalchemy.ext.asyncio import async_engine_from_config, create_async_engine
from alembic import context
from app.config import settings
from app.db.base import Base
import app.models # noqa: F401 — imports every model in dependency order
config = context.config
config.set_main_option("sqlalchemy.url", settings.DATABASE_URL)
target_metadata = Base.metadata

import app.models is a single line that imports an __init__.py which re-exports every model in the correct dependency order. Alembic reads Base.metadata after this import and sees the full table set. The # noqa: F401 suppresses the “imported but unused” linter warning — the import is side-effect-only.

config.set_main_option("sqlalchemy.url", settings.DATABASE_URL) overrides the sqlalchemy.url in alembic.ini with the value from your Pydantic settings. This means alembic.ini can stay at its placeholder driver://user:pass@localhost/dbname — the actual URL is always sourced from .env. Never hard-code credentials in alembic.ini.

2. Auto-create the database

A fresh environment — a new developer machine, a CI runner, a clean Docker container — may not have the target database yet. Running alembic upgrade head against a missing database fails before a single migration runs.

alembic/env.py
from sqlalchemy import text
from sqlalchemy.engine import make_url
async def ensure_database_exists(url: str) -> None:
target = make_url(url)
db_name = target.database
maintenance_url = target.set(database="postgres")
engine = create_async_engine(
maintenance_url, isolation_level="AUTOCOMMIT", poolclass=pool.NullPool
)
try:
async with engine.connect() as conn:
result = await conn.execute(
text("SELECT 1 FROM pg_database WHERE datname = :name"),
{"name": db_name},
)
if result.scalar() is None:
await conn.execute(text(f'CREATE DATABASE "{db_name}"'))
print(f">>> Database '{db_name}' created.")
finally:
await engine.dispose()

make_url parses the URL properly — passwords containing / or ?, query parameters, unusual ports — where a hand-written regex eventually breaks. The function connects to the postgres maintenance database — which always exists on a PostgreSQL server — and creates the target database if the pg_database lookup returns nothing. AUTOCOMMIT isolation is required because CREATE DATABASE cannot run inside a transaction.

The NullPool on both this engine and the migration engine is deliberate. Migration runs are short-lived scripts, not persistent application processes. Connection pooling adds overhead and can leave connections open after the script exits. NullPool closes each connection immediately after use.

3. Offline and online migration modes

alembic/env.py
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"},
compare_type=True,
compare_server_default=True,
)
with context.begin_transaction():
context.run_migrations()
def do_migrations(connection: Connection) -> None:
context.configure(
connection=connection,
target_metadata=target_metadata,
compare_type=True,
compare_server_default=True,
)
with context.begin_transaction():
context.run_migrations()
async def run_migrations_online() -> None:
await ensure_database_exists(settings.DATABASE_URL)
connectable = async_engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
async with connectable.connect() as connection:
await connection.run_sync(do_migrations)
await connectable.dispose()
if context.is_offline_mode():
run_migrations_offline()
else:
asyncio.run(run_migrations_online())

compare_type=True tells Alembic to detect column type changes — for example, a String(100) widened to String(255) — and include ALTER COLUMN statements in the autogenerated migration. Without it, type changes are silently ignored.

compare_server_default=True detects changes to server_default values, such as adding server_default=func.now() to a column. Without it, adding a server default produces no migration and the change never reaches the database.

do_migrations is a plain synchronous function because connection.run_sync() executes it inside the async connection’s synchronous driver interface. This is the standard pattern for mixing Alembic’s synchronous context.run_migrations() with an async SQLAlchemy connection.

4. Generating and running migrations

Terminal
# Generate a migration after changing a model
$ alembic revision --autogenerate -m "add room floor column"
# Review the generated file in alembic/versions/
# Then apply
$ alembic upgrade head
# Check current state
$ alembic current
# Rollback one step
$ alembic downgrade -1

Always review the generated migration file before applying it. Autogenerate misses certain changes: custom constraints with non-standard naming, CHECK constraints, partial indexes, and some enum operations on PostgreSQL. Add those manually.


Implementation — Idempotent Seed Script

5. Single-transaction, ordered seeders

The seed script wraps every seeder in a single session.begin() block. If any seeder fails, the entire transaction rolls back — no half-seeded database. Seeders run in dependency order: permissions before roles, roles before users, organisations before branches.

scripts/seed.py
async def seed() -> None:
engine = create_async_engine(settings.DATABASE_URL, echo=False)
async_session = async_sessionmaker(engine, expire_on_commit=False)
async with async_session() as session:
async with session.begin():
role_map = await seed_permissions_and_roles(session)
await seed_superadmin(session)
org = await seed_organization(session)
dodoma, abuja = await seed_branches(session, org)
await seed_staff_users(session, dodoma, role_map)
await seed_guests(session)
await seed_room_types_and_rooms(session, dodoma)
await seed_room_types_and_rooms(session, abuja)
await seed_menu(session)
await seed_item_categories(session)
await engine.dispose()
print("\n✓ Seed complete.\n")

Seeders receive the parent object as an argument when they depend on it — seed_branches(session, org) receives the organisation returned by seed_organization. This makes the dependency graph explicit in the call site rather than hidden inside each seeder.

6. The idempotent pattern — flush, check, skip

Every seeder follows the same shape: query by a stable unique key, skip if found, insert and flush if not. flush() writes the row to the database within the current transaction — giving the new row a database-assigned ID — without committing. Subsequent seeders in the same transaction can reference that ID.

scripts/seed.py
async def seed_organization(session: AsyncSession) -> Organization:
result = await session.execute(
select(Organization).where(Organization.code == "GHG")
)
org = result.scalar_one_or_none()
if org:
skip("Organization 'GHG' already exists")
return org # return existing object, not None
org = Organization(
name="Glonency Hotels Group",
code="GHG",
country="Tanzania",
default_currency="TZS",
is_active=True,
)
session.add(org)
await session.flush() # org.id is now set, no commit yet
ok("Organization 'Glonency Hotels Group' created")
return org

The function always returns an Organization — whether it created one or found an existing one. Callers treat the return value identically regardless of which path ran.

Choosing the unique key for the existence check matters. Using the database primary key (UUID) requires knowing it in advance, which the seed script does not. Using a natural key — Organization.code, Room.number, User.username — works for stable reference data that does not change between runs.

7. Many-to-many assignment without lazy loading

Role-permission assignment is a many-to-many relationship. The naive approach — role.permissions.append(permission) — triggers a lazy load of role.permissions in async mode, which raises MissingGreenlet because there is no event loop context for the implicit database call.

scripts/seed.py
from sqlalchemy.orm.attributes import set_committed_value
if abbr not in role_map:
role = Role(name=display_name, abbreviation=abbr, is_system=True)
session.add(role)
await session.flush()
set_committed_value(role, "permissions", []) # init collection, no DB call
role_map[abbr] = role
else:
role = role_map[abbr] # already eager-loaded via selectinload earlier
# Assign permissions safely — works for both new and existing roles
role.permissions = list(perm_map.values())

set_committed_value(role, "permissions", []) initialises the collection on the ORM object without touching the database. SQLAlchemy treats it as if the collection was loaded from the database as an empty list. After this, role.permissions = [...] is a direct assignment that SQLAlchemy queues for the next flush, not a lazy-load trigger.

For existing roles, the selectinload(Role.permissions) earlier in the same function pre-loads the collection, so the same assignment works without needing set_committed_value.

8. Seeding hierarchical data

Room types must exist before rooms. Items must be categorised before they are created. The pattern is to build a dict keyed by name during the first pass, then reference it during the second:

scripts/seed.py
async def seed_room_types_and_rooms(session: AsyncSession, branch: Branch) -> None:
type_map: dict[str, RoomType] = {}
for rt_data in room_types_data:
result = await session.execute(
select(RoomType).where(RoomType.branch_id == branch.id, RoomType.name == rt_data["name"])
)
rt = result.scalar_one_or_none() or RoomType(branch_id=branch.id, **rt_data)
if not rt.id:
session.add(rt)
await session.flush()
type_map[rt_data["name"]] = rt
for r in rooms_data:
# ...
rt = type_map[r["room_type"]] # safe — type_map is fully populated
room = Room(branch_id=branch.id, room_type_id=rt.id, ...)
session.add(room)
await session.flush()

The room type pass runs completely before the room pass starts. No room is created until its type exists and has a database ID.

Testing

Verify migrations and seed on a clean database:

Terminal
# Start a fresh Postgres
$ docker compose -f docker-compose-dev.yml up postgres -d
# Apply all migrations — this also creates the database if needed
$ alembic upgrade head
# Output
>>> Database 'mydb' created.
INFO [alembic.runtime.migration] Running upgrade -> 0bfe3470a1fb, init
# Seed reference data
$ PYTHONPATH=. python3 scripts/seed.py
── Permissions & Roles ──────────────────────────────
[+] Permissions ensured (87 total)
[+] Role 'hotel_manager' created
[+] Role 'receptionist' created
── Superadmin ───────────────────────────────────────
[+] Superadmin 'admin' created
── Organization ─────────────────────────────────────
[+] Organization 'Glonency Hotels Group' created
── Branches ─────────────────────────────────────────
[+] Branch 'DOD' created
[+] Branch 'ABJ' created
✓ Seed complete.
# Re-run — confirm idempotency
$ PYTHONPATH=. python3 scripts/seed.py
── Permissions & Roles ──────────────────────────────
[~] Role 'hotel_manager' already exists
[~] Role 'receptionist' already exists
── Superadmin ───────────────────────────────────────
[~] Superadmin 'admin' already exists
✓ Seed complete.

Every [~] line confirms idempotency. Zero errors on the second run means the seed script can be added to deployment pipelines without a “already exists” guard around the entire script.

Pitfalls

Production considerations

The seed script is for reference data — roles, permissions, categories, and lookup tables that must exist for the application to function. It is not for generating test fixtures. Test fixtures belong in conftest.py with factory-boy; seeding belongs in scripts/seed.py and runs as part of the deployment pipeline.

Run alembic upgrade head before the seed script on every deployment. Migration and seed are two separate steps with a strict order: schema first, data second. A seed script that runs against an old schema fails with a column-not-found error, which is the correct failure mode — it surfaces the ordering mistake immediately.

For CI, add both steps to the test pipeline:

.github/workflows/test.yml
- name: Apply migrations
run: alembic upgrade head
- name: Seed reference data
run: PYTHONPATH=. python3 scripts/seed.py

Wrapping up

The async env.py makes Alembic compatible with an asyncpg-only application without introducing a synchronous SQLAlchemy engine just for migrations. ensure_database_exists removes the manual createdb step from onboarding and CI setup. The idempotent seed script runs safely at any stage — initial setup, after a database wipe, or in a continuous deployment pipeline — and produces explicit output for every record it creates or skips.

The next problem is migration safety under live traffic: adding a column with a NOT NULL default, renaming a column, or removing one while old application instances are still running against the database. Those operations require multi-step migrations separated by deployments.

Going deeper

Let the database enforce idempotency. Select-then-insert is safe when one process seeds at a time. If two deploy jobs can run the seed together, both see “not found” and both insert. PostgreSQL’s INSERT ... ON CONFLICT (code) DO NOTHING (SQLAlchemy: postgresql.insert(Organization).on_conflict_do_nothing(index_elements=["code"])) makes the database the arbiter, and a unique constraint on every natural key turns a race into a no-op instead of a duplicate.

Seed data that changes. “Skip if exists” never updates a row. When a permission’s description or a role’s permission set changes between releases, the seed must converge instead: use ON CONFLICT ... DO UPDATE for reference rows, and replace collections (as the role-permission code does) rather than append to them. A seed that converges can run on every deploy; one that only inserts quietly goes stale.

Reference data or migration? Rows the code depends on by value — a role the authorisation code checks by name, a currency the pricing code assumes — belong in a data migration, versioned alongside the schema change that needs them. The seed script is for everything that is convenient but not structural: demo branches, sample menus, a development superadmin. Never ship real credentials in a seed: read the superadmin password from the environment and refuse to run if it is missing in production.