Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Puma, how do I calculate DB connections?

I'm trying to figure out how many database connections my app will use.

It's Rails 5 hosted on Heroku.

Here is my Puma config

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
end

And the first part of my DB config:

default: &default
  adapter: postgresql
  encoding: unicode
  pool: <%= ENV['RAILS_MAX_THREADS'] || 5 %>

The part that seems strange to me is # of connections, and also my pool setting in database.yml are all using RAILS_MAX_THREADS... but shouldn't it be using RAILS_MAX_THREADS multiplied by the number of workers (WEB_CONCURRENCY?

like image 655
Tallboy Avatar asked Nov 03 '16 22:11

Tallboy


1 Answers

Actually I found the answer explained well here... https://devcenter.heroku.com/articles/deploying-rails-applications-with-the-puma-web-server#database-connections


As you add more concurrency to your application, it will need more connections to your database. A good formula for determining the number of connections each application will require is to multiply the RAILS_MAX_THREADS by the WEB_CONCURRENCY. This combination will determine the number of connections each dyno will consume.

Rails maintains its database connection pool, with a new pool created for each worker process. Threads within a worker will operate on the same pool. Make sure there are enough connections inside of your Rails database connection pool so that RAILS_MAX_THREADS number of connections can be used. If you see this error:

ActiveRecord::ConnectionTimeoutError - could not obtain a database connection within 5 seconds

This error is an indication that your Rails connection pool is too low. For an in-depth look at these topics, please read the Dev Center article Concurrency and Database Connections.

like image 163
Tallboy Avatar answered Nov 08 '22 11:11

Tallboy