Active Record has ConnectionPool
. A pool of TCP connections (not real database connections) for your web server.
[Web Server] <-> [ActiveRecord ConnectionPool] <-> [Database]
To configure Rails’s Connection Pool, change config/database.yml
.
production:
pool: <%= Integer(ENV["RAILS_MAX_THREADS"] || 20) %>
idle_timeout: 60
pool
— How many number of connections Active Record can open with your database. If your database can only have 20 connections, and you have 4 servers. Then this value should be 5
. Your Sidekiq workers also consume database connections.
idle_timeout
— Number of seconds a connection will be kept unused in the pool before it automatically disconnected (default 300 seconds). The default is too long, it is better to change to 60
.
AR::B = ActiveRecord::Base
To get a connection from Active Record, Model.connection
.
When you finished using it, AR::B.clear_active_connections!
.
You can also use AR::B.connection_pool.checkout
to get a connection.
Return it by AR::B.connection_pool.checkin(connection)
.
Or use AR::B.connection_pool.with_connection(&block)
with a block.