Fun with Rails ActiveRecord and Ruby’s Thread
I’ve been working on threading a Rails application lately and after reading headlines like ‘Rails is thread safe’ I figured how hard could it be. My first discovery was that when people talk about Rails and threads there are two different types of threading in Rails.
- Multiple request threading – This is where Rails itself threads among different requests to your web server and allows ActiveRecord to behave properly without having to keep a copy of Rails in memory for each request.
- Intra-request threading – This is where you have 1 request to your web server and inside the action you want to create multiple threads that run concurrently.
I’ll be talking about Intra-request threading. In particular, I want my threads to execute some code, read and write to the database, and play nicely with each other. My first attempt was to use the Ruby Thread method. This seemed to work somewhat until I started seeing strange errors coming in from MySQL. The problems seemed to occur randomly and what I determined was that the threads were trying to write to the database at the same time which ended up causing some collisions of sorts resulting in ‘lock wait timeout exceeded’ errors.
After considerable Googling, I found numerous posts about setting:
ActiveRecord::Base.allow_concurrency = true
The problem with that is that this is deprecated in the newest version of Rails in favor of connection pooling.
The short answer: Don’t use the Ruby Thread method within Rails when doing anything with ActiveRecord.

December 8th, 2009 at 8:24 pm
[...] « Fun with Rails ActiveRecord and Ruby’s Thread [...]