By Dharin Rajgor,
Last Modified: April 9, 2025

When updating a database schema in a Ruby on Rails application, zero-downtime migrations ensure that database changes do not cause application downtime or errors. Here are key techniques to achieve zero-downtime migrations:

1. Add New Columns Without Removing Old Ones

				
					class AddNewColumnToUsers < ActiveRecord::Migration[6.1]
  def change
    add_column :users, :new_column, :string
  end
end

				
			

2. Use add_column With Defaults Carefully

				
					class AddNewFieldToUsers < ActiveRecord::Migration[6.1]
    def change
        add_column :users, :new_field, :string, null: true
    end
end
				
			

Then, backfill the data asynchronously:

				
					User.update_all(new_field: 'default_value')
				
			

Finally, apply constraints safely:

				
					class AddNotNullConstraintToUsers < ActiveRecord::Migration[6.1]
    def change
        change_column_null :users, :new_field, false
    end
end
				
			

3. Indexing Without Downtime

				
					class AddIndexToUsers < ActiveRecord::Migration[6.1]
  disable_ddl_transaction!
  def change
    add_index :users, :email, unique: true, algorithm: :concurrently
  end
end

				
			

4. Renaming Columns or Tables Safely

5. Removing Columns Without Breaking Queries

6. Dropping Tables Safely

				
					class DropOldTable < ActiveRecord::Migration[6.1]
  def up
    drop_table :old_table
  end
  def down
    # Optional rollback (recreate table)
  end
end

				
			

7. Avoid Locking Large Tables

Best Practices

Would you like help structuring your migrations for a specific use case? 🚀


Schedule a Free Consultation

Discover the power of Ruby on Rails

for your projects!


Explore our Ruby on Rails expertise



Start a project



Share On: