0xSina 0xSina - 7 months ago 29
Ruby Question

ActiveRecord::ConnectionTimeoutError

I am getting this error:

'could not obtain a database connection within 5 seconds (waited 5.001017 seconds). The max pool size is currently 16; consider increasing it.'


First I got this error, I bumped up the count from 5 to 16. But it's still happening and i am the only one test out the database. Why is this happening when I am the only user?

I am not on rails btw. I am using:

ActiveRecord::Base.establish_connection ({
:adapter => 'mysql2',
:database => 'ck',
:host => 'localhost',
:username => 'root',
:password => '',
:pool => 16,
})


and using Sinatra.

Thanks

Answer

As Frederick pointed out you need to return opened ActiveRecord connections to the connection pool.

If you're using the Thin server, in threaded mode, then you need to add this to your Sinatra app:

after do
  ActiveRecord::Base.connection.close
end

...instead of using the ConnectionManagement suggestion. The reason is that Thin splits the request processing over 2 threads and the thread that is closing the ActiveRecord connection is not the same as the thread that opened it. As ActiveRecord tracks connections by thread ID it gets confused and won't return connections correctly.