Rails 4 is thread safe by default [Rails 4 Countdown to 2013]

Posted on

This post is part of a series of 31 Rails 4 articles being released each day in December 2012.

A big change to Rails 4 is that production applications will now be thread safe by default. This will have huge performance benefits for applications as they will be able to serve more than one request at a time.

Thread Safe Code

If you are running a production server which allows for concurrency, such as Puma, you must ensure all your code is thread safe. This includes all gem dependencies of your application. You should do an investigation of every gem included in your project to see if it is thread safe. This involves checking out the source of the gem, and potentially having a conversation with the gem author. If a gem you require is not thread safe, you can be a good open source samaritan and provide a pull request including the required changes.

Once all gems have been evaluated, the next step should be to look into your own project code. Go through your application and look for any shared code, such as:

  • Class Variables
  • Constants
  • Global Variables

Here is an example of writing a thread safe memoized calculation on the class using a Mutex:

class SomeClass
  @lock = Mutex.new

  class << self
    def some_calculation
      @lock.synchronize do
        @calc ||= heavy_operation


If you run a web server such as Unicorn, even if your application is set to be thread safe, all requests will still run in isolation. Each worker process only runs a single thread at a time. However, since Rails is now thread safe by default, you do not have the overhead of including the Rack::Lock middleware in each request.


Rails will automatically include Rack::Lock if your application is using a threaded web server, such as WEBrick.

Aaron Patterson's Aloha Ruby Conference Keynote

A must watch conference video is Aaron Patterson's keynote from Aloha Ruby Conference. In the video, he goes into detail about how thread safety works and how to write thread safe code. I've included the video for your viewing pleasure below:

Extra Resources


This post is by Kevin Faustino. Kevin is the Chief Craftsman of Remarkable Labs and also the founder of the Toronto Ruby Brigade.


comments powered by Disqus