How-To Guide

How to Backfill a Large Table Safely

Populate a new column over millions of rows in batches, without long locks, replication lag or a table rewrite.

On this page

  1. Introduction
  2. Why One Big Update Is Unsafe
  3. Batching by a Key
  4. Batch Sizing and Pacing
  5. Watching Replication Lag and Load
  6. Catching Rows Inserted During the Backfill
  7. Knowing When It Is Done
  8. Conclusion

Introduction

A schema change often needs existing rows populated with a value the new column was added empty. A single UPDATE over millions of rows holds locks long enough to block the application, generates a burst of write-ahead log that lags replicas, and can consume a transaction id that delays vacuum. A safe backfill is incremental: update a bounded batch, commit, wait, and repeat, so each step is short and the system stays responsive throughout. This article covers batch sizing, avoiding lock escalation, watching replication lag, and knowing when the backfill is done.

Why One Big Update Is Unsafe

A single UPDATE across a large table runs in one transaction, so it holds locks on every row it touches until it commits, and generates all its write-ahead log at once. On a busy table that blocks writes for the duration and floods the replicas with a volume they cannot apply quickly, so replication lag grows. It also consumes a range of transaction ids, delaying the vacuum that reclaims dead rows.

The table may also grow while the update runs, so a single pass may not cover rows inserted after it passed their position. A batched backfill, keyed by an ordered column, makes progress in short transactions and can include rows added during the backfill in a later pass.

Batching by a Key

Backfill by selecting a batch of rows, updating them, committing, then selecting the next batch after the last key. Key on a unique, ordered column such as the primary key, and process in ascending order so the batch boundary moves forward. Commit each batch so locks are released and the write-ahead log is spread over time.

-- One batch: update rows after the last processed key, limited to N rows.
-- Commit after each statement so locks are released and WAL is spread out.
UPDATE orders
SET currency = 'USD'                 -- the value to backfill
WHERE id > $last_id                  -- resume after the previous batch
  AND currency IS NULL               -- only untouched rows
  AND id IN (
    SELECT id FROM orders
    WHERE id > $last_id AND currency IS NULL
    ORDER BY id
    LIMIT 1000                       -- batch size, tune to keep each step short
  )
RETURNING id;                        -- last id becomes $last_id for the next pass

Batch Sizing and Pacing

The batch size trades throughput for lock duration. A small batch commits quickly and holds locks briefly but needs many iterations; a large batch does more per iteration and holds locks longer. Start conservative and increase while watching the lock wait and the replication lag, then back off if either grows. The right size depends on the row width and the write rate, so measure rather than assume.

Pace the batches with a short sleep so the database has time to apply the log on replicas and to vacuum. A tight loop backfills faster but starves the other work, which defeats the purpose. The goal is to complete the backfill without degrading the service, not to complete it as fast as possible.

import time

def backfill(cursor, batch_size=1000, sleep_s=0.05):
    last_id = 0
    total = 0
    while True:
        cursor.execute(
            """UPDATE orders SET currency = 'USD'
               WHERE id > %s AND currency IS NULL
                 AND id IN (SELECT id FROM orders
                            WHERE id > %s AND currency IS NULL
                            ORDER BY id LIMIT %s)
               RETURNING id""",
            (last_id, last_id, batch_size),
        )
        rows = cursor.fetchall()
        if not rows:
            break
        cursor.connection.commit()          # release locks between batches
        last_id = max(r[0] for r in rows)
        total += len(rows)
        time.sleep(sleep_s)                 # let replicas catch up and autovacuum run
    return total

Watching Replication Lag and Load

Batch writes generate log that replicas must apply, so a rapid backfill can grow replication lag even though each statement is short. Watch the lag and pause the backfill if it grows beyond the tolerance, resuming when it recovers. This keeps the replicas usable for read traffic during the backfill.

Also watch the lock wait and the transaction id age. A backfill written as one transaction per batch keeps transactions short, so lock wait stays low; if it climbs, some other long transaction is contending, or the batch is too large. Confirm that autovacuum is keeping up, because the backfill creates dead tuples as it rewrites rows.

Catching Rows Inserted During the Backfill

New rows can be inserted while the backfill runs, and they are not covered if they have a key beyond the current batch and the writer does not populate the new column. The writer must populate the new column from the moment the backfill starts, so new rows are correct by construction. Then the backfill only needs to cover rows that existed before the writer changed, and a final pass over the remaining nulls catches any stragglers.

After the backfill, run one more pass to catch rows that were inserted with a null value during the transition, and then add the not-null constraint. The final pass should find zero rows; if it finds some, the writer was not populating the column consistently, which is the bug to fix before enforcing the constraint.

Knowing When It Is Done

Track the count of rows still needing a backfill, not just the batches processed. The count tells you the remaining work and confirms the process is making progress; a count that stops falling means the batch predicate does not match the rows that remain, which is a bug in the backfill query rather than a slow database.

When the remaining count reaches zero and a verification pass confirms it, the backfill is complete and the constraint can be enforced. Keep the backfill script idempotent so it can be re-run safely if it is interrupted, and record the last processed key so a restart resumes rather than repeating.

Conclusion

A safe backfill of a large table is incremental: key the batches on an ordered column, size them so each step is short, commit between batches, and pace them so replicas and vacuum keep up. Populate the new column from the writer so new rows are correct by construction, watch replication lag and lock wait, and track the remaining count rather than the batches processed. Keep the script idempotent and resumable, and enforce the constraint only after a verification pass finds zero rows.

Sources: PostgreSQL: VACUUM and bloat, PostgreSQL: concurrency and locking, GitLab: batched background migrations.

FAQ

Why not backfill with one UPDATE?
One UPDATE runs in a single transaction, holding locks on every row until it commits and generating all its write-ahead log at once. On a large table that blocks writes, lags replicas and delays vacuum. Batching keeps each transaction short and spreads the log over time.
How do I handle rows inserted during the backfill?
Have the application write the new column from the moment the backfill starts, so new rows are correct by construction. Then the backfill only covers rows that existed before, and a final pass over remaining nulls catches any straggler before the constraint is enforced.

Related Examples