Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Lab · 30 min · revision 3

Lab: Ship a Column Rename Through CI Without Downtime

Rename books.title to books.display_title through expand, backfill, online NOT NULL and contract revisions while four app releases keep working, gate the history with alembic check in CI, and rehearse recovery from a backup.

Contentsand lesson path

What you will learn

  • Plan a zero-downtime schema change with the expand-migrate-contract pattern, avoiding long-held table locks.
  • Run migrations as a controlled deploy step and fail CI when models and migrations drift apart.

Prerequisites: Data Access with SQLAlchemy

01. Goal and setup

The product team has decided books.title is ambiguous and must become books.display_title. The table is busy and the service runs several replicas, so a straight ALTER TABLE ... RENAME would break every replica still using the old name. You will ship it as the expand-migrate-contract sequence, prove each intermediate schema with four small "releases" of the service, make the new column mandatory without a long lock, add the CI drift gate from the Alembic loop lesson, and rehearse recovery before the one destructive step.

You need: Docker, Python 3.12, uv and the small models printed below. Versions in this run: Python 3.12.13, SQLAlchemy 2.1.9, Alembic 1.20.1, psycopg 3.3.9, PostgreSQL 17.12 (a supported major; 19 is the newest). Use a throwaway database and delete it afterwards:

Terminal · scratch folder for the whole lab
docker run -d --name rename-pg -e POSTGRES_USER=lab -e POSTGRES_PASSWORD=lab \
  -e POSTGRES_DB=renamelab -p 55434:5432 postgres:17-alpine

uv venv --python 3.12 .venv && source .venv/bin/activate
uv pip install sqlalchemy==2.1.9 alembic==1.20.1 "psycopg[binary]==3.3.9"
alembic init alembic
Edits after alembic init: alembic.ini and alembic/env.py
# alembic.ini, in the [alembic] section
sqlalchemy.url = postgresql+psycopg://lab:lab@localhost:55434/renamelab

# alembic/env.py: replace the line "target_metadata = None" with
import models
target_metadata = models.Base.metadata
Project layout
renamelab/
├── alembic.ini              URL: postgresql+psycopg://lab:lab@localhost:55434/renamelab
├── alembic/env.py           target_metadata = models.Base.metadata
├── alembic/versions/        the revisions this lab creates
├── models.py                moves through three states: v1, transition, final
├── release.py               shared helper of the four releases
├── app_v1.py ... app_v4.py  the four "releases" of the service
├── seed.py                  3 authors, 60 books
└── backup_before_contract.sql

Each app_vN.py stands in for a release of the service: it inserts one book and lists three, using the columns that release knows about. They use raw SQL, so an old release fails loudly the moment the schema stops supporting it, as a surviving old replica would. They share one helper that reads DATABASE_URL; step 6 uses it to point release 4 at a restored copy. seed.py writes 60 books as five copies of twelve titles, and models.py starts as an Author/Book pair smaller than the one in the models lesson.

Python · models.py, release 1 state
from sqlalchemy import ForeignKey, String
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column


class Base(DeclarativeBase):
    pass


class Author(Base):
    __tablename__ = "authors"

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


class Book(Base):
    __tablename__ = "books"

    id: Mapped[int] = mapped_column(primary_key=True)
    author_id: Mapped[int] = mapped_column(ForeignKey("authors.id"))
    title: Mapped[str] = mapped_column(String(200))
Python · release.py
"""Shared by app_v1.py ... app_v4.py: one insert, then the three newest books."""
import os

import psycopg

URL = os.environ.get(
    "DATABASE_URL", "postgresql+psycopg://lab:lab@localhost:55434/renamelab"
).replace("postgresql+psycopg://", "postgresql://")  # psycopg wants plain URLs


def release(label: str, insert_sql: str, title: str, read_col: str) -> None:
    with psycopg.connect(URL) as conn:
        conn.execute(insert_sql, {"t": title})
        rows = conn.execute(
            f"SELECT id, {read_col} FROM books ORDER BY id DESC LIMIT 3"
        ).fetchall()
        count = conn.execute("SELECT count(*) FROM books").fetchone()[0]
    print(label.format(count=count))
    for book_id, text in rows:
        print(f"  {book_id}: {text}")
Python · app_v1.py ... app_v4.py (four files, one per comment)
# app_v1.py
from release import release

release("v1 list (reads title):",
        "INSERT INTO books (author_id, title) VALUES (1, %(t)s)",
        "The Unicorn Project", "title")

# app_v2.py
from release import release

release("v2 list (dual-writes, still reads title):",
        "INSERT INTO books (author_id, title, display_title)"
        " VALUES (2, %(t)s, %(t)s)",
        "Data and the New Economy", "title")

# app_v3.py
from release import release

release("v3 list (reads display_title, still dual-writes):",
        "INSERT INTO books (author_id, title, display_title)"
        " VALUES (3, %(t)s, %(t)s)",
        "Blink", "display_title")

# app_v4.py
from release import release

release("v4 list (display_title only), table now has {count} rows:",
        "INSERT INTO books (author_id, display_title) VALUES (1, %(t)s)",
        "The Deadline", "display_title")
Python · seed.py
from sqlalchemy import create_engine, text

from release import URL

TITLES = [
    "Designing Data-Intensive Applications", "The Pragmatic Programmer",
    "Refactoring", "Accelerate", "Team Topologies", "Site Reliability Engineering",
    "Clean Architecture", "Database Internals", "The Phoenix Project",
    "Working Effectively with Legacy Code", "Release It!", "Observability Engineering",
]

engine = create_engine(URL.replace("postgresql://", "postgresql+psycopg://"))
with engine.begin() as conn:
    conn.execute(text("INSERT INTO authors (name) VALUES ('A'), ('B'), ('C')"))
    for copy in range(1, 6):  # 12 titles x 5 copies = 60 books
        for i, title in enumerate(TITLES):
            conn.execute(
                text("INSERT INTO books (author_id, title) VALUES (:a, :t)"),
                {"a": i % 3 + 1, "t": f"{title} (copy {copy})"},
            )
print("seeded 3 authors, 60 books")

02. Step 1: baseline, seed, release 1

Terminal
alembic revision --autogenerate -m "reading list baseline"
alembic upgrade head
python seed.py
python app_v1.py
Expected output (INFO prefixes, sequence and plugin notices trimmed; revision ids differ per run)
Detected added table 'authors'
Detected added table 'books'
Running upgrade  -> 99dcf52f4ba0, reading list baseline
seeded 3 authors, 60 books
v1 list (reads title):
  61: The Unicorn Project
  60: Observability Engineering (copy 5)
  59: Release It! (copy 5)

Release 1 writes and reads title, and everything works. The baseline is committed; from here the history only grows.

03. Step 2: expand — both columns, one revision

Move models.py to the transition state: both columns exist, and both are nullable. Dropping the NOT NULL on title matters: the final release stops writing title, and a NOT NULL column nobody fills would reject every insert. Autogenerate sees both differences:

Python · models.py, transition state
    # transition models: title stays but stops being mandatory;
    # display_title is the new column, empty until the backfill runs
    title: Mapped[str | None] = mapped_column(String(200))
    display_title: Mapped[str | None] = mapped_column(String(200))
Expected output (INFO prefixes, sequence and plugin notices trimmed; revision ids differ per run)
$ alembic revision --autogenerate -m "expand add display_title"
Detected added column 'books.display_title'
Detected NULL on column 'books.title'
$ alembic upgrade head
Running upgrade 99dcf52f4ba0 -> 3742e615a10b, expand add display_title
$ alembic check
No new upgrade operations detected.
Expected output · old and new release side by side
$ python app_v1.py        # the old release, unchanged
v1 list (reads title):
  62: The Unicorn Project
  61: The Unicorn Project
  60: Observability Engineering (copy 5)
$ python app_v2.py        # new release: writes both columns
v2 list (dual-writes, still reads title):
  63: Data and the New Economy
  62: The Unicorn Project
  61: The Unicorn Project

This is the N-1 window working: the schema serves the release before the change and the release after it. Release 2 dual-writes — every new book gets both columns — so that a rollback to release 1 loses nothing.

04. Step 3: migrate — the batched backfill

Create the backfill with alembic revision -m "migrate backfill" and write it by hand, in the pattern of the backfill lesson but with batches of 25: select ids where display_title IS NULL in primary-key order, copy title into display_title, print the totals. Keep the generated header, add the text import, and replace both functions:

Python · alembic/versions/<rev>_migrate_backfill.py, below the header
from sqlalchemy import text  # add to the generated imports

BATCH = 25


def upgrade() -> None:
    conn = op.get_bind()
    batches = done = 0
    while True:
        ids = conn.execute(text(
            "SELECT id FROM books WHERE display_title IS NULL"
            " ORDER BY id LIMIT :limit"), {"limit": BATCH}).scalars().all()
        if not ids:
            break
        conn.execute(text("UPDATE books SET display_title = title"
                          " WHERE id = ANY(:ids)"), {"ids": ids})
        done += len(ids)
        batches += 1
    print(f"backfill: {done} rows in {batches} batches of up to {BATCH}")


def downgrade() -> None:
    pass  # the copied values can stay: title still holds the originals

Apply it, then deploy release 3 (reads the new column, still dual-writes) and release 4 (touches only display_title):

Expected output (INFO prefixes, sequence and plugin notices trimmed; revision ids differ per run)
$ alembic upgrade head
Running upgrade 3742e615a10b -> dfaea8651715, migrate backfill
backfill: 62 rows in 3 batches of up to 25
$ python app_v3.py
v3 list (reads display_title, still dual-writes):
  64: Blink
  63: Data and the New Economy
  62: The Unicorn Project
$ python app_v4.py
v4 list (display_title only), table now has 65 rows:
  65: The Deadline
  64: Blink
  63: Data and the New Economy

The backfill processed 62 of the 63 rows the table held at that moment: row 63, written by release 2, already had display_title, and the IS NULL guard skipped it. And release 4 works before the contract, because the expand step made title optional; that is what the transition state in models.py was for. That is fine on 63 rows; on a busy table, use the committing job from the backfill lesson, because one migration transaction keeps every updated row locked until it commits.

05. Step 4: make display_title mandatory without a long lock

The final model declares display_title: Mapped[str], so autogenerate will emit ALTER COLUMN display_title SET NOT NULL. On its own, that statement scans every row for a NULL under an ACCESS EXCLUSIVE lock that blocks all reads and writes: harmless on 65 rows, an outage on millions. The same result with only short locks takes three statements:

  1. ADD CONSTRAINT ... CHECK (display_title IS NOT NULL) NOT VALID. Still ACCESS EXCLUSIVE, but with no scan it lasts only as long as a catalogue update. Every new insert and update must now pass the check; existing rows are not yet trusted.
  2. VALIDATE CONSTRAINT, in a separate transaction. It scans the table under SHARE UPDATE EXCLUSIVE, which lets reads and writes continue.
  3. SET NOT NULL, in the contract. Since PostgreSQL 12 it skips its own scan when a valid CHECK proves there are no NULLs.

Locks are held until commit, so if steps 1 and 2 share a transaction, step 2 scans under the ACCESS EXCLUSIVE lock of step 1. Alembic's default env.py runs all pending revisions in one transaction; tell it to commit after each:

Python · alembic/env.py, inside run_migrations_online()
        context.configure(
            connection=connection,
            target_metadata=target_metadata,
            transaction_per_migration=True,  # commit after each revision
        )
Python · upgrade()/downgrade() of two hand-written revisions
# alembic revision -m "tighten add not-null check"
def upgrade() -> None:
    # ACCESS EXCLUSIVE, but only for a catalog update: NOT VALID skips the scan
    op.execute("SET LOCAL lock_timeout = '2s'")
    op.execute(
        "ALTER TABLE books ADD CONSTRAINT books_display_title_nn"
        " CHECK (display_title IS NOT NULL) NOT VALID"
    )


def downgrade() -> None:
    op.drop_constraint("books_display_title_nn", "books", type_="check")


# alembic revision -m "tighten validate check"
def upgrade() -> None:
    # scans every row, but under SHARE UPDATE EXCLUSIVE: reads and writes go on
    op.execute("ALTER TABLE books VALIDATE CONSTRAINT books_display_title_nn")


def downgrade() -> None:
    pass  # validation changed no schema or data

Apply both, then check that release 1 (which never writes display_title) is refused and that PostgreSQL accepts the check as proof. dryrun.sql rehearses SET NOT NULL in a rolled-back transaction, with client_min_messages = debug1 so PostgreSQL says how it verified the column:

SQL · dryrun.sql
SELECT conname, convalidated FROM pg_constraint
 WHERE conname = 'books_display_title_nn';
BEGIN;  -- rehearsal only: see how SET NOT NULL will prove its rule
SET LOCAL client_min_messages = debug1;
ALTER TABLE books ALTER COLUMN display_title SET NOT NULL;
ROLLBACK;
Expected output (INFO prefixes and traceback trimmed, long lines wrapped; revision ids differ per run)
$ alembic upgrade head
Running upgrade dfaea8651715 -> 46085cf2699e, tighten add not-null check
Running upgrade 46085cf2699e -> a90697c3814b, tighten validate check
$ python app_v1.py
psycopg.errors.CheckViolation: new row for relation "books" violates check
                               constraint "books_display_title_nn"
DETAIL:  Failing row contains (66, 1, The Unicorn Project, null).
$ docker exec -i rename-pg psql -U lab -d renamelab < dryrun.sql
        conname         | convalidated 
------------------------+--------------
 books_display_title_nn | t
(1 row)

BEGIN
SET
DEBUG:  existing constraints on column "books.display_title" are sufficient
        to prove that it does not contain nulls
ALTER TABLE
ROLLBACK

Release 1 is refused because a NOT VALID check still applies to every new row, so this step, like the backfill, waits until no release older than 2 is running. The DEBUG line is the proof: without the check, the same rehearsal prints verifying table "books", a full scan under ACCESS EXCLUSIVE. SET LOCAL lock_timeout makes a statement give up after two seconds instead of queueing traffic behind it. (The refused insert used up id 66.)

06. Step 5: backup, then contract

Terminal · restore point before the destructive step
docker exec rename-pg pg_dump -U lab renamelab > backup_before_contract.sql

Now move models.py to the final state — display_title: Mapped[str], no title at all — and run alembic revision --autogenerate -m "contract drop title". It detects NOT NULL on column 'books.display_title' and removed column 'books.title'. Review both halves. In upgrade(), add the lock timeout and drop the helper check after SET NOT NULL has used it. The generated downgrade() would re-add title as an empty column, which is not a rollback, it is a lie; make the irreversibility explicit instead:

Python · the reviewed contract revision (import sqlalchemy as sa is generated)
def upgrade() -> None:
    op.execute("SET LOCAL lock_timeout = '2s'")
    # no table scan: the validated CHECK already proves there are no NULLs
    op.alter_column("books", "display_title",
                    existing_type=sa.VARCHAR(length=200), nullable=False)
    op.drop_constraint("books_display_title_nn", "books", type_="check")
    op.drop_column("books", "title")


def downgrade() -> None:
    # Destructive: re-adding books.title cannot bring its data back.
    # Recover forward from backup_before_contract.sql instead.
    raise NotImplementedError(
        "title data was dropped; restore the pre-contract backup"
    )
Expected output (traceback middles trimmed; revision ids differ per run)
$ alembic upgrade head
Running upgrade a90697c3814b -> 477720ca73e8, contract drop title
$ python app_v4.py
v4 list (display_title only), table now has 66 rows:
  67: The Deadline
  65: The Deadline
  64: Blink
$ python app_v1.py
psycopg.errors.UndefinedColumn: column "title" of relation
                            "books" does not exist
$ python app_v3.py
psycopg.errors.UndefinedColumn: column "title" of relation
                            "books" does not exist
$ alembic downgrade -1
NotImplementedError: title data was dropped; restore the
                          pre-contract backup

Release 4 never notices the contract; a surviving release 1 or 3 fails on its first write, because both still use title. That is why the contract runs after the rollout of release 4 has finished, not with it, and why after the contract the only safe application rollback is to release 4. The refused downgrade marks the boundary from the first lesson: going back further means restoring the pre-contract backup (step 6), because reverting the migration cannot conjure dropped data.

07. Step 6: rehearse the recovery

Terminal · restore into an isolated database, never over live data
docker exec rename-pg createdb -U lab renamelab_restore
docker exec -i rename-pg psql -U lab -d renamelab_restore \
  -q < backup_before_contract.sql
docker exec rename-pg psql -U lab -d renamelab_restore -c \
  "select count(*) as books, count(title) as with_title from books;"
DATABASE_URL=postgresql+psycopg://lab:lab@localhost:55434/renamelab_restore \
  python app_v4.py
Expected output (the restore's set_config and setval result rows trimmed)
 books | with_title 
-------+------------
    65 |         64
(1 row)

v4 list (display_title only), table now has 66 rows:
  67: The Deadline
  65: The Deadline
  64: Blink

The restore proves two things: the backup is usable, and release 4 runs against the pre-contract schema. In a real incident you would restore like this, verify, then write a forward migration, never downgrade over live traffic. Note with_title: 64 of 65, as release 4 was already writing rows without title.

08. Step 7: the drift gate in CI

Everything above assumed models and migrations agree. Enforce that in CI: a job that starts a clean database, upgrades to head and runs alembic check. To see the red path, add a column to the model without a migration, run the check, then revert the edit:

Python · models.py, temporary edit (no migration)
from sqlalchemy import ForeignKey, Integer, String

    # ... last line of class Book:
    rating: Mapped[int | None] = mapped_column(Integer)
Expected output (exit code 255; INFO log lines trimmed, long lines wrapped)
$ alembic check
ERROR [alembic.util.messaging] New upgrade operations detected:
    [('add_column', None, 'books', Column('rating', Integer(), table=<books>))]
FAILED: New upgrade operations detected:
    [('add_column', None, 'books', Column('rating', Integer(), table=<books>))]
$ alembic check     # after reverting the model edit
No new upgrade operations detected.

The CI database below listens on port 5432 as user postgres and has no renamelab database, while alembic.ini holds the lab URL. Let env.py take the URL from the environment when one is given:

Python · alembic/env.py, after config = context.config
import os

# CI and restores pass their own database; local runs use alembic.ini.
if url := os.environ.get("DATABASE_URL"):
    config.set_main_option("sqlalchemy.url", url)
YAML · .github/workflows/migrations.yml (illustrative: not run here)
name: migrations
on: pull_request
jobs:
  drift:
    runs-on: ubuntu-latest
    env:  # read by env.py; the service has no renamelab database
      DATABASE_URL: postgresql+psycopg://postgres:lab@localhost:5432/postgres
    services:
      postgres:
        image: postgres:17-alpine
        env:
          POSTGRES_PASSWORD: lab
        ports: ['5432:5432']
        options: >-
          --health-cmd pg_isready --health-interval 5s
          --health-timeout 5s --health-retries 10
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1  # v7.0.1
      - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0  # v7.1.0
        with: { python-version: '3.12' }
      - run: pip install sqlalchemy==2.1.9 alembic==1.20.1 "psycopg[binary]==3.3.9"
      - run: alembic upgrade head
      - run: alembic check

The same gate can run in the deploy pipeline before alembic upgrade head touches a real database. Either way, a schema change without its migration stops the line. In the deploy, migrations run once, as one step before the new release rolls out, not in each replica at startup.

09. Troubleshooting

10. Check your understanding

Practice check · 3 questions

The rename, end to end

Three decisions from the sequence you just shipped.

Q1. Why does release 2 write both title and display_title during the transition?
Q2. A colleague merges the two tighten revisions into one, so ADD CONSTRAINT ... NOT VALID and VALIDATE CONSTRAINT run in the same transaction. What changes on a busy table?
Q3. After the contract drops title, alembic downgrade raises by design. What is the intended recovery?
Practice only: not graded, not saved, not evidence.

11. Apply it: stretch tasks

Take the lab closer to production shape:

  1. Make the backfill crashable: raise an exception after the second batch, and show that a restart finishes the job without duplicating work.
  2. Redo Step 4 on PostgreSQL 18, which stores NOT NULL as a constraint of its own and accepts ADD CONSTRAINT books_display_title_nn NOT NULL display_title NOT VALID followed by VALIDATE CONSTRAINT; the contract then needs neither SET NOT NULL nor a check to drop. Compare the locks each statement takes in pg_locks. Uniqueness has no such route: UNIQUE constraints cannot be NOT VALID, so on a busy table use CREATE UNIQUE INDEX CONCURRENTLY, then ADD CONSTRAINT ... UNIQUE USING INDEX.
  3. Write the deploy runbook in four lines: what runs first (migrations or code), what is verified between phases, who may run the contract, and where the backup lives.

12. Review prompt

Without looking back: what are the revisions of the rename, and what does each one make safe? Why must the expand revision relax the NOT NULL on the old column, and why does the backfill skip rows that dual-writing already filled? Which three statements make the new column NOT NULL without a long lock, and why must the first two commit separately? What does the contract wait for, what does its rewritten downgrade declare, and how does rolling the application back differ from reverting the migration?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check