Backend February 20, 2026

"Lost Time" in Alembic Migrations and the Defensive Migration Strategy

By Kahraman Bayraktar
Editorial NoteThis article was drafted with AI assistance from real engineering problems, debugging sessions, and architectural questions that surfaced during my own software development work. While the underlying experience is real, AI-generated explanations may contain inaccuracies.

Managing database schemas is a standard operation for most of us. In a local environment, you run alembic revision --autogenerate, then alembic upgrade head, and everything works flawlessly. But what if one day your Production (or Staging) database is at the version indicated by your migration file, but physically does not contain those tables or columns?

That is the moment you have come face to face with the infamous database "Drift" problem and hours of Alembic chaos. Today I want to share the war story behind the UndefinedTable error we encountered and the "Defensive Migration" strategy we subsequently developed.

Setting the Scene: A Failed Deploy

It all started on an ordinary Friday when we tried to deploy the Zenis project to the Staging environment on Railway. The pipeline ran, the container spun up, and suddenly that cold-sweat-inducing error log appeared: psycopg2.errors.UndefinedTable: relation "health_metrics" does not exist.

This was impossible. Because the health_metrics table should have been in the database from a migration done weeks ago.

Situation Assessment: We looked at the infamous alembic_version table that Alembic keeps in the database. Version: 5c85ade3019c (meaning the version where the table had already been created, and even file_id added on top of it). The Problem: The database was saying "I'm on step 5", but the table that physically should have been in step 1 was nowhere to be found. Someone had either deleted the table manually, or a synchronization loss (drift) had occurred during database dump/restore operations coming from different environments.

Attempt 1: The Repair Script and "Things Left in the Past"

Our first instinct was to add a "repair file" (123456789abc) at the very beginning. We placed the file right after initial_schema. The thought was: "If the table is missing while Alembic is scanning from the beginning, let it create it."

What Happened? The operation failed. Alembic saw that the database was already at version 5c85... (step 5) and completely skipped our repair file from the past, assuming every ancestor revision had already executed.

Attempt 2: Laying Stones Where You Stepped (The Linked List Trick)

Since Alembic didn't re-run ancestor revisions, we placed our repair file at the exact step where the database stood. We set our file's down_revision value to 5c85..., the current version of the database.

What Happened? The table was created! Alembic saw our file and executed it. But it was too early to rejoice. The migration chain had split in two because other revision files already pointed to 5c85... as their down_revision. We encountered the infamous Git/Alembic nightmare: Multiple heads are present for given argument 'head'.

Different environments (Dev, Stage, Prod) were on different branches of the graph. Stage was patched, while Prod sat at a different revision. Merging stage and main turned the revision graph into a tangle.

Attempt 3: Fixing the Chain and the Ironic "DuplicateColumn" Error

We resolved the Git conflicts, linearized the migration chain, and prepared everything to run sequentially.

What Happened? This time we hit psycopg2.errors.DuplicateColumn. Why? Because our repair script had already included later columns (e.g., ref_min, analysis_id) when creating the missing table, and subsequent original migrations in the linear chain tried to op.add_column those exact columns again.

The Reliable Solution: Idempotent "Defensive" Migrations

The fundamental reason for all this chaos was that our Alembic migrations were acting blindly on revision history, assuming "If I am at revision X, the physical schema must match revision X." When external databases experience manual hotfixes or partial restores, that assumption breaks.

Leaving blind assumptions behind, we made schema-mutating migrations idempotent and data-driven using SQLAlchemy's runtime inspect() reflection API:

import sqlalchemy as sa
from alembic import op

def upgrade() -> None:
    # 1. Inspect what physically exists in the target database right now:
    bind = op.get_bind()
    inspector = sa.inspect(bind)
    tables = inspector.get_table_names()

    # 2. SAFEGUARD: If the table is missing due to schema drift, create its base definition
    if 'health_metrics' not in tables:
        op.create_table('health_metrics', ...)

    # 3. Idempotent Column Addition: Skip if the column already exists
    columns = {c['name'] for c in inspector.get_columns('health_metrics')}
    if 'analysis_id' not in columns:
        op.add_column('health_metrics', sa.Column('analysis_id', sa.Integer()))

    # 4. Idempotent Constraint (FK) Deletion: Drop only if physically present
    fks = inspector.get_foreign_keys('health_metrics')
    fk_names = {fk['name'] for fk in fks if fk['name']}
    if 'health_metrics_file_id_fkey' in fk_names:
        op.drop_constraint('health_metrics_file_id_fkey', 'health_metrics', type_='foreignkey')

Conclusion: A Resilient Pipeline

With runtime schema inspection in place, deployments across drifted environments stabilized immediately:

  • Prod (Main) detected the missing table, created it cleanly, and skipped re-adding columns that were already present.
  • Stage already had the repaired table, skipped table creation, and cleanly reconciled the remaining foreign-key state without crashing.
  • Dev (Local) was already aligned and passed through the idempotent checks normally.

Lesson Learned

Migration tools like Alembic treat the alembic_version pointer as the single source of truth—which holds true only when every environment evolves strictly through immutable CI/CD migrations. Once real-world drift occurs (dump/restore mismatches, manual out-of-band SQL hotfixes, or diverged branches), blind DDL statements fail hard.

To be clear: duplicating full create_table definitions across everyday migrations would violate DRY; the permanent cure for schema drift is locking down manual database access and enforcing automated CI/CD migration pipelines. However, when reconciling drifted environments or writing high-risk DDL transitions (equivalent to ADD COLUMN IF NOT EXISTS or DROP CONSTRAINT IF EXISTS), inspecting what physically exists via sa.inspect(bind) turns fragile migrations into idempotent, self-healing operations.