Backfill data without overwhelming production
Use bounded batches, restart safety, and independent validation.
Define the transformation
Write the new invariant and count affected rows before changing data. Decide how nulls, malformed legacy values, and concurrent writes are handled. Deploy code that can read old and new representations while the backfill runs; otherwise users may see half-migrated records.
Process in stable batches
Use a monotonic primary-key cursor, commit each bounded batch, and record the last successful key. Make the update idempotent so a resumed run can overlap safely. Avoid OFFSET on a changing table because inserts or deletes can shift pages. Rate-limit when lock time or replica lag rises.
last_id = 0
while rows := fetch_batch(after_id=last_id, limit=500):
transform_and_commit(rows)
last_id = rows[-1].id
Validate before switching readers
Compare counts, sample transformed values, and inspect exceptional rows separately. A successful script exit is not proof of correctness. Keep an audit of which records were changed and a forward correction strategy. Tighten database constraints only after all writers and readers use the new representation.
Check your understanding
Why is a primary-key cursor safer than OFFSET for a live backfill?
Show explanation
Rows may be inserted or removed during the run. A stable cursor reduces skips and repeats when pages shift.
You can read for free. Create an account to save your progress.
← Previous lesson: Design a stable Python library boundary Next lesson: Budget time across dependent services →Try it at senior level
Design a restartable backfill over a million rows. Show cursor checkpoints, bounded batches, a dry run, and independent validation.
Check your work
A crash can resume without skipping or duplicating rows, production load is bounded, and validation catches silent drift.
Self-guided practice. This does not record assessed mastery.
Put this lesson into practice
A related activity in this module at mid level.
Try: Fix a SQL injectionFurther reading
Primary references for this module. Check the current version when behavior or framework guidance may have changed.