The Wordchuck Blog. RSS

Shelly Shelly Roche is a Ruby on Rails engineer and founder of Wordchuck. She usually blogs about Ruby, Rails 3, woodchucks, i18n, l10n, startup life or whatever has her fired up on any given day. Yes, she is available for i18n consulting & training. Find her @shellyroche or by email.

Running on Async Rails 3

by Shelly
Wordchuck is now running on async Rails!

It was actually quite simple to set up, as I was already running Rails 3 + Ruby 1.9.2. I used @ejwcom's Async Rails 3.x demo project on github as a reference, as well as some, er, light reading from @igrigorik, and everything pretty much worked as advertised.

Step 1: Use the right gems


Add these gems to your Gemfile:
  source 'http://rubygems.org'
  
  gem 'rails', '3.0.0'
  gem 'rake', '0.8.7'
  gem 'thin', '1.2.7'
  gem 'rack', '>=1.0.0'

  gem 'eventmachine', '0.12.10'
  gem 'rack-fiber_pool', :require => 'rack/fiber_pool'
  gem 'mysql2', '0.2.4'
  gem 'builder'

Step 2: Enable threaded mode


In your various environments' configs:
  # Enable threaded mode
  config.threadsafe!

Step 3: Add FiberPool as Rack middleware


Update config.ru to use FiberPool as Rack middleware. This will make sure each request runs in its own fiber:
use Rack::FiberPool
run Wordchuck::Application

Step 4: Configure MySQL for async use


Set the adapter in database.yml to "em_mysql2" to run mysql in async mode with ActiveRecord and Rails:
development:
  adapter: em_mysql2

Step 5: Fix your rake tasks


When I enabled threaded mode in my production environment...
  # Enable threaded mode
  config.threadsafe!
...I broke the rake tasks and delayed_job startup script I use in production. To fix this, I can create a new environment called "tasks", that has the same config as my old production.rb file, in particular, turning thread safety off:
  # Enable threaded mode
  # config.threadsafe!
Then, I can run my rake tasks & script using RAILS_ENV=tasks instead of RAILS_ENV=production.

Step 6: Restart your app


At this point, restart your app, and you should be running async Rails!

One thing to note is that many gems aren't yet fiber-aware, so they will be blocking. You can still use them, just be aware that they'll prevent you from seeing the full performance benefit of running asynchronously.

To find out more about how this all works, watch the video at the end of Ilya's post, and read this article from @mperham.


blog comments powered by Disqus