Database migrations are deceptively dangerous. A one-line schema change that takes milliseconds on your dev laptop can lock a production table for 10 minutes on a 50-million-row dataset — bringing your application to its knees during peak traffic. The problem isn't the migration itself. It's how most teams approach it.

This article covers the patterns that actually work: how to restructure schema changes so they're safe to run against live traffic, with real code for both Python (Alembic) and Go.

Why Naive Migrations Cause Downtime

Most relational databases (Postgres, MySQL) require table-level or row-level locks for certain DDL operations. The worst offenders:

  • ALTER TABLE ... ADD COLUMN NOT NULL without a default → full table rewrite
  • ALTER TABLE ... RENAME COLUMN → schema lock, blocks reads in some engines
  • Adding an index without CONCURRENTLY → table locked for the entire build

PostgreSQL has improved significantly — ADD COLUMN with a stable default is a metadata-only operation in PG 11+. But many operations still require a full table scan, and the moment you add a constraint or modify a column type, you're back in dangerous territory.

The root issue: your application and your migration tool race against each other. While the migration holds a lock, incoming queries queue up. If the migration takes 30 seconds and your connection pool is 50 connections, you've effectively taken down the service.

The Expand-Contract Pattern

The solution is to decompose breaking changes into multiple non-breaking steps. This is called the expand-contract pattern (sometimes called "parallel change"):

  1. Expand: add the new structure alongside the old. Write to both. The app handles both states.
  2. Migrate: backfill data from old to new in batches.
  3. Contract: once fully migrated and deployed, remove the old structure.

Each phase is independently deployable. No phase requires a table lock that blocks reads. The key: at no point does the application depend on a structure that doesn't exist yet.

Implementing a Zero-Downtime Column Rename in Python

Renaming a column is the canonical example. The naive ALTER TABLE users RENAME COLUMN name TO full_name is safe in Postgres but your application code will break the moment it deploys if it references name before the migration runs — or vice versa.

Here's the expand-contract approach with Alembic:

# Phase 1: add new column alongside old from alembic import op import sqlalchemy as sa from sqlalchemy import text def upgrade(): # Add new column, nullable — no lock escalation op.add_column("users", sa.Column("full_name", sa.String(255), nullable=True)) # Backfill in PK-range batches to avoid long-running transactions conn = op.get_bind() max_id = conn.execute(text("SELECT MAX(id) FROM users")).scalar() or 0 batch = 5_000 for low in range(0, max_id + batch, batch): conn.execute(text(""" UPDATE users SET full_name = name WHERE id > :low AND id <= :high AND full_name IS NULL """), {"low": low, "high": low + batch}) conn.commit() def downgrade(): op.drop_column("users", "full_name") 

Deploy your application to write to both columns and read from the new one with a fallback:

# models.py — dual-read/write during migration window class User(Base): __tablename__ = "users" id = sa.Column(sa.Integer, primary_key=True) name = sa.Column(sa.String(255)) # old column, still present full_name = sa.Column(sa.String(255)) # new column @property def display_name(self) -> str: return self.full_name or self.name # fallback during backfill def set_name(self, value: str) -> None: self.name = value # keep writing old for rollback safety self.full_name = value # write new for forward compatibility 

Once every application instance is on the new code and the backfill is confirmed complete, run Phase 3:

# Phase 3: drop old column def upgrade(): op.drop_column("users", "name") def downgrade(): op.add_column("users", sa.Column("name", sa.String(255), nullable=True)) 

This three-step process takes more calendar time (you need a deploy between each phase), but zero seconds of downtime. For tables with more than a few thousand rows, it's the only safe approach.

Handling Large Backfills Without Replication Lag

The batch loop above works, but naive batch updates create their own problems. On a 100M-row table, looping with LIMIT will cause full sequential scans on each iteration. Processing in primary-key ranges is faster and more predictable:

import time def backfill_in_ranges(conn, batch_size: int = 10_000, sleep_ms: int = 75): max_id = conn.execute(text("SELECT MAX(id) FROM users")).scalar() or 0 low = 0 while low <= max_id: result = conn.execute(text(""" UPDATE users SET full_name = name WHERE id > :low AND id <= :high AND full_name IS NULL """), {"low": low, "high": low + batch_size}) conn.commit() low += batch_size # Throttle to give replication a chance to catch up if result.rowcount > 0: time.sleep(sleep_ms / 1000) 

Two adjustments that matter at scale: commit after each batch (not inside a single giant transaction), and add a sleep between batches proportional to your replication lag tolerance. If you have read replicas serving traffic, monitor pg_stat_replication lag and pause the backfill if it climbs above your SLA threshold.

This approach is also audit-friendly: each committed batch is a discrete, recoverable unit. For environments where regulatory compliance requires row-level change tracking, processing in bounded ranges makes reconciliation straightforward.

Index Creation Without Downtime

Adding an index is frequently overlooked as a migration risk. Standard CREATE INDEX acquires a full table lock. The fix in PostgreSQL:

-- Never on production without CONCURRENTLY: CREATE INDEX idx_users_email ON users(email); -- Safe for live traffic: CREATE INDEX CONCURRENTLY idx_users_email ON users(email); 

The CONCURRENTLY option builds the index in multiple passes without holding a table lock, at the cost of slightly longer build time. The catch: it cannot run inside a transaction. In Alembic, you must opt out of the automatic transaction wrapper:

def upgrade(): with op.get_context().autocommit_block(): op.execute( "CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_users_email ON users(email)" ) 

The IF NOT EXISTS guard makes the migration idempotent — safe to retry if it's interrupted mid-build.

Enforcing Migration Order with Go

The expand-contract pattern requires strict sequencing: migrations before code, always. A fast-fail check at startup enforces this in Go:

func checkSchema(db *sql.DB) error { var exists bool err := db.QueryRow(` SELECT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_name = 'users' AND column_name = 'full_name' ) `).Scan(&exists) if err != nil { return fmt.Errorf("schema check: %w", err) } if !exists { return fmt.Errorf("column users.full_name missing — run Phase 1 migration first") } return nil } 

Call this in main() before binding the HTTP server. A startup crash with a clear error message beats a runtime panic at 2 AM. Pair it with a readiness probe in Kubernetes so the deployment stalls rather than routing traffic to instances running against an incompatible schema.

The Takeaway

Zero-downtime migrations are not about clever database tricks — they're about discipline in how you structure schema changes. The expand-contract pattern adds steps, but those steps are each individually safe to deploy.

The practical checklist:

  • Use CONCURRENTLY for every index on production
  • Backfill in PK-range batches, committed individually, with throttling
  • Dual-write during migration windows; never drop columns before the app stops reading them
  • Enforce schema presence at startup with a fast-fail check

For a broader set of database hardening rules — covering access controls, backup verification, and privilege auditing — the free security checklists at AYI NEDJIMI Consultants cover the operational side in detail.

I run AYI NEDJIMI Consultants, a cybersecurity consulting firm. We publish free security hardening checklists — PDF and Excel.