Search code examples
ruby-on-railsperformanceruby-on-rails-3.1observer-patternasset-pipeline

Rails observer causes slow processing time in development mode


I'm on Rails 3.1.1 and I have noticed my app has become exceedingly slow (15 seconds) in development mode. See my firebug 'Net' listing below:

Before!

I've done a number of things like:

  • reducing the number of gems
  • turning class caching on
  • turning asset debugging to false
  • turning asset compression to true
  • installing the rails-dev-boost gem

Maybe there were some improvements, but nothing helped it to go as fast I'd expect when running off localhost. That is, until I commented out my observers config line in application.rb:

config.active_record.observers = :item_observer, :loan_observer, :friendship_observer, :message_observer, :user_observer

And then the app was fast again (~1 sec) load time. See the firebug listing now:

After!

Other notes:

  • When in production on Heroku, it's fast (~1 sec), as you'd expect.
  • I'm using postgresql and Thin; I have not tried using other DBs to see if this problem exists.
  • When I commented out just the last observer, user_observer, the load time dropped by about half.
  • The load times printed in development.log do not reflect actual load times. Assets were flagged as 304 Not Modified (0ms) they really took a while to load.
  • Yes, I'm using the asset pipeline

The Golden Question: Is the simple act of registering observers causing assets to load slowly? And what can be done about it?


Solution

  • Take a look at https://github.com/wavii/rails-dev-tweaks.

    Rails is running all of the to_prepare hooks on every Sprockets asset request in development mode. This includes things like auto-(re)loading your code, and various gems perform work in there too. And in your case, observers are being registered (which - I believe - causes Rails to reference a good portion of your app in order to reference the models)

    rails-dev-tweaks disables to_prepare & reloading on any asset request (and a few others - read the first part of its README). Speeds up your dev environment by a huge amount for any decently sized project. It's also configurable to do this for any additional requests you like