0
0
Ruby on Railsframework~8 mins

Creating migrations in Ruby on Rails - Performance Optimization Steps

Choose your learning style9 modes available
Performance: Creating migrations
MEDIUM IMPACT
This affects the database schema update speed and the initial page load time when the app interacts with the database.
Updating database schema with migrations
Ruby on Rails
class AddDetailsToUsers < ActiveRecord::Migration[7.0]
  def change
    change_table :users do |t|
      t.text :bio
      t.integer :age
      t.boolean :admin, default: false
    end
  end
end
Combines multiple column additions into a single ALTER TABLE command, reducing table locks and downtime.
📈 Performance GainSingle table lock, reducing downtime and improving migration speed.
Updating database schema with migrations
Ruby on Rails
class AddDetailsToUsers < ActiveRecord::Migration[7.0]
  def change
    add_column :users, :bio, :text
    add_column :users, :age, :integer
    add_column :users, :admin, :boolean, default: false
  end
end
Multiple add_column statements cause separate ALTER TABLE commands, each locking the table and increasing downtime.
📉 Performance CostTriggers multiple table locks and blocks writes during migration, increasing downtime.
Performance Comparison
PatternDatabase LocksMigration TimeApp DowntimeVerdict
Multiple separate add_column callsMultiple locksLongerHigher[X] Bad
Single change_table block with multiple columnsSingle lockShorterLower[OK] Good
Rendering Pipeline
Migrations run outside the browser but affect app responsiveness by locking database tables during schema changes, which can delay API responses and page loads.
Database Schema Update
API Response Time
Page Load Time
⚠️ BottleneckDatabase table locking during ALTER TABLE commands
Optimization Tips
1Batch multiple schema changes in a single migration to reduce table locks.
2Avoid running long migrations during peak traffic to minimize downtime.
3Use database-specific features like concurrent index creation when possible.
Performance Quiz - 3 Questions
Test your performance knowledge
What is a performance downside of running multiple separate add_column migrations instead of combining them?
AMultiple table locks increase downtime during migration
BIt reduces the size of the migration file
CIt improves database query speed after migration
DIt automatically optimizes indexes
DevTools: Rails Console and Logs
How to check: Run migrations with verbose logging enabled and monitor the SQL commands executed; check for multiple ALTER TABLE statements.
What to look for: Look for multiple ALTER TABLE commands indicating multiple locks versus a single combined command.