Why am I getting the error "could not obtain a database connection" from my Rails app?

Issue

You are seeing an error similar to one of these in your logs:

ActiveJob::DeserializationError: Error while trying to deserialize arguments: could not obtain a database connection within 5.000 seconds (waited 5.055 seconds)

or:

ActiveRecord::ConnectionTimeoutError: could not obtain a database connection within 5.000 seconds (waited 5.015 seconds)

Resolution

This is usually a problem with application configuration, not the database itself. You can verify that your database has available connections by running heroku pg:info from the command line and looking at the connection count compared to the maximum count for your plan.

This error is usually caused by trying to share a small number of database connections across a larger number of worker processes. It's common with Puma and Sidekiq in particular. For recommended configurations for many common Rails servers and worker libraries, see Correctly Establishing Postgres Connections in Forked Environments.