Python

Mastering Database Migrations in Python: Advanced Alembic & SQLAlchemy Patterns

Database migrations are one of those parts of backend development that seem simple at first. We add a column, update a model, run a migration, and move on.But…

D
DevByteTechnical Author
Published
11 min read0 views
Mastering Database Migrations in Python: Advanced Alembic & SQLAlchemy Patterns

Database migrations are one of those parts of backend development that seem simple at first. We add a column, update a model, run a migration, and move on.

But as an application grows, database changes become more complicated. A new column may affect thousands of records. A table rename can break an older application version. A migration that works locally may lock a production table or fail halfway through deployment.

This is where Alembic and SQLAlchemy become important.

SQLAlchemy helps us define and interact with database models. Alembic manages schema changes over time, allowing a team to track, review, and apply database migrations in a controlled way.

In this guide, we’ll explore advanced migration patterns that are useful in real-world Python applications. We’ll cover migration configuration, autogeneration, data migrations, safe schema changes, branching, testing, and production deployment strategies.

The examples use SQLAlchemy 2.x, Alembic, and PostgreSQL. Most concepts also apply to other relational databases, although locking and DDL behavior vary by database engine.

1. Why Database Migrations Matter

Imagine we have a user table:

class User(Base):
    __tablename__ = "users"

    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str] = mapped_column(String(100))

Now the product team asks us to store each user’s email address.

We update the model:

email: Mapped[str] = mapped_column(String(255))

But changing the Python model does not automatically change the database schema.

Without a migration, our application may try to query a column that does not exist.

Migrations provide a versioned history of database changes:

Initial schema
    ↓
Add users table
    ↓
Add email column
    ↓
Create email index
    ↓
Add account status

This history helps developers:

  • Apply schema changes consistently across environments

  • Review database changes in code

  • Recreate a database schema from scratch

  • Coordinate changes between application versions

  • Diagnose deployment failures

  • Manage controlled rollbacks where possible

A migration is not just a script. It is part of the application’s deployment process.

2. Install SQLAlchemy and Alembic

Install the required dependencies:

pip install sqlalchemy alembic psycopg[binary]

For this example, we’ll use PostgreSQL.

Create a project structure:

myapp/
├── app/
│   ├── __init__.py
│   ├── database.py
│   └── models.py
├── alembic/
│   ├── env.py
│   └── versions/
├── alembic.ini
└── requirements.txt

Initialize Alembic:

alembic init alembic

This creates the Alembic configuration file and migration directory.

The versions directory stores individual migration scripts. Each migration has a revision ID and usually references a previous revision.

3. Configure SQLAlchemy 2.x Models

Create app/database.py:

import os

from sqlalchemy import create_engine
from sqlalchemy.orm import DeclarativeBase, sessionmaker


DATABASE_URL = os.getenv(
    "DATABASE_URL",
    "postgresql+psycopg://postgres:postgres@localhost:5432/myapp",
)


class Base(DeclarativeBase):
    pass


engine = create_engine(
    DATABASE_URL,
    pool_pre_ping=True,
)


SessionLocal = sessionmaker(
    bind=engine,
    autoflush=False,
    expire_on_commit=False,
)

Now create app/models.py:

from sqlalchemy import String
from sqlalchemy.orm import Mapped, mapped_column

from app.database import Base


class User(Base):
    __tablename__ = "users"

    id: Mapped[int] = mapped_column(primary_key=True)

    name: Mapped[str] = mapped_column(
        String(100),
        nullable=False,
    )

    email: Mapped[str] = mapped_column(
        String(255),
        nullable=False,
        unique=True,
    )

SQLAlchemy models describe the current schema that the application expects.

Alembic compares this metadata with the database schema to help generate migration scripts.

4. Connect Alembic to SQLAlchemy Metadata

Open alembic/env.py.

Alembic needs access to the SQLAlchemy metadata object so it can compare the current model definitions with the database.

Add:

from app.database import Base
from app import models

target_metadata = Base.metadata

Importing models is important because it ensures the model classes are registered with the metadata.

In the online migration configuration, use the metadata:

context.configure(
    connection=connection,
    target_metadata=target_metadata,
    compare_type=True,
    compare_server_default=True,
)

compare_type=True allows Alembic to detect many column-type changes.

compare_server_default=True enables comparison of server-side defaults.

Autogeneration is useful, but it is not a replacement for reviewing migrations. Alembic cannot reliably infer every database operation or business intention.

5. Generate and Apply a Migration

Generate a migration from the model changes:

alembic revision --autogenerate -m "create users table"

Alembic creates a migration file in alembic/versions.

A simplified generated migration might look like this:

from alembic import op
import sqlalchemy as sa


revision = "a1b2c3d4"
down_revision = None
branch_labels = None
depends_on = None


def upgrade():
    op.create_table(
        "users",
        sa.Column("id", sa.Integer(), primary_key=True),
        sa.Column("name", sa.String(100), nullable=False),
        sa.Column("email", sa.String(255), nullable=False),
        sa.UniqueConstraint("email"),
    )


def downgrade():
    op.drop_table("users")

Apply the migration:

alembic upgrade head

Alembic records the applied revision in its alembic_version table.

To check the current revision:

alembic current

To view migration history:

alembic history

The head revision represents the latest migration in a single migration branch.

6. Advanced Pattern: Expand and Contract Migrations

One of the most useful production migration patterns is expand and contract.

Suppose our application currently stores a user’s full name in a column called name. We want to split it into first_name and last_name.

A direct migration might:

  1. Add the new columns.

  2. Copy data from name.

  3. Remove the old column.

This can break older application instances that still expect name.

During a rolling deployment, both old and new application versions may run at the same time.

Instead, use multiple migration steps.

Step 1: Expand the schema

Add the new columns without removing the old one:

def upgrade():
    op.add_column(
        "users",
        sa.Column("first_name", sa.String(100), nullable=True),
    )

    op.add_column(
        "users",
        sa.Column("last_name", sa.String(100), nullable=True),
    )

At this stage, the old application can continue using name.

Step 2: Backfill the data

Copy existing data into the new columns.

For a simple dataset:

def upgrade():
    op.execute(
        """
        UPDATE users
        SET first_name = split_part(name, ' ', 1),
            last_name = NULLIF(
                substring(name from position(' ' in name) + 1),
                ''
            )
        WHERE first_name IS NULL
        """
    )

This example uses PostgreSQL string functions. Name splitting is inherently imperfect for real-world names, so production data transformations should be designed around the actual business rules.

For a large table, avoid one enormous update if it could cause excessive locking, transaction growth, or replication lag. Use a controlled batch process or a dedicated backfill job.

Step 3: Deploy compatible application code

Deploy application code that can work with the old and new columns during the transition.

A common approach is:

  • Read from the new columns when available.

  • Continue writing to both representations temporarily.

  • Monitor whether old application instances still depend on the old field.

Step 4: Contract the schema

After all application versions have moved to the new columns and the backfill is verified, remove the old column in a later migration:

def upgrade():
    op.drop_column("users", "name")

The key idea is to avoid combining a breaking schema change with the first application deployment.

7. Advanced Pattern: Data Migrations with Stable References

Schema migrations change the database structure. Data migrations transform existing records.

For example, we may add a new status field:

status = mapped_column(
    String(20),
    nullable=False,
    server_default="active",
)

Then we may need to convert older status values.

A data migration can use SQL:

from alembic import op


def upgrade():
    op.execute(
        """
        UPDATE users
        SET status = 'inactive'
        WHERE status = 'disabled'
        """
    )

For more complex transformations, use SQLAlchemy Core or a dedicated script.

A migration should not import the current application model and assume it will remain unchanged forever. Application models evolve, but old migration files should remain executable.

Instead, define the table structure needed by the migration using the migration’s own SQLAlchemy objects:

from alembic import op
import sqlalchemy as sa


def upgrade():
    users = sa.table(
        "users",
        sa.column("id", sa.Integer),
        sa.column("status", sa.String),
    )

    op.execute(
        users.update()
        .where(users.c.status == "disabled")
        .values(status="inactive")
    )

This keeps the migration independent of future application model changes.

8. Advanced Pattern: Batch Processing for Large Data Migrations

Updating millions of records in one transaction can create operational problems.

Potential issues include:

  • Long-running transactions

  • Large write-ahead logs

  • Increased replication lag

  • Database lock contention

  • Difficult recovery after failure

For large data transformations, consider a batch process.

A simplified PostgreSQL example can process records in chunks:

WITH batch AS (
    SELECT id
    FROM users
    WHERE status IS NULL
    ORDER BY id
    LIMIT 1000
)
UPDATE users
SET status = 'active'
WHERE id IN (SELECT id FROM batch);

Repeat the operation until no matching rows remain.

For very large datasets, it may be better to run a separate operational backfill job instead of embedding the entire process in a single Alembic migration.

The migration can add the new column, while a separately monitored job fills it. A later migration can enforce NOT NULL after validation.

9. Advanced Pattern: Adding a Non-Nullable Column Safely

Consider adding a new created_at column to a table that already contains millions of rows.

A direct operation might be:

op.add_column(
    "users",
    sa.Column(
        "created_at",
        sa.DateTime(timezone=True),
        nullable=False,
        server_default=sa.func.now(),
    ),
)

This can have different operational effects depending on the database version and the exact default expression.

For a large production table, a safer staged approach is often:

  1. Add the column as nullable.

  2. Deploy code that writes the new value.

  3. Backfill existing records in batches.

  4. Verify that no rows remain null.

  5. Add the NOT NULL constraint.

Example:

def upgrade():
    op.add_column(
        "users",
        sa.Column(
            "created_at",
            sa.DateTime(timezone=True),
            nullable=True,
        ),
    )

After the backfill:

def upgrade():
    op.alter_column(
        "users",
        "created_at",
        nullable=False,
    )

The database-specific locking and validation behavior should be reviewed before applying this to a large table.

10. Advanced Pattern: Creating Indexes Without Blocking Writes

Indexes improve query performance, but creating an index on a large production table may affect write availability.

PostgreSQL supports concurrent index creation:

def upgrade():
    with op.get_context().autocommit_block():
        op.create_index(
            "ix_users_email",
            "users",
            ["email"],
            unique=False,
            postgresql_concurrently=True,
        )

The autocommit_block() is important because PostgreSQL does not allow CREATE INDEX CONCURRENTLY inside a regular transaction block.

There are trade-offs:

  • Concurrent index creation takes longer.

  • It can fail if conflicting conditions occur.

  • A failed concurrent build may leave an invalid index that needs cleanup.

Review the PostgreSQL documentation and migration state before retrying a failed index migration.

For a unique index, first check whether duplicate values already exist. A unique index cannot be created successfully if the data violates the uniqueness requirement.

11. Advanced Pattern: Handling Migration Branches

In a team environment, two developers may create migrations from the same base revision.

For example:

          ┌── Migration A
Base ──────┤
          └── Migration B

This creates multiple heads.

Check the current heads:

alembic heads

If the branches are compatible, create a merge revision:

alembic merge -m "merge migration branches" <revision_a> <revision_b>

The merge migration usually has no schema operations. Its purpose is to connect the revision graph.

After creating it, review the history:

alembic history

Do not merge migration branches blindly if both migrations modify the same table or depend on one another. Resolve the logical ordering and test the resulting upgrade path.

12. Advanced Pattern: Reversible Migrations

Alembic supports upgrade() and downgrade() functions.

A reversible migration might create a table:

def upgrade():
    op.create_table(
        "audit_logs",
        sa.Column("id", sa.Integer(), primary_key=True),
        sa.Column("action", sa.String(100), nullable=False),
    )


def downgrade():
    op.drop_table("audit_logs")

You can roll back one revision:

alembic downgrade -1

Or move to a specific revision:

alembic downgrade <revision_id>

But not every migration can be safely reversed.

For example, dropping a column destroys data. A downgrade that recreates the column cannot restore the deleted values.

Before writing a downgrade, ask:

  • Does this operation lose data?

  • Can the original data be reconstructed?

  • Will the downgrade work with the current application version?

  • Is rollback safer than deploying a forward fix?

In production, a forward corrective migration may be safer than trying to reverse a destructive change.

13. Test Migrations Before Production

Migration testing should be part of the deployment workflow.

A useful CI process is:

  1. Start a clean database.

  2. Run all migrations from the base revision.

  3. Verify the resulting schema.

  4. Run application tests.

  5. Test upgrades from a supported previous schema version.

  6. Test downgrades where rollback is part of the release strategy.

A simple command to apply all migrations is:

alembic upgrade head

To create a new migration and review its generated operations:

alembic revision --autogenerate -m "describe change"

Always inspect the generated file before committing it.

Look for:

  • Unexpected table or column drops

  • Incorrect nullability changes

  • Missing indexes or constraints

  • Unintended type conversions

  • Data transformations that assume every row is valid

14. Production Migration Deployment Strategy

A common mistake is running migrations independently from every application replica during startup.

This can create race conditions if multiple instances attempt to apply migrations at the same time.

A more controlled deployment process is:

Build application
       ↓
Run migration job once
       ↓
Verify migration success
       ↓
Deploy compatible application version
       ↓
Monitor application and database

For rolling deployments, use backward-compatible migrations whenever possible.

The migration job should have:

  • Access to the database

  • A clear timeout and failure policy

  • Logs and monitoring

  • A single controlled execution path

  • A tested recovery plan

The exact deployment setup depends on whether you use Docker Compose, Kubernetes, a managed container platform, or a CI/CD pipeline.

15. Common Alembic Migration Problems

Problem

Possible cause

What to check

Autogenerate detects no changes

Models are not imported

Verify target_metadata and model imports

Migration fails on NOT NULL

Existing rows contain null values

Backfill data before adding the constraint

Duplicate migration heads

Parallel development branches

Use alembic heads and merge revisions carefully

Index creation blocks writes

Regular index creation on a large table

Consider PostgreSQL concurrent index creation

Downgrade loses data

Destructive schema operation

Prefer a forward fix or plan data preservation

Migration works locally but fails in production

Different data, permissions, or database behavior

Test against production-like data and settings

Conclusion

Alembic and SQLAlchemy provide a strong foundation for managing database schema changes in Python applications. But reliable migrations require more than generating scripts from models.

The most useful advanced patterns are:

  • Expand and contract migrations for rolling deployments

  • Separate data migrations from schema changes when appropriate

  • Batch large data transformations

  • Add constraints only after validating existing data

  • Create indexes with database-specific operational considerations

  • Manage migration branches deliberately

  • Test migration paths in CI

  • Run production migrations through a controlled deployment job

The goal is not simply to make a migration pass. The goal is to evolve the database without breaking the application, losing important data, or causing avoidable downtime.

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘