Moving Data, Not Just Columns
Give every existing row a value for the new slug column with a batched, idempotent backfill — first inside the migration, then as a standalone job that commits per batch.
Contentsand lesson path
On this page
- The task
- Step 1: expand — the nullable column
- Step 2: the backfill migration, batched and idempotent
- Step 3: the standalone backfill, committing per batch
- Data-migration pitfalls
- Check your understanding
- Apply it
- Review prompt
Lessons of Database Schema Migrations
- Why Schemas Need Version Control Concept · 15 min
- The Alembic Loop: Autogenerate, Review, Apply Worked example · 25 min
- Moving Data, Not Just Columns Worked example · 20 min
- Zero-Downtime Changes with Expand and Contract Concept · 25 min
- Lab: Ship a Column Rename Through CI Without Downtime Lab · 30 min
- Check: Is This Migration Safe to Ship? Knowledge check · 8 questions
What you will learn
- Write a data migration (backfill) that is idempotent and processes rows in batches.
Prerequisites: Data Access with SQLAlchemy
01. The task
A migration that changes the schema is half a change. The reading-list API now wants stable URLs like /books/the-pragmatic-programmer, so every book needs a slug derived from its title. The 60 books that already exist do not have one, and they never will unless a migration moves the data: ALTER TABLE can add the column, but filling it is our job. That second half is a backfill: a data migration that computes or copies values for existing rows.
A backfill on a live service has three requirements that a plain UPDATE does not meet. It must be batched, so no single transaction holds locks on millions of rows until it commits, or hands replicas and checkpoints one concentrated burst of write-ahead log (the total volume is about the same; batching spreads it out). It must be idempotent, so a rerun after a crash skips the work already done instead of repeating it. And it must be honest about where it runs, because a backfill that takes six hours does not belong inside a deploy that blocks on alembic upgrade head.
This worked example continues the project from the Alembic loop lesson: PostgreSQL 17 on port 55434, and the 60 books from its seed step (12 titles, 5 copies each, titled like Refactoring (copy 1), which is why the slugs below end in -copy-1).
02. Step 1: expand — the nullable column
The model gains slug: Mapped[str | None], and autogenerate drafts the schema half. Nothing is written yet; the column simply exists, NULL for every row:
$ alembic revision --autogenerate -m 'expand add books.slug'
Detected added column 'books.slug'
$ alembic upgrade head
Running upgrade 67ead21a23e9 -> 880b472c369d, expand add books.slugKeeping the DDL and the data in separate revisions is deliberate. Each step can then be reviewed, applied and, if needed, repeated on its own — a shape the expand-and-contract lesson generalises.
03. Step 2: the backfill migration, batched and idempotent
Create the next revision empty — alembic revision -m "backfill books.slug in batches", no --autogenerate, because there is no schema change to detect — and write the data half by hand. op.get_bind() returns the connection the migration is running on; query and update through it with SQL text, not the ORM:
import re
from alembic import op
from sqlalchemy import text
BATCH = 20
def _slug(title: str) -> str:
"""Lower-case words joined by hyphens; kept local to this migration."""
return re.sub(r"[^a-z0-9]+", "-", title.lower()).strip("-")
def upgrade() -> None:
"""Set slug from title for rows without one, in primary-key batches."""
conn = op.get_bind()
batches = done = 0
while True:
rows = conn.execute(text(
"SELECT id, title FROM books "
"WHERE slug IS NULL ORDER BY id LIMIT :limit"),
{"limit": BATCH},
).all()
if not rows:
break
for book_id, title in rows:
conn.execute(
text("UPDATE books SET slug = :slug WHERE id = :id"),
{"slug": _slug(title), "id": book_id},
)
done += len(rows)
batches += 1
print(f"backfill: {done} rows in {batches} batches of up to {BATCH}")
def downgrade() -> None:
"""Data only: forget the slugs; the expand revision drops the column."""
op.get_bind().execute(text("UPDATE books SET slug = NULL"))Three details do the work. WHERE slug IS NULL selects only unfinished rows, so a rerun finds nothing to do. ORDER BY id LIMIT :limit takes the next slice in primary-key order, which keeps each statement small and lets the primary-key index serve the scan. The two work together: because finished rows drop out of slug IS NULL, the same query returns a new slice on every pass and an empty result when the work is done. And the loop prints what it did, because a silent migration is unauditable:
$ alembic upgrade head
Running upgrade 880b472c369d -> 718197e7159c, backfill books.slug in batches
backfill: 60 rows in 3 batches of up to 20readinglist=# select id, slug from books order by id limit 3;
id | slug
----+----------------------------------------------
1 | designing-data-intensive-applications-copy-1
2 | the-pragmatic-programmer-copy-1
3 | refactoring-copy-1
(3 rows)By default Alembic runs the whole alembic upgrade invocation — every pending revision — in one transaction (set transaction_per_migration=True in env.py for one transaction per revision), so batches inside a migration bound memory, not lock time: every row updated stays locked until the last revision finishes. You can prove the loop is re-runnable with the developer round trip — alembic downgrade -1 (the downgrade sets slug back to NULL) then alembic upgrade head — and watch it process 60 rows again. But remember from the first lesson that Alembic runs each revision at most once per database; a rerun through Alembic is not the scenario that hurts. The scenario that hurts is the job being interrupted halfway and started again, which is the standalone version below.
04. Step 3: the standalone backfill, committing per batch
When the table is large, the backfill moves out of the deploy path: the migration does DDL only, and a separate command — a script, a job, a python -m app.backfill — moves the rows and commits after every batch. A crash then loses one batch, not everything, and the WHERE slug IS NULL guard means the restart skips finished rows. This is the version to write when the copy takes minutes or hours. It uses the same _slug helper, copied into the script rather than imported from the migration. Here is the whole job:
"""Backfill books.slug outside the deploy: one short transaction per batch."""
import re
from sqlalchemy import create_engine, text
BATCH = 20
engine = create_engine("postgresql+psycopg://lab:lab@localhost:55434/readinglist")
def _slug(title: str) -> str:
"""Same rule as the migration, copied here rather than imported."""
return re.sub(r"[^a-z0-9]+", "-", title.lower()).strip("-")
with engine.connect() as conn:
pending = conn.execute(
text("SELECT id FROM books WHERE slug IS NULL ORDER BY id")
).scalars().all()
print(f"rows needing a slug: {len(pending)}")
with engine.connect() as conn:
for start in range(0, len(pending), BATCH):
ids = pending[start : start + BATCH]
rows = conn.execute(
text("SELECT id, title FROM books WHERE id = ANY(:ids)"),
{"ids": ids},
).all()
for book_id, title in rows:
conn.execute(
text("UPDATE books SET slug = :slug "
"WHERE id = :id AND slug IS NULL"),
{"slug": _slug(title), "id": book_id},
)
conn.commit() # one short transaction per batch
print(f"batch {start // BATCH + 1}: committed {len(ids)} rows")
print(f"done: {len(pending)} rows")readinglist=# INSERT INTO books (author_id, title)
VALUES (1, 'The Unicorn Project'),
(2, 'Data and the New Economy');
INSERT 0 2
$ python backfill_slug.py # first run
rows needing a slug: 2
batch 1: committed 2 rows
done: 2 rows
$ python backfill_slug.py # rerun after the job "crashed"
rows needing a slug: 0
done: 0 rowsThe second run is the whole argument for idempotency: it found zero pending rows and did no work. This holds because the update is absolute — slug = <computed value>. An update that is relative (credit = credit + 10) or appends to a list is not idempotent: a rerun changes already-finished rows again, and no WHERE guard can tell a "needs doing" row from a "already done" one. If the business change must be relative, give the job its own memory of progress: for example a credited_at timestamp set by the same UPDATE, or a table the job inserts each finished id into, and make the WHERE clause exclude what that memory says is finished.
Prove all three properties before the job touches a shared database, in the same spirit as the testing discipline you already apply to code. Run the backfill against a seeded copy with production-shaped row counts and assert the expected total. Run it a second time and assert the second run reports zero work — that assertion is your idempotency test, and it belongs in the suite so a future edit that breaks the WHERE guard fails in CI rather than at 03:00. And log the counts somewhere you can find them during an incident; "the job printed 4,312 rows in 217 batches, then 0 on the rerun" is the difference between an investigated deploy and a guessed one.
05. Data-migration pitfalls
06. Check your understanding
07. Apply it
Give the backfill the tests it deserves:
- Make the standalone job crashable on purpose: raise after N batches, run it, and confirm a restart finishes the remaining rows without touching finished ones.
- Add a unique constraint on
slugand decide what the backfill should do when two books slug to the same value — skip, suffix, or fail? Write the rule into the job and its log. - Time the job against a seeded table two orders of magnitude larger (a script with
generate_serieswill build you 100,000 books) and record how batch size changes duration and lock time. How locking interacts with concurrent readers is the bridge to transaction isolation.
08. Review prompt
Without looking back: what makes a backfill idempotent, and why does a relative update break that property? Why commit per batch, and why does the WHERE clause need to select unfinished rows rather than all rows? When does a backfill stop belonging inside a migration file, and what is left in the migration when it moves out?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.