ConnectionTimeoutError on Heroku with Postgres

2020-02-29 04:17发布

问题:

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?

回答1:

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.



回答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.