skip to content

Why should a Rails migration that adds a column to the busy events table not also backfill it with Event.update_all?

level: middleimportance: should knowfreq 50%

answer

  1. one transaction per migration
  2. the ALTER's lock lives until commit
  3. one UPDATE over 50 million rows
  4. disable_ddl_transaction! plus small batches
  5. strong_migrations does not see backfills

basics

~20 s

Rails runs the migration in one transaction, so add_column's lock on events lasts until the UPDATE over every row commits, blocking traffic for the whole backfill. Add the column in one migration; backfill in batches outside a transaction.

solid answer

~40 s

On PostgreSQL, Rails wraps each migration in a transaction. `add_column` takes a short but exclusive lock on `events`, and inside a transaction that lock is held until commit. Follow it with `Event.update_all(source: "web")` and the lock lasts as long as one `UPDATE` across 50 million rows, so every read and write on `events` waits. The single statement is also a problem on its own: one huge transaction, heavy WAL and replica lag, and no progress if it is cancelled. Split it: migration one adds the column (nullable, no backfill); migration two declares `disable_ddl_transaction!` and updates in batches with `in_batches(of: 10_000)` and `update_all`, with a short sleep between batches, or the backfill runs as a job or task. strong_migrations does not detect backfills, so review has to catch this one.

code

ruby · 10 lines
ruby
class BackfillSourceOnEvents < ActiveRecord::Migration[8.1]
  disable_ddl_transaction!

  def up
    Event.unscoped.in_batches(of: 10_000) do |batch|
      batch.where(source: nil).update_all(source: "web")
      sleep(0.01) # throttle
    end
  end
end

go deeper

for a junior

Remember the rule: a migration that changes a busy table's schema should not also update all of its rows.

for a middle

Explain the mechanism: the migration's transaction keeps add_column's exclusive lock until the single UPDATE over every row commits.

for a senior

Lay out the release: add the column, deploy writes for new rows, backfill in throttled batches outside a transaction, then tighten constraints.

for a principal

Decide where large backfills run, a migration that gates the deploy or a job with progress tracking, and who owns watching them.

## The migration that looks harmless The analytics product wants to record where each event came from, so the team writes: ```ruby class AddSourceToEvents < ActiveRecord::Migration[8.1] def change add_column :events, :source, :string Event.update_all(source: "web") end end ``` On a development database with a few thousand rows it finishes instantly. On production, with **50 million events** and constant inserts, it causes an outage. ## Why it blocks the table 1. **Rails wraps the migration in a transaction.** On adapters with transactional DDL, PostgreSQL among them, every migration runs inside one transaction unless the class calls `disable_ddl_transaction!`. 2. **`add_column` takes an exclusive lock on `events`.** On its own that lock is brief, because adding a nullable column without a volatile default only changes the catalogue. 3. **Locks inside a transaction last until commit.** The next statement, `Event.update_all(source: "web")`, is one `UPDATE events SET source = 'web'` touching every row. The exclusive lock from step 2 stays held for the whole of it. The result is that every `SELECT` and `INSERT` on `events` waits for the entire backfill. The tracking endpoint stalls, Puma threads fill up, and the deploy has turned into an incident. Even without the lock, a single `UPDATE` over 50 million rows is a poor idea: it is one enormous transaction, it writes a new version of every row, it generates a burst of WAL that replicas must replay, and if it is cancelled after 40 minutes nothing is kept. ## The safe shape | Step | Migration | Notes | |---|---|---| | 1 | `add_column :events, :source, :string` | transactional, quick, no data | | 2 | deploy code that writes `source` for new events | rows created during the backfill are already correct | | 3 | backfill migration with `disable_ddl_transaction!` | small batches, each committed on its own | | 4 | optional `NOT NULL` via a check constraint | only once the backfill is complete | The backfill migration, following the recipe strong_migrations documents: ```ruby class BackfillSourceOnEvents < ActiveRecord::Migration[8.1] disable_ddl_transaction! def up Event.unscoped.in_batches(of: 10_000) do |batch| batch.where(source: nil).update_all(source: "web") sleep(0.01) end end end ``` - **`disable_ddl_transaction!`** lets each batch's `UPDATE` commit by itself, so no lock or transaction outlives a batch. - **Batching** keeps each statement short; batching mechanics belong to `in_batches` itself. - **`where(source: nil)`** makes the backfill safe to rerun: a second run skips rows already done. - **The sleep** throttles the work so replicas and the primary keep up. - **`unscoped`** stops a default scope from silently skipping rows. If the backfill writes through model attributes and `save` instead of `update_all`, call `Event.reset_column_information` first, so the model picks up the column added earlier in the same run. ## Deploy order around the backfill The backfill sits between two code changes. Code that **writes** the new column for fresh rows must be live before the backfill finishes, or rows created in the gap stay empty. Code that **relies** on every row having a value, such as a `NOT NULL` constraint, a query that no longer handles `nil`, or a validation, ships only after the backfill is complete and verified with a quick count of rows still missing a value. If the column needs a default for new rows, set it with `change_column_default` after adding the column; strong_migrations recommends that split for volatile defaults such as `gen_random_uuid()`, since adding the column with one would rewrite the table. ## Where the backfill should live A backfill in a migration blocks `bin/rails db:migrate`, and therefore the deploy, until it finishes. For tens of millions of rows many teams prefer an Active Job or a one-off task that the deploy does not wait for, with progress logging and the option to pause. The trade-off is that a migration runs exactly once per database and in order, while a job or task needs its own bookkeeping. ## What tooling catches strong_migrations **does not detect backfills**; its documentation says so. It stops the risky DDL calls, such as a volatile default like `gen_random_uuid()` on a new `uuid` column, but an `update_all` inside a migration passes unchallenged. That makes this pattern a code-review item: any data change in a migration that also alters a table should be questioned.

  • Rows keep arriving during the backfill. How do you make sure none end up with a NULL source?
    Deploy the code that sets `source` on new events before the backfill starts, then backfill the rows where `source` is nil. New rows are written correctly by the app, and the backfill's `where(source: nil)` catches everything older, including rows created between the column's addition and the code deploy.
  • When is it fine to backfill in the same migration as the DDL?
    When the table is small or brand new, for example a table created in the same migration that nothing reads yet. The lock is then held for milliseconds and no traffic waits on it. On a large, busy table, keep DDL and data in separate migrations.

It is like closing a road to paint one lane marking and then, before reopening it, repaving the whole road: the closure was meant to last a minute, but it lasts as long as the slowest job done while it is closed.

  • update_all in the migration is fine because add_column is instant
  • strong_migrations will stop a dangerous backfill
  • one UPDATE is faster, so batching only adds overhead
  • disable_ddl_transaction! is only needed for concurrent indexes
  • Rails commits add_column before running the next statement in change