Search code examples
ruby-on-railsrubyruby-on-rails-5pgbouncer

Can I / Should I disable Ruby On Rails Database Connection Pooling when using PgBouncer?


Can I disable Ruby on Rails connection pooling completely?

And would this be okay considering PgBouncer already handles database connection pooling?


Solution

  • No.

    PgBouncer advertises itself to clients as a Postgres server and then manages connections to the actual Postgres server. We don't need to get into any further detail than that for PgBouncer -- from the Rails side of things, the PgBouncer instance is the Postgres server, so let's explain why starting from there.

    In Rails there are two primary factors to consider for concurrency: the number of inbound client requests that can be made to its web server and the size of the connection pool for the database.

    If your connection pool size is 1 then your application is effectively single-threaded: every time an inbound client request is made that must make a database query, the request must check out a connection to the database from the pool. When the pool size is 1 and the number of concurrent inbound requests is greater than 1, every request after the first request must be put on hold while the first request completes its query and returns the connection to the pool. If the first request takes a long time to complete then subsequent requests may timeout while waiting for an available connection from the pool.

    So from the Rails side, you want to have a connection pool with a size larger than 1 to allow for concurrency. If you set it to a size of 1 then it doesn't matter how you have PgBouncer configured; Rails will always make at most one connection to the database and all threads must share that single connection.

    You can read more about connection pools in Rails at ActiveRecord::ConnectionAdapters::ConnectionPool < Object.