Question: Rails threads hang in ActiveRecord database call when using Puma server

Question

Rails threads hang in ActiveRecord database call when using Puma server

Answers 0
Added at 2016-12-22 06:12
Tags
Question

I'm new to Rails and trying to code an implementation where web service queries are run in parallel using celluloid-pmap in Puma. In doing that Rails server hangs at ActiveRecord database calls. I don't receive any error messages. The threads hang at the very first database call. I found that the same piece of code executes perfectly in 'rails console'.

I also found that I face the same hanging issue when I use Ruby threads. I use Rails 5.0.0.1 and Ruby 2.3.1. Here's a modified code snippet from my server code using threads in Puma.

def with_connection(&block)
  ActiveRecord::Base.connection_pool.with_connection do
    yield block
  end
  ensure
  ActiveRecord::Base.clear_active_connections!
  ActiveRecord::Base.connection.close
end

thread_arr = []
[5,10,15,20].each do |number|
   thread_arr << Thread.new {
     with_connection do
       @label = Label.where("user_id = ? ", "2")
     end
   }
end 
thread_arr.each { |t| t.join; }

I have my config/puma.rb file set to:

workers Integer(ENV['WEB_CONCURRENCY'] || 2)
threads_count = Integer(ENV['RAILS_MAX_THREADS'] || 5)
threads threads_count, threads_count

preload_app!

rackup      DefaultRackup
port        ENV['PORT']     || 3000
environment ENV['RACK_ENV'] || 'development'

on_worker_boot do
  ActiveRecord::Base.establish_connection

  $CELLULOID_BACKPORTED = false
  Celluloid.start
end 

Any pointers to resolve this will be very helpful.

Answers
Source Show
◀ Wstecz