/writing · 29 November 2026 · 7 min read
Making a Rails data migration safe to re-run
Moving live data is where Rails projects quietly go wrong. A migration that runs once in staging can still fail halfway in production, get interrupted by a deploy, or need a second pass for records created while it ran. If running it again creates duplicates or loses state, every retry becomes a cleanup job.
I used the design below when merging four conversation types into one chat model at SMATA. None of it is exotic, but together it turns a scary one-shot script into something you can run as often as you need.
1. Make every write idempotent
The core rule: running the migration twice must produce the same result as running it once. The simplest way is to look for the record you're about to create, using a natural key from the source data, before creating it.
message = room.messages.find_or_initialize_by(
sender_id: comment.user_id,
body: comment.body,
created_at: comment.created_at
)
return unless message.new_record? # already migrated: skip
If the migration can run in parallel, back this with a unique index on the same key. find_or_initialize_by alone can race; a unique index can't.
2. Work in batches
Loading every row at once is slow and memory-hungry, and one bad record kills the whole run. find_each walks the table in primary-key order in fixed-size batches:
Comment.where("created_at < ?", cutoff)
.find_each(batch_size: 500) { |comment| migrate(comment) }
3. Use a cutoff, then sweep the stragglers
New comments keep arriving while the migration runs. Instead of chasing a moving target, migrate everything created before a fixed cutoff time, switch the app to the new model, then run the same code again with a later cutoff to catch anything in between. Because writes are idempotent, the second run only adds what's missing.
4. Carry state, not just content
Copying the text is the easy part. Users also have state attached to it: who has read what, reactions, attachments. If read state doesn't move with each message, everyone's inbox lights up with years of "new" messages the morning after go-live. Migrate that state in the same transaction as the record it belongs to:
Message.transaction do
message.save!
copy_read_receipts(from: comment, to: message)
end
5. Keep side effects out of the critical path
Search indexing, notifications and webhooks shouldn't be able to stop a data migration. Suppress notifications entirely during the run, and treat indexing as best effort: log the failure, carry on, and reindex in bulk afterwards.
begin
message.reindex # or your search client's call
rescue SearchIndexError => e # your client's specific error class
Rails.logger.warn("index failed for message #{message.id}: #{e.message}")
end
Prove it with a spec
The most useful test for a migration like this runs it twice:
it "is safe to run twice" do
create_list(:comment, 3, created_at: 2.days.ago)
migration = described_class.new(cutoff: 1.day.ago)
expect { migration.call }.to change(Message, :count).by(3)
expect { migration.call }.not_to change(Message, :count)
end
Add one for read state and one where indexing raises, and you can schedule the production run with confidence instead of crossed fingers. It's also the step I'd add first if I ran that SMATA migration again: the design was idempotent, but only a test like this proves it.
The checklist
- Idempotent writes, backed by a unique index if runs can overlap.
- Batches with
find_each. - A cutoff time, plus a straggler sweep after switch-over.
- State moves with the record, in one transaction.
- Side effects suppressed or best effort.
- A spec that runs the migration twice.