Book a 30-min callBook a call

PostgreSQL connection pooling: why connections are expensive and how PgBouncer modes work

Why each PostgreSQL connection is a process, how app-side pools and PgBouncer differ, what breaks in transaction mode, and how to size and monitor a pool.

Seven small client boxes with lines into one pooler box, which connects to a database cylinder through three thick lines.
Written by
BYD Tech
Published
Topic
Deep dives
Reading time
14 min read

Questions people ask

How many connections should a PostgreSQL pool have?

Fewer than you think. A common starting point, from the HikariCP wiki and attributed there to the PostgreSQL project, is twice the database server’s CPU cores plus the number of disks, then adjust by measuring. Make sure the sum of every pool in every process stays under max_connections with headroom.

What is the difference between session and transaction pooling in PgBouncer?

In session mode a client keeps its server connection until it disconnects, so every PostgreSQL feature works but there is little sharing. In transaction mode the connection goes back to the pool when each transaction ends, so many clients share few connections, but session state such as SET, session advisory locks, LISTEN and SQL PREPARE does not carry over.

Does PgBouncer support prepared statements in transaction mode?

Protocol-level named prepared statements, yes, since PgBouncer 1.21, when max_prepared_statements is set above zero; the current documentation lists 200 as the default. SQL-level PREPARE, EXECUTE and DEALLOCATE are passed through untracked and still break in transaction mode.

Do I need PgBouncer if my framework already has a connection pool?

Not always. With a handful of long-running app processes, their pools can stay well under max_connections. Add an external pooler when the number of processes, containers or function instances grows, or changes with autoscaling, so their pools together would exceed what the database can hold.

Why do serverless functions run out of database connections?

Every function instance opens its own connections, instances multiply with traffic, and idle instances keep connections open. Use a pool of one per instance, connect through a pooler in transaction mode, and cap function concurrency.

Building something like this?