LeepCast
Subscribe
All posts
Software

Database Connection Pooling Explained: Pool Sizing, PgBouncer Modes, and the Math That Keeps Postgres Alive

Why every PostgreSQL connection costs a whole server process, how to size an application pool from cores instead of guesses, what PgBouncer's session, transaction, and statement modes break, and a working setup for both layers.

LeepCast6 min read

Most PostgreSQL outages that start with the error "sorry, too many clients already" are not caused by heavy queries. They are caused by arithmetic. Someone scaled the web tier from four instances to twenty, each instance opened its own pool of connections, and the total quietly crossed the database's connection limit. Connection pooling is the fix, but only when the pools are sized deliberately and the layers between the application and the database agree on what a connection means.

This guide covers why connections are expensive, how application-side pools work, a starting formula for pool size, and how an external pooler such as PgBouncer multiplexes many clients onto a few server connections, including the features its transaction mode breaks.

Why a Postgres connection is expensive

PostgreSQL uses a process-per-connection model. A supervisor process called the postmaster listens for connection requests, and for each new client it spawns a dedicated backend process. That backend parses, plans, and executes every query the client sends, and it coordinates with the other backends through shared memory and semaphores. Opening a connection therefore means creating an operating-system process, authenticating, and setting up session state, all before the first query runs.

Because each connection is a real process, the server caps how many it will accept. The max_connections setting defaults to 100 on a typical install, and superuser_reserved_connections holds three of those back for administrators by default. Raising the limit is possible, but every extra backend competes for the same CPU cores and memory. More connections do not mean more throughput once the cores are busy; they mean more context switching.

What an application-side pool does

A connection pool keeps a set of already-open connections inside the application process and lends them out. A request checks a connection out, runs its queries, and returns it, so the cost of process creation and authentication is paid once per connection rather than once per request. When every connection is busy, new requests wait in a queue instead of opening more connections.

The node-postgres Pool is a representative example. Its max option defaults to 10 clients. Idle clients are closed after idleTimeoutMillis, which defaults to 10 seconds. The connectionTimeoutMillis option defaults to 0, meaning a caller waits for a client forever, which is rarely what a web service wants. When the pool is full, pool. connect() places the request in a first-in, first-out queue until a client is released.

Two rules matter more than any setting. First, every client that is checked out must be released, or the pool slowly drains until every caller hangs. Second, a transaction must run on a single checked-out client. A convenience method like pool. query() may send consecutive queries to different connections, so BEGIN and COMMIT could land on two separate sessions.

javascript
import pg from "pg";
const { Pool } = pg;

const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
  max: 10,
  idleTimeoutMillis: 10_000,
  connectionTimeoutMillis: 2_000, // fail fast instead of waiting forever
});

// Idle clients can error if the server restarts; without a listener,
// Node treats it as an uncaught error and the process can crash.
pool.on("error", (err) => {
  console.error("idle pg client error", err);
});

export async function transfer(fromId, toId, cents) {
  const client = await pool.connect();
  try {
    await client.query("BEGIN");
    await client.query(
      "UPDATE accounts SET balance = balance - $1 WHERE id = $2",
      [cents, fromId]
    );
    await client.query(
      "UPDATE accounts SET balance = balance + $1 WHERE id = $2",
      [cents, toId]
    );
    await client.query("COMMIT");
  } catch (err) {
    await client.query("ROLLBACK");
    throw err;
  } finally {
    client.release(); // always return the client
  }
}

How big should the pool be?

Intuition says a bigger pool serves more users. The HikariCP project's well-known pool-sizing guide argues the opposite, and its reasoning comes down to hardware. A CPU core runs one thread at a time; past the core count, extra active connections only time-slice against each other. Connections are worth having beyond the core count only to cover time spent blocked on disk or network I/O.

The guide offers a starting formula attributed to the PostgreSQL project: connections = (core_count × 2) + effective_spindle_count. Core count means physical cores, not hyperthreads. The effective spindle count is roughly the number of disks doing real work; it drops toward zero when the active data set is fully cached in memory. The guide is explicit that this is a starting point to load-test and adjust, not a law, and that it has not been analyzed specifically for SSDs.

You want a small pool, saturated with threads waiting for connections.

— HikariCP wiki, About Pool Sizing

A worked example

Suppose the database server has 8 physical cores and the working set fits in memory, so the effective spindle count is about 0. The formula suggests (8 × 2) + 0 = 16 connections doing useful work at the database. Now look at the application side: 20 container instances, each with the node-postgres default of 10 connections, can open 200 connections. That is double the default max_connections of 100, and more than twelve times the number the hardware can use efficiently.

The total that matters is always the sum across every process that can connect: web instances, background workers, cron jobs, migration runners, and admin tools. Divide the database's useful budget by the number of instances and set each pool's max accordingly. In this example that would be fewer than one connection per instance, which is exactly the situation where an external pooler becomes necessary.

When you need an external pooler

Application pools only share connections within one process. Serverless functions, autoscaling containers, and fleets of workers each bring their own pool, and none of them can lend an idle connection to a neighbor. An external pooler sits between all of those clients and the database. Clients connect to it cheaply, and it multiplexes them onto a small, fixed set of real server connections.

PgBouncer is the most widely deployed option for PostgreSQL. It listens on port 6432 by default. Its default_pool_size, which defaults to 20, caps server connections per user and database pair, while max_client_conn, which defaults to 100, caps how many clients may connect to PgBouncer itself. The max_db_connections setting caps server connections per database across all users and is unlimited by default. Idle server connections are closed after server_idle_timeout, which defaults to 600 seconds.

Session, transaction, and statement pooling

The pool_mode setting decides when a server connection goes back into the pool, and it is the most consequential choice in the configuration.

  • Session mode, the default, assigns a server connection to a client for the whole client session. Every PostgreSQL feature works, but a mostly idle client still holds a server connection, so multiplexing is limited.
  • Transaction mode assigns a server connection only for the duration of a transaction. Between transactions the connection serves other clients, which is how thousands of clients can share a few dozen backends.
  • Statement mode returns the connection after every statement and forbids multi-statement transactions, effectively enforcing autocommit. It is intended for narrow uses such as PL/Proxy.

Transaction mode is where the real savings are, and it is also where applications break, because anything tied to a session can leak to whichever client gets the connection next. PgBouncer's documentation lists the features that never work in transaction mode:

  • SET and RESET of session settings
  • LISTEN
  • WITH HOLD cursors
  • SQL-level PREPARE and DEALLOCATE
  • Temporary tables declared with PRESERVE ROWS or DELETE ROWS
  • LOAD
  • Session-level advisory locks

Some neighbors do work: NOTIFY, cursors declared WITHOUT HOLD, and temporary tables created with ON COMMIT DROP all stay inside a single transaction.

The prepared statement caveat

Many drivers use protocol-level prepared statements automatically, and those were historically incompatible with transaction pooling because the statement lived on one backend while the next query might run on another. PgBouncer 1.21.0, released in October 2023, added tracking of protocol-level named prepared statements in transaction and statement modes, controlled by max_prepared_statements. Since version 1.24.0 that setting defaults to 200, the size of the per-connection cache. SQL-level PREPARE statements remain unsupported. If you run an older PgBouncer or have set this option to 0, configure your driver to avoid named prepared statements.

A two-layer configuration

A common production layout keeps a small pool in each application instance, points it at PgBouncer instead of PostgreSQL, and lets PgBouncer hold the real budget of server connections. The following configuration accepts up to 2,000 client connections while never opening more than 40 server connections to the database:

ini
[databases]
appdb = host=10.0.0.5 port=5432 dbname=appdb

[pgbouncer]
listen_addr = 0.0.0.0
listen_port = 6432
auth_type = scram-sha-256
auth_file = /etc/pgbouncer/userlist.txt
pool_mode = transaction
max_client_conn = 2000
default_pool_size = 20
max_db_connections = 40
max_prepared_statements = 200

Raising max_client_conn may also require raising the operating system's limit on open file descriptors, since every client socket consumes one. Keep max_db_connections comfortably below the server's max_connections so that administrators, replication, and monitoring still have room.

A production checklist

  1. Add up every process that can connect and confirm the total stays below max_connections, with headroom for maintenance.
  2. Start each application pool small, using cores times two as the database-wide target, and load-test before raising it.
  3. Set a finite connection-acquire timeout so overload surfaces as fast errors rather than hung requests.
  4. Always release connections in a finally block, and run each transaction on one checked-out connection.
  5. Use an external pooler when instance counts are high or unpredictable, such as with serverless or autoscaling.
  6. Before switching PgBouncer to transaction mode, search the codebase for session-level SET, LISTEN, advisory locks, and SQL PREPARE.
  7. Verify your PgBouncer version and max_prepared_statements value match how your driver uses prepared statements.

Connection pooling is less about a clever library and more about a budget. The database can do a fixed amount of concurrent work, set by its cores and storage. Every pool in the system is a claim on that budget, and the job is to make sure the claims add up to something the hardware can actually serve.

Share

Enjoyed this?

Get the next deep dive in your inbox. No spam — just the stories worth reading.

Subscribe to the newsletter

Comments