Ruby/Rails thread safety Ruby/Rails thread safety multithreading multithreading

Ruby/Rails thread safety


First and foremost, Ruby 1.9 (the most recent official release) now uses native (kernel) threads. Previous versions of Ruby used green threads. To answer your question succinctly, prior to 1.9, threads have not commonly been used in Ruby applications large or small precisely because they're not particularly safe or reliable.

This is not particularly alarming because prior to version 2.2 Rails made no attempt to be threadsafe, and so we typically handle asynchronous processing through the use of multiple processes, database record locking, and message queues like Starling. This is generally a pretty reliable way to scale a web application--at least as reliable than incorrectly multithreaded Java applications--and has the added advantage that it becomes easier to scale your application sideways to multiple processors and servers.

I have no idea whether the 'require' issue you've mentioned has been resolved as of 1.9, but I do humbly venture that if you're requiring libraries dynamically in new threads then you have more than one maintainability problem.

If you'd like to avoid threads entirely, Ruby 1.9 also supports fibers, which employ a shared-nothing approach to concurrency and are, from what I gather, generally easier to write and maintain than threads. Performance numbers here.


The normal solution for MRI is to run multiple Rails instances, each handling requests independently. Since MRI isn't multithreaded anyway, you can't run multiple Rails instances on top of it. This means you take a memory hit since Rails is loaded once per Ruby process.

Since JRuby supports native threads, you could always run several Rails instances in a single JVM. But with Rails being thread-safe, you can cut it down to one, which means lower memory usage and less JIT compilation.

Charles Nutter (JRuby) has a nice summary.