Database connection pooling

suggest change

Opening a database connection is expensive. The client has to open a TCP (or TLS) socket, authenticate, negotiate a protocol and set up a session. Once connected, the connection is a stateful object. It runs one query at a time and carries session settings, open transactions and temporary tables.

A connection pool keeps a small set of open connections and lends them out:

  1. A thread checks out a connection, waiting if all of them are busy.
  2. It runs its queries.
  3. It checks the connection back in, so another thread can reuse it.

This article covers why pools exist, how they work inside, the connection_pool gem for raw drivers, and the pools built into Sequel and Active Record. It also covers sizing, stale connections and forking. Relational databases gives a short overview and MySQL covers the drivers. The examples use MySQL 9 through the mysql2 gem on Ruby 4.0, but the pooling code works the same way with pg or trilogy.

# Gemfile
gem 'mysql2'
gem 'connection_pool'   # 3.x: keyword arguments everywhere
gem 'sequel'            # or:
gem 'activerecord'      # 8.1+

Why pool: the cost of connecting

This benchmark runs SELECT 1 200 times. The first loop opens a new connection for each query, and the second loop reuses one connection:

require 'mysql2'
require 'benchmark'

CONFIG = { host: '127.0.0.1', port: 33871, username: 'root', database: 'shop' }

n = 200
fresh = Benchmark.realtime do
  n.times do
    c = Mysql2::Client.new(**CONFIG)
    c.query('SELECT 1')
    c.close
  end
end

reused = Benchmark.realtime do
  c = Mysql2::Client.new(**CONFIG)
  n.times { c.query('SELECT 1') }
  c.close
end

printf("new connection per query: %6.1f ms\n", fresh * 1000)
printf("one reused connection:    %6.1f ms\n", reused * 1000)
new connection per query: 3638.1 ms
one reused connection:      95.3 ms

Here the server runs on the same machine. Over a network, with TLS and a cloud database, a connection setup costs even more round trips. Every connection also uses memory on the server (a thread in MySQL, a whole process in PostgreSQL), so you can't open one for every request either.

Why not share one connection?

A single connection can't run two queries at once. If two threads use the same client, the driver either corrupts the protocol stream or refuses. mysql2 refuses:

require 'mysql2'

CONFIG = { host: '127.0.0.1', port: 33871, username: 'root', database: 'shop' }
Thread.report_on_exception = false
client = Mysql2::Client.new(**CONFIG)

threads = 2.times.map do
  Thread.new { client.query('SELECT SLEEP(0.2)').to_a }
end
threads.each do |t|
  t.join
rescue Mysql2::Error => e
  puts "#{e.class}: #{e.message}"
end
Mysql2::Error: This connection is in use by: #<Fiber:0x00007c38cb22b0c0 (resumed)>

A pool sits between these two extremes: a fixed number of connections shared safely by many threads. See Thread and Race conditions for more on Ruby concurrency.

How a pool works: a 30-line version

You don't need to write your own pool, but a small one shows what the real ones do. It's built on a thread-safe Queue (see Queue). Since Ruby 3.2, Queue#pop accepts a timeout::

require 'mysql2'

class TinyPool
  class TimeoutError < StandardError; end

  def initialize(size:, timeout: 5, &factory)
    @size = size
    @timeout = timeout
    @factory = factory
    @idle = Queue.new        # connections ready for reuse
    @created = 0
    @lock = Mutex.new
  end

  def with
    conn = checkout
    begin
      yield conn
    ensure
      @idle.push(conn)
    end
  end

  private

  def checkout
    # 1. reuse an idle connection if there is one
    conn = @idle.pop(timeout: 0)
    return conn if conn

    # 2. create a new one while under the limit
    create = @lock.synchronize { @created < @size && (@created += 1) }
    return @factory.call if create

    # 3. otherwise wait for another thread to return one
    @idle.pop(timeout: @timeout) or raise TimeoutError, "no connection within #{@timeout}s"
  end
end

CONFIG = { host: '127.0.0.1', port: 33871, username: 'root', database: 'shop' }
pool = TinyPool.new(size: 3, timeout: 2) { Mysql2::Client.new(**CONFIG) }

threads = 8.times.map do
  Thread.new do
    pool.with { |c| c.query('SELECT CONNECTION_ID() AS id, SLEEP(0.1)').first['id'] }
  end
end
ids = threads.map(&:value)
puts "queries run:          #{ids.size}"
puts "distinct connections: #{ids.uniq.size}"
queries run:          8
distinct connections: 3

Every real pool shares these ideas:

A production pool also handles what this one ignores: connections that died while idle, reentrant checkouts, closing idle connections, and fork.

The connection_pool gem

connection_pool is the standard generic pool. Sidekiq, Rails' Redis cache store and many HTTP clients use it. It pools any object, so you can use it with a raw Mysql2::Client, PG::Connection, Trilogy or a Redis client.

require 'mysql2'
require 'connection_pool'

CONFIG = { host: '127.0.0.1', port: 33871, username: 'root', database: 'shop' }

DB = ConnectionPool.new(size: 3, timeout: 1) do
  puts "  opening connection"
  Mysql2::Client.new(**CONFIG)
end

def connection_id
  DB.with { |c| c.query('SELECT CONNECTION_ID() AS id').first['id'] }
end

puts "size=#{DB.size} available=#{DB.available} idle=#{DB.idle}"
first = connection_id
second = connection_id
puts "same connection reused: #{first == second}"
puts "size=#{DB.size} available=#{DB.available} idle=#{DB.idle}"

DB.with do |outer|
  inner_same = DB.with { |inner| inner.equal?(outer) }
  puts "nested with gets the same object: #{inner_same}"
  puts "available while checked out: #{DB.available}"
end
size=3 available=3 idle=0
  opening connection
same connection reused: true
size=3 available=3 idle=1
nested with gets the same object: true
available while checked out: 2

Things to note:

In connection_pool 3.0, all options are keyword arguments: checkout(timeout: 1) and reap(idle_seconds: 30), not the positional arguments of 2.x.

Pool exhaustion and timeouts

When every connection is busy, with waits up to timeout seconds and then raises ConnectionPool::TimeoutError. You can pass a different timeout for a single call:

require 'mysql2'
require 'connection_pool'

CONFIG = { host: '127.0.0.1', port: 33871, username: 'root', database: 'shop' }
DB = ConnectionPool.new(size: 2, timeout: 0.5) { Mysql2::Client.new(**CONFIG) }

slow = 2.times.map do
  Thread.new { DB.with { |c| c.query('SELECT SLEEP(1)') } }
end
sleep 0.1 # let both slow threads check out a connection

begin
  DB.with { |c| c.query('SELECT 1') }
rescue ConnectionPool::TimeoutError => e
  puts "#{e.class}: #{e.message}"
end

# a per-call timeout overrides the pool default
DB.with(timeout: 2) { |c| puts "got a connection after waiting: #{c.query('SELECT 1 AS x').first}" }
slow.each(&:join)
ConnectionPool::TimeoutError: Waited 0.5 sec, 0/2 available
got a connection after waiting: {"x" => 1}

A pool timeout in production almost always means one of three things:

Keep the with block as short as possible. Fetch the data, leave the block, and then do the slow work.

Dead connections

A pooled connection can die while it sits idle. The server may restart, a failover may happen, a firewall may drop the idle TCP session, or MySQL's wait_timeout (8 hours by default) may close it. The pool doesn't know, and it hands the dead connection to the next caller:

require 'mysql2'
require 'connection_pool'

CONFIG = { host: '127.0.0.1', port: 33871, username: 'root', database: 'shop' }
DB = ConnectionPool.new(size: 2, timeout: 1) { Mysql2::Client.new(**CONFIG) }
ADMIN = Mysql2::Client.new(**CONFIG)

def connection_id
  DB.with { |c| c.query('SELECT CONNECTION_ID() AS id').first['id'] }
end

# simulate the server dropping an idle connection (restart, wait_timeout, failover)
victim = connection_id
ADMIN.query("KILL #{victim}")

begin
  connection_id
rescue Mysql2::Error => e
  puts "1st attempt: #{e.class}: #{e.message}"
end

begin
  connection_id
rescue Mysql2::Error => e
  puts "2nd attempt: #{e.class}: #{e.message}"
end
1st attempt: Mysql2::Error::ConnectionError: Lost connection to MySQL server during query
2nd attempt: Mysql2::Error: MySQL client is not connected

The broken client went back into the pool and keeps failing. Fix this with discard_current_connection, which tells the pool to drop the connection at checkin instead of reusing it. Then retry outside the with block. A retry inside the block would get the same broken connection back, because checkout is reentrant:

require 'mysql2'
require 'connection_pool'

CONFIG = { host: '127.0.0.1', port: 33871, username: 'root', database: 'shop' }
DB = ConnectionPool.new(size: 2, timeout: 1) { Mysql2::Client.new(**CONFIG) }
ADMIN = Mysql2::Client.new(**CONFIG)

def with_db(attempts: 2)
  tries = 0
  begin
    DB.with do |conn|
      yield conn
    rescue Mysql2::Error::ConnectionError
      DB.discard_current_connection(&:close) # don't return it to the pool
      raise
    end
  rescue Mysql2::Error::ConnectionError => e
    tries += 1
    raise if tries >= attempts
    puts "  retrying after: #{e.message}"
    retry
  end
end

def connection_id
  with_db { |c| c.query('SELECT CONNECTION_ID() AS id').first['id'] }
end

victim = connection_id
ADMIN.query("KILL #{victim}")
replacement = connection_id
puts "old connection #{victim}, new connection #{replacement}"
  retrying after: Lost connection to MySQL server during query
old connection 224, new connection 225

Only retry statements that are safe to run twice. If the connection dropped in the middle of an INSERT or a transaction, you can't tell whether the server committed it. Sequel and Active Record (below) detect and replace dead connections for you.

Reaping idle connections and shutting down

After a burst of traffic, a pool keeps its peak number of connections open. reap closes connections that have been idle for longer than idle_seconds. Run it periodically, for example from a background thread. shutdown closes everything and rejects later checkouts, and reload closes everything but lets the pool open new connections:

require 'mysql2'
require 'connection_pool'

CONFIG = { host: '127.0.0.1', port: 33871, username: 'root', database: 'shop' }
ADMIN = Mysql2::Client.new(**CONFIG)
def server_connections = ADMIN.query("SHOW STATUS LIKE 'Threads_connected'").first['Value'].to_i

DB = ConnectionPool.new(size: 5, timeout: 1) { Mysql2::Client.new(**CONFIG) }

# a burst of traffic opens all five connections
5.times.map { Thread.new { DB.with { |c| c.query('SELECT SLEEP(0.1)') } } }.each(&:join)
puts "after burst:    idle=#{DB.idle} server=#{server_connections}"

sleep 1.5
DB.reap(idle_seconds: 1, &:close)   # close connections unused for 1+ second
puts "after reap:     idle=#{DB.idle} server=#{server_connections}"

DB.with { |c| c.query('SELECT 1') } # opens a fresh one on demand
puts "after query:    idle=#{DB.idle} server=#{server_connections}"

DB.shutdown(&:close)
puts "after shutdown: idle=#{DB.idle} server=#{server_connections}"
begin
  DB.with { |c| c.query('SELECT 1') }
rescue ConnectionPool::PoolShuttingDownError => e
  puts e.class
end
after burst:    idle=5 server=6
after reap:     idle=0 server=1
after query:    idle=1 server=2
after shutdown: idle=0 server=1
ConnectionPool::PoolShuttingDownError

The server count includes the ADMIN connection. Call shutdown on a graceful exit (see Signals and graceful shutdown), so the server isn't left with half-open sessions.

ConnectionPool.wrap

wrap returns a proxy that looks like a single connection. Each method call checks out a connection, calls the method on it and returns it. It's handy for migrating code that used one global client:

require 'mysql2'
require 'connection_pool'

CONFIG = { host: '127.0.0.1', port: 33871, username: 'root', database: 'shop' }

DB = ConnectionPool.wrap(size: 3, timeout: 1) { Mysql2::Client.new(**CONFIG) }

# looks like a single client, but each call checks a connection out and back in
p DB.query('SELECT 1 + 1 AS two').first
p DB.pool_size
p DB.pool_available
{"two" => 2}
3
3

Avoid the proxy for anything that needs several statements on one session: a transaction, SET variables, LAST_INSERT_ID(), or prepared statements. Consecutive calls may run on different connections. Use an explicit with block for those.

Sequel's built-in pool

Every Sequel::Database object owns a thread-safe pool. On Ruby 3.2+, the default pool is Sequel::TimedQueueConnectionPool. Each query checks a connection out and back in automatically, so you rarely touch the pool directly:

require 'sequel'

DB = Sequel.connect(
  adapter: 'mysql2', host: '127.0.0.1', port: 33871, user: 'root', database: 'shop',
  max_connections: 3,     # pool size (default 4)
  pool_timeout: 1,        # seconds to wait for a free connection (default 5)
  connect_sqls: ["SET SESSION time_zone = '+00:00'"] # run on every new connection
)

puts "pool class: #{DB.pool.class}"
puts "max_size=#{DB.pool.max_size} size=#{DB.pool.size}"

ids = 6.times.map do
  Thread.new { DB.synchronize { sleep 0.05; DB.get(Sequel.lit('CONNECTION_ID()')) } }
end.map(&:value)
puts "6 threads used #{ids.uniq.size} connections, pool size now #{DB.pool.size}"
puts "time_zone on a pooled connection: #{DB.get(Sequel.lit('@@session.time_zone'))}"

# hold every connection, then ask for one more
holders = 3.times.map { Thread.new { DB.synchronize { sleep 1.5 } } }
sleep 0.1
begin
  DB.get(1)
rescue Sequel::PoolTimeout => e
  puts "#{e.class}: #{e.message}"
end
holders.each(&:join)
pool class: Sequel::TimedQueueConnectionPool
max_size=3 size=1
6 threads used 3 connections, pool size now 3
time_zone on a pooled connection: +00:00
Sequel::PoolTimeout: timeout: 1.0

size=1 right after connecting is because Sequel.connect tests the connection by default (test: true). Other useful options:

Option Effect
max_connections: upper limit of the pool (default 4)
pool_timeout: seconds to wait before Sequel::PoolTimeout (default 5)
connect_sqls: SQL strings run on each new connection
after_connect: a proc called with each new raw connection
preconnect: true open all max_connections connections up front (:concurrently opens them in parallel)
test: false don't open a connection in Sequel.connect

Pinning a connection with synchronize

DB.synchronize checks out one connection for the duration of the block. All queries the thread runs inside it, including nested transaction blocks, use that same connection. Use it when statements depend on session state:

require 'sequel'

DB = Sequel.connect(adapter: 'mysql2', host: '127.0.0.1', port: 33871, user: 'root',
                    database: 'shop', max_connections: 2)

# one checkout for several statements: they all run on the same session
DB.synchronize do
  DB.run('SET @request_id = 42')
  puts "same checkout sees:      #{DB.get(Sequel.lit('@request_id'))}"

  # another thread can't use this connection, so it gets a different one
  other = Thread.new { DB.get(Sequel.lit('@request_id')).inspect }
  puts "another connection sees: #{other.value}"
end
same checkout sees:      42
another connection sees: nil

Session state stays on a connection after it goes back to the pool. A later checkout by an unrelated request could see @request_id = 42. Reset what you set, or use connect_sqls for settings that every connection should share.

Validating connections

Sequel recognizes disconnect errors. It raises Sequel::DatabaseDisconnectError and removes the dead connection from the pool, so only one query fails. The connection_validator extension prevents even that one failure: it pings connections that have been idle for longer than connection_validation_timeout before handing them out:

require 'sequel'

DB = Sequel.connect(adapter: 'mysql2', host: '127.0.0.1', port: 33871, user: 'root',
                    database: 'shop', max_connections: 2)
ADMIN = Sequel.connect(adapter: 'mysql2', host: '127.0.0.1', port: 33871, user: 'root',
                       database: 'shop', max_connections: 1)

def kill_pooled_connection
  id = DB.get(Sequel.lit('CONNECTION_ID()'))
  ADMIN.run("KILL #{id}")
  id
end

kill_pooled_connection
begin
  DB.get(1)
rescue Sequel::DatabaseDisconnectError => e
  puts "without validator: #{e.class}"
end
puts "next query works:  #{DB.get(1)}" # Sequel removed the dead connection

DB.extension(:connection_validator)
DB.pool.connection_validation_timeout = -1 # validate on every checkout
old = kill_pooled_connection
new = DB.get(Sequel.lit('CONNECTION_ID()'))
puts "with validator:    killed #{old}, query ran on #{new}"
without validator: Sequel::DatabaseDisconnectError
next query works:  1
with validator:    killed 241, query ran on 242

The default validation threshold is 3600 seconds, so most checkouts skip the ping. A value of -1 adds a round trip to every checkout. Only use it together with coarse checkouts, such as one DB.synchronize per web request in a Rack middleware. The connection_expiration extension retires connections after a maximum age, which helps behind load balancers that drop long-lived sessions.

Active Record's pool

Active Record keeps one pool per database configuration (and per role and shard). In Rails 8.1 the size setting is called max_connections. The old pool: key still works:

# config/database.yml
production:
  adapter: mysql2
  url: <%= ENV["DATABASE_URL"] %>
  max_connections: <%= ENV.fetch("RAILS_MAX_THREADS", 5) %>
  checkout_timeout: 5   # wait before ActiveRecord::ConnectionTimeoutError
  idle_timeout: 300     # close connections idle this long (0 = never)
  min_connections: 0    # keep at least this many open
  keepalive: 600        # ping idle connections this often
  max_age: 3600         # retire connections older than this (default: never)

Outside Rails, pass the same keys to establish_connection. connection_pool.stat shows what the pool is doing:

require 'active_record'

ActiveRecord::Base.establish_connection(
  adapter: 'mysql2', host: '127.0.0.1', port: 33871, username: 'root', database: 'shop',
  max_connections: 3,   # called `pool:` before Rails 8.1 (still accepted)
  checkout_timeout: 1,  # seconds to wait for a free connection (default 5)
  idle_timeout: 60      # close connections idle this long (default 300)
)

class Product < ActiveRecord::Base; end
ActiveRecord::Schema.verbose = false
ActiveRecord::Schema.define do
  create_table :products, force: true do |t|
    t.string :name
  end
end
Product.create!(name: 'pen')
ActiveRecord::Base.release_connection # main thread gives its connection back

pool = ActiveRecord::Base.connection_pool
p pool.stat

threads = 3.times.map do
  Thread.new do
    ActiveRecord::Base.with_connection do |conn|
      sleep 0.1
      conn.select_value('SELECT CONNECTION_ID()')
    end
  end
end
p threads.map(&:value).uniq.size
p pool.stat
{size: 3, connections: 1, busy: 0, dead: 0, idle: 1, waiting: 0, checkout_timeout: 1.0}
3
{size: 3, connections: 3, busy: 0, dead: 0, idle: 3, waiting: 0, checkout_timeout: 1.0}

In a Rails request, a Sidekiq job or a rails runner script, the framework's executor returns connections for you at the end of each unit of work. The danger is threads you start yourself.

Leaking connections from your own threads

ActiveRecord::Base.lease_connection (named connection before Rails 7.2) ties a connection to the current thread until something releases it. Long-running threads that lease connections and never give them back exhaust the pool:

require 'active_record'

ActiveRecord::Base.establish_connection(
  adapter: 'mysql2', host: '127.0.0.1', port: 33871, username: 'root', database: 'shop',
  max_connections: 2, checkout_timeout: 0.5
)
class Product < ActiveRecord::Base; end
pool = ActiveRecord::Base.connection_pool

# LEAK: lease_connection pins a connection to the thread until the thread
# releases it, and these threads never do
leakers = 2.times.map do
  Thread.new do
    ActiveRecord::Base.lease_connection.select_value('SELECT 1')
    sleep 1.5
  end
end
sleep 0.2
p pool.stat.slice(:size, :connections, :busy, :idle)

begin
  Product.count
rescue ActiveRecord::ConnectionTimeoutError => e
  puts "#{e.class}: #{e.message.lines.first.strip}"
end
leakers.each(&:join)

# the threads are gone; the pool reclaims their connections on the next checkout
puts "after threads exit: #{Product.count} products"
{size: 2, connections: 2, busy: 2, idle: 0}
ActiveRecord::ConnectionTimeoutError: could not obtain a connection from the pool within 0.500 seconds (waited 0.500 seconds); all pooled connections were in use
after threads exit: 1 products

The fix is to wrap database work in ActiveRecord::Base.with_connection { ... }, as in the previous example. In a Rails app, Rails.application.executor.wrap { ... } does the same and also resets query caches and other per-request state. The pool recovers connections from dead threads, but a thread pool worker never dies, so its leaked connection is never returned.

Sizing the pool

The pool size is a per-process limit. The database sees the sum over all processes:

server connections = processes × pool size (+ consoles, cron jobs, migrations, monitoring)

Rules of thumb:

When many processes need connections, put an external pooler between the app and the database. Options are PgBouncer or the pooler your cloud database provides for PostgreSQL, and ProxySQL for MySQL. Thousands of client connections then share a few dozen server connections. In PgBouncer's transaction mode, a server connection is only yours for one transaction, so session state doesn't carry over between statements (session SETs, advisory locks, LISTEN). For prepared statements, use a PgBouncer version that tracks them or disable them in the client (prepared_statements: false in Active Record).

Pools and fork

Servers like Puma (cluster mode), Unicorn, Pitchfork and Resque fork worker processes. A forked child inherits the parent's open sockets. If both processes use the same socket, their packets interleave and both connections break. The rule is that each process opens its own connections:

require 'mysql2'
require 'connection_pool'
require 'sequel'

CONFIG = { host: '127.0.0.1', port: 33871, username: 'root', database: 'shop' }
POOL = ConnectionPool.new(size: 2) { Mysql2::Client.new(**CONFIG) }
DB = Sequel.connect(adapter: 'mysql2', host: '127.0.0.1', port: 33871, user: 'root', database: 'shop')

pool_id = -> { POOL.with { |c| c.query('SELECT CONNECTION_ID() AS id').first['id'] } }
seq_id  = -> { DB.get(Sequel.lit('CONNECTION_ID()')) }

puts "parent: pool=#{pool_id.call} sequel=#{seq_id.call}"

DB.disconnect # Sequel: close connections before forking
2.times do
  fork { puts "child:  pool=#{pool_id.call} sequel=#{seq_id.call}" }
  Process.wait
end
parent: pool=264 sequel=263
child:  pool=265 sequel=266
child:  pool=267 sequel=268

Each child got fresh server connections, and none reused the parent's sessions.

Checklist

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents