Lesson 6 of 9 · 26m
Safe Migrations and Production Data Backfills
Design zero-downtime migrations, avoid lock-heavy schema changes, run bounded backfills, and separate deploy-compatible database evolution from cleanup.
The migration that passes review and ruins lunch is usually simple: add a column with a default, rewrite a table, lock a hot relation, or backfill 80 million rows inside a deploy transaction. Rails makes schema change easy enough that teams forget it is a production operation. Treat migrations as code plus database behavior plus timing.
The compatibility sequence
A safe structural change often takes multiple deploys:
1. Add nullable column.
2. Deploy code writing both old and new fields.
3. Backfill in bounded batches; validate and repair stragglers.
4. Deploy code reading only the new field, then add constraints.
5. Remove the old field later.Compressing that into one deploy only works when the table is small or the application can tolerate downtime. Admit which situation you are in.
Avoid heavy table rewrites
Changing column types, adding volatile defaults, and some constraint operations can rewrite or lock large tables in PostgreSQL. Prefer additive changes:
add_column :orders, :fulfillment_state, :string
add_index :orders, :fulfillment_state, algorithm: :concurrentlyalgorithm: :concurrently avoids a full table lock for index creation, but it cannot run inside a transaction. Rails therefore requires disable_ddl_transaction! in that migration.
Backfills are jobs, not migration side effects
Do not mutate a huge table inside the schema migration. Write a bounded job or task:
class BackfillOrderFulfillmentStateJob < ApplicationJob
def perform(start_id, end_id)
Order.where(id: start_id..end_id).find_each do |order|
order.update_columns(fulfillment_state: order.shipped_at? ? "shipped" : "pending")
end
end
endEnqueue ranges, record progress, and make the job idempotent. Kill and resume it without corrupting state. Measure replication lag and database load if the system is busy.
Constraints come after confidence
NOT NULL, foreign keys, and unique indexes are final commitments. Validate first:
SELECT COUNT(*) FROM orders WHERE fulfillment_state IS NULL;Then enforce in a small migration. On very large tables, consider PostgreSQL's staged constraint validation patterns rather than assuming one ORM call is downtime-free. Rolling back code does not unwrite data: irreversible transformations need backups, dual writes, or a reversible representation, with the rollback story documented in the migration or pull request.
Field notes
strong_migrations-style checks catch many hazards, but they do not know your table sizes or traffic shape.add_referencewithout an index decision creates either missing indexes or surprise locking depending on options.- Never run an unbounded production console loop as your backfill strategy; use resumable, logged batches.
- Keep migration code independent of application models when possible; future model changes can break old migrations.
Was this lesson helpful?