Unicorn Performance Tips for Rails Developers

If you’re using Unicorn, first off good job. If you’re not, bookmark this post and fix that. I can wait.

Next, you’ll want to make your app as fast as possible. One of the biggest penalties you’ll pay in a Rails app is Garbage Collection. MRI’s GC is just awful in terms of performance. But you don’t need to have people waiting on it anymore! In exchange for a little higher CPU and Memory usage, you can tell Unicorn to run garbage collection outside of the request/response cycle using OOB_GC. It’s really quite simple, and it works in any Rack application. Just open config.ru and add this:

require 'unicorn/oob_gc'

That’s all you have to do! There is some additional tuning if you have, for example some routes that are particularly memory intensive and have GC run more frequently than the every 5 requests it comes set out of the box for. You can read the docs for more info.

A word of warning: This increased memory usage ~100% on my Gitlab install. It made things much faster too, though. Coincidentally, the memory increase from doing this was the same as the decrease from switching from multiple thins to Unicorn.

Another nice trick is to preload your app in the master process so that your workers are a little lighter weight and spin up faster. With Rails it’s pretty easy, just add this to your unicorn config file:

preload_app true

before_fork do |server, worker|
  # the following is highly recomended for Rails + "preload_app true"
  # as there's no need for the master process to hold a connection
  defined?(ActiveRecord::Base) and
    ActiveRecord::Base.connection.disconnect!
end

after_fork do |server, worker|
  # the following is *required* for Rails + "preload_app true",
  defined?(ActiveRecord::Base) and
    ActiveRecord::Base.establish_connection
end

I’d encourage you to read the docs for Unicorn if you’re using it and spend some time tweaking it for your app. In just a few minutes I significantly sped up Gitlab over Thin and the default Unicorn configuration and everyone likes “free” performance bumps :-)