Writing Data Backfill Scripts With LLMs in November 2026: Walk the Table in Small Primary-Key Batches, Make Every Batch Safe to Rerun, and Throttle Before the Database Notices
A backfill is the unglamorous half of most schema changes. You add a column, a new table, or a normalized copy of some messy field, and then every existing row needs a value. Ask an LLM to "write a script to fill in the new column" and you will usually get one line of SQL: UPDATE orders SET total_cents = ROUND(total * 100);. On a table with a few thousand rows, that is fine. On a table with tens of millions of rows that production traffic is reading and writing, that single statement can hold row locks for minutes, bloat the table, flood replication, and leave you with no way to tell how far it got when you cancel it.
This post walks through how to get an LLM to write backfill scripts you can run against a live database without holding your breath. The examples use PostgreSQL and Python with psycopg, but the rules carry over to MySQL and to whatever language your team uses.
What makes a backfill different from a migration
A schema migration changes the shape of the data: add a column, add an index, create a table. A backfill changes the data itself, row by row, usually after the migration has shipped. Keeping them separate matters for three reasons:
- Size. A migration usually finishes in seconds. A backfill can run for hours, and it should be able to stop and resume without starting over.
- Concurrency. While the backfill runs, the application keeps writing. New rows arrive, and old rows get updated. The script has to cooperate with that traffic, not race it.
- Load. Every row you rewrite creates write-ahead log, replication traffic, and (in PostgreSQL) a dead row version for vacuum to clean up. Done too fast, a backfill becomes the outage it was meant to prevent.
Tell the model this up front. A prompt that says "this table has about 40 million rows, it takes live writes, and we have one read replica" produces very different code from "fill in the new column."
A bucket brigade moves a lot of water one manageable bucket at a time. A good backfill moves rows the same way. Image: Bucket Brigade by David Brossard, CC BY-SA 2.0, via Wikimedia Commons.
Step 1: Make new writes correct before you touch old rows
The most common logic bug in generated backfills is a gap. The script fills in every row that exists when it starts, but the application code that writes the new column ships after the backfill, so rows created in between end up empty. The fix is an order of operations, and you should spell it out in your prompt:
- Ship the schema change (new nullable column, or new table).
- Ship application code that writes the new value for every insert and update.
- Run the backfill for older rows.
- Verify that no rows are missing the value.
- Only then add the
NOT NULLconstraint, switch reads to the new column, or drop the old one.
If the model proposes a single deploy that adds the column, backfills it, and makes it NOT NULL in one migration, push back. That is the approach that locks a big table.
Step 2: Walk the table in primary-key batches, not OFFSET pages
Ask for batches of a fixed size, keyed on the primary key, with a remembered position. Generated code often reaches for LIMIT 1000 OFFSET n, which gets slower as n grows because the database still has to step past every skipped row. It also skips or repeats rows when other writes shift the order.
Keyset batching avoids both problems. Each batch picks up where the last one ended:
UPDATE orders
SET total_cents = ROUND(total * 100)
WHERE id IN (
SELECT id FROM orders
WHERE id > %(last_id)s
AND total_cents IS NULL
ORDER BY id
LIMIT %(batch_size)s
)
RETURNING id;
The script keeps the largest returned id as the next last_id. Each statement touches at most one batch of rows, commits, and releases its locks. A batch size between a few hundred and a few thousand rows is a reasonable starting point, but the right number depends on row width, indexes, and your hardware, so make it a command-line flag rather than a constant the model picks for you.
One caveat to check: if the table's primary key is a random UUID, ORDER BY id still works for keyset batching, but the rows in each batch are scattered across the table rather than physically close together. That is usually fine. If it is too slow, ask the model to batch on an indexed, increasing column such as created_at combined with id as a tie-breaker.
Step 3: Make every batch safe to run twice
A long backfill will be interrupted. Someone presses Ctrl+C, a deploy restarts the worker, a lock timeout fires. The script must be safe to run again from any point. Two habits get you there:
- Filter on "not done yet." The
AND total_cents IS NULLcondition above means a rerun only touches rows that still need work. If the value can legitimately beNULLafter the backfill, use a different marker, such as comparing the new value with the computed one, or a separatebackfilled_atcolumn. - Store a checkpoint. Write the last finished
idto a small table or file after each committed batch. On restart, read it back. The filter keeps things correct even if the checkpoint is stale; the checkpoint just saves time.
Never let the model "improve" the transform by making it non-deterministic, such as calling now() or a random function inside the update. Running the same batch twice should produce the same result.
Steady, repeatable batches beat one heroic push, whether you are filling sandbags or rows. Image: FEMA - 43190 - Sandbag filling operation in North Dakota by Michael Rieger (FEMA), public domain, via Wikimedia Commons.
Step 4: Throttle, and set timeouts on every statement
The fastest backfill is rarely the right one. You want it to finish without anyone noticing. Ask the model for these controls:
- A pause between batches, configurable from the command line, so you can slow down without editing code.
lock_timeoutandstatement_timeouton the session. In PostgreSQL,SET lock_timeout = '2s'makes a batch give up instead of queueing behind a long transaction, andSET statement_timeout = '30s'stops a batch that runs far longer than expected. The script should catch these errors, wait, and retry the same batch.- A replica lag check if you have read replicas. On a PostgreSQL streaming replica,
SELECT now() - pg_last_xact_replay_timestamp()gives a rough idea of how far behind it is (it reads high when the primary is idle, so treat it as a ceiling). On MySQL 8,SHOW REPLICA STATUSreportsSeconds_Behind_Source. If lag passes your threshold, the script sleeps until it recovers. - A stop file or signal handler so an operator can ask for a clean stop after the current batch.
A complete script to start from
Here is the shape you are aiming for. Paste something like it into your prompt as the pattern to follow, and ask the model to adapt only the transform and table names:
import argparse, os, time, signal
import psycopg
stop = False
def request_stop(*_):
global stop
stop = True
signal.signal(signal.SIGINT, request_stop)
signal.signal(signal.SIGTERM, request_stop)
BATCH_SQL = """
UPDATE orders SET total_cents = ROUND(total * 100)
WHERE id IN (
SELECT id FROM orders
WHERE id > %(last_id)s AND total_cents IS NULL
ORDER BY id LIMIT %(batch_size)s
)
RETURNING id
"""
def main():
p = argparse.ArgumentParser()
p.add_argument("--batch-size", type=int, default=1000)
p.add_argument("--sleep", type=float, default=0.2)
p.add_argument("--start-id", type=int, default=0)
p.add_argument("--dry-run", action="store_true")
a = p.parse_args()
last_id, total = a.start_id, 0
with psycopg.connect(os.environ["DATABASE_URL"]) as conn:
conn.execute("SET lock_timeout = '2s'")
conn.execute("SET statement_timeout = '30s'")
conn.commit()
while not stop:
try:
rows = conn.execute(BATCH_SQL,
{"last_id": last_id, "batch_size": a.batch_size}).fetchall()
if a.dry_run:
conn.rollback()
else:
conn.commit()
except (psycopg.errors.LockNotAvailable,
psycopg.errors.QueryCanceled) as e:
conn.rollback()
print(f"retrying after {type(e).__name__}")
time.sleep(5)
continue
if not rows:
break
last_id = max(r[0] for r in rows)
total += len(rows)
print(f"last_id={last_id} updated={total}", flush=True)
if a.dry_run:
break
time.sleep(a.sleep)
print(f"done: last_id={last_id} total={total} stopped_early={stop}")
if __name__ == "__main__":
main()
Things worth noticing: each batch commits on its own, so a cancel loses at most one batch; the printed last_id doubles as a checkpoint you can pass back with --start-id; the dry-run mode runs one batch and rolls it back so you can check the SQL and the timing safely; and the stop handler finishes the current batch instead of dying in the middle of it.
Step 5: Verify with a query, not with the script's own count
The script printing "done" proves only that it stopped. Before you add constraints or switch reads, run independent checks:
SELECT count(*) FROM orders WHERE total_cents IS NULL;should return zero (or exactly the number of rows you expect to stay empty).- Spot-check the transform:
SELECT id, total, total_cents FROM orders WHERE total_cents <> ROUND(total * 100) LIMIT 20;should return nothing. - Pick a handful of real records you know well and look at them by hand. Edge cases like negative amounts, zero, very large values, and legacy rows with odd formats are where transforms break.
Then add the constraint in a way that does not lock the table for a full scan. In PostgreSQL 12 and later, you can add a CHECK (total_cents IS NOT NULL) NOT VALID constraint, run VALIDATE CONSTRAINT separately, and then SET NOT NULL, which can use the validated check instead of scanning again. Ask the model to write that sequence explicitly and confirm it against the documentation for your exact version.
A prompt template that works
Here is a prompt you can adapt. The details about size, traffic, and replicas are what change the output most:
Write a Python backfill script using psycopg 3 for PostgreSQL 16.
Table: orders (about 40 million rows, primary key id bigint,
live inserts and updates all day, one streaming read replica).
Goal: set total_cents = ROUND(total * 100) where total_cents IS NULL.
The application already writes total_cents for new and updated rows.
Requirements:
- keyset batches on id, batch size and sleep as CLI flags
- each batch in its own transaction
- safe to rerun: only touch rows where total_cents IS NULL
- lock_timeout 2s and statement_timeout 30s, retry on those errors
- pause while replica lag is above 10 seconds
- print last_id after each batch and accept --start-id to resume
- --dry-run that runs one batch and rolls it back
- clean stop on SIGINT/SIGTERM after the current batch
Do not use OFFSET. Do not run a single UPDATE over the whole table.
After the script, list the SQL I should run to verify it finished.
Review checklist before you run it in production
- Is the application already writing the new value for new and changed rows?
- Does every batch commit separately, with a bounded size?
- Does it batch on an indexed key, without
OFFSET? - Will rerunning it from the start produce the same result and skip finished rows?
- Are
lock_timeoutandstatement_timeoutset, with retries on those errors? - Is there a way to slow down or stop it without killing the process mid-batch?
- Have you run it against a recent copy of production data and timed a few batches?
- Do you have independent verification queries ready?
The short version
LLMs are good at writing the transform in a backfill. They are much less reliable about how the backfill behaves on a busy table, because the one-statement answer looks correct and works on a laptop. Tell the model the table size and traffic, ask for primary-key batches with a checkpoint, insist that every batch be safe to repeat, add timeouts and throttling, and check the result with your own queries before you build anything on top of the new data.
Comments
Post a Comment