5

I’m having problems with my application deployed on Heroku. It works fine on local env, but when deployed to Heroku there are often application errors.

The exception in logs are: ActiveRecord::ConnectionTimeoutError (could not obtain a database connection within 5.000 seconds (waited 5.000 seconds))

The controller and models are nothing fancy, rather simple CRUD operations.

The app is build with Rails 4, its using standard heroku postgres database add-on and WEBrick server.

I've tried to set config like this:

#config/initializers/database_connection.rb
Rails.application.config.after_initialize do
  ActiveRecord::Base.connection_pool.disconnect!

  ActiveSupport.on_load(:active_record) do
    config = Rails.application.config.database_configuration[Rails.env]
    config['reaping_frequency'] = ENV['DB_REAP_FREQ'] || 5 # seconds
    config['pool']              = ENV['DB_POOL']      || 10
    config['timeout']           = ENV['DB_TIMEOUT']   || 10
    ActiveRecord::Base.establish_connection(config)
  end
end

but it did not help.

Do you have any idea what can help?

nataliastanko
  • 852
  • 1
  • 7
  • 13

2 Answers2

5

Your DB pool is not the problem. This is a known rails issue. If you are using Rails 4.0.2 then the claim is to use rails master in your Gemfile instead. I am experiencing this issue as well, however I haven't tried this solution yet.

Simpleton
  • 6,285
  • 11
  • 53
  • 87
  • 3
    Thanks for this! I just upgraded from 4.0.3 to 4.0.4 and it's fixed the issue. Left me with another issue but hey. – Evolve Apr 10 '14 at 21:39
  • My secondary error was 'NoMethodError: undefined method `environment' for nil:NilClass' which caused heroku not to deploy. I upgraded sass-rails from 4.0.1 to 4.0.3 and it fixed this secondary issue. – Evolve Apr 10 '14 at 21:46
  • 2
    @Daniel apparently this will be finally fixed in Rails 4.2, see the last comment in above link – Mike Szyndel Sep 18 '14 at 13:49
2

The code example you posted is legitimate. There is likely something causing a problem in your Heroku config environment.

The error you are seeing would indicate your DB_POOL value is set too low. This error indicates a timeout within the app server waiting to check a connection out of the pool, not necessarily a connection failure. Is it possible your DB_POOL is set to 1 or a low value?

You should also verify that your database configuration is complete, that you have the full hostname, credentials, and config set from the default db configuration. You can run the following in a Heroku console:

Rails.application.config.database_configuration[Rails.env]

There is something incorrect in your Heroku config settings that is causing this timeout.

Winfield
  • 18,985
  • 3
  • 52
  • 65
  • I increased the values in `config/database.yml` which solved it for me. I think the default is 5, but on Heroku the max pool depends on the db and tier that is provisioned – whodini9 Jul 10 '19 at 02:27