Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Improve slow Rails startup time (rails console, rails server)

I work with several Rails apps, some on Rails 3.2/Ruby 2.0, and some one Rails 2.3/Ruby 1.8.7.

What they have in common is that, as they've grown and added more dependencies/gems, they take longer and longer to start. Development, Test, Production, console, it doesn't matter; some take 60+ seconds.

What is the preferred way to first, profile for what is causing load times to be so slow, and two, improve the load times?

like image 950
professormeowingtons Avatar asked Jul 02 '13 23:07

professormeowingtons


2 Answers

There are a few things that can cause this.

  1. Too many GC passes and general VM shortcomings - See this answer for a comprehensive explanation. Ruby <2.0 has some really slow bits that can dramatically increase load speeds; compiling Ruby with the Falcon or railsexpress patches can massively help that. All versions of MRI Ruby use GC settings by default that are inappropriate for Rails apps.
  2. Many legacy gems that have to be iterated over in order to load files. If you're using bundler, try bundle clean. If you're using RVM, you could try creating a fresh gemset.

As far as profiling goes, you can use ruby-prof to profile what happens when you boot your app. You can wrap config/environment.rb in a ruby-prof block, then use that to generate profile reports of a boot cycle with something like rails r ''. This can help you track down where you're spending the bulk of your time in boot. You can profile individual sections, too, like the bundler setup in boot.rb, or the #initialize! call in environment.rb.

Something you might not be considering is DNS timeouts. If your app is performing DNS lookups on boot, which it is unable to resolve, these can block the process for $timeout seconds (which might be as high as 30 in some cases!). You might audit the app for those, as well.

like image 170
Chris Heald Avatar answered Oct 27 '22 08:10

Chris Heald


Ryan has a good tutorial about speeding up tests, console, rake tasks: http://railscasts.com/episodes/412-fast-rails-commands?view=asciicast

I have checked every methods there and found "spring" the best. Just run the tasks like:

$ spring rspec 

The time for your first run of spring will be same as before, but the second and later will be much faster.

Also, from my experience, there will be time you need to stop spring server and restart when there is weird error, but the chance is rare.

like image 37
Billy Chan Avatar answered Oct 27 '22 10:10

Billy Chan