Sub topic 2
What connection pooling does
This chapter explains what a connection pool is, what it changes between your application and PostgreSQL, and where pooling can live. It assumes you know basic SQL and psql, understand PostgreSQL roles and the max_connections setting, and have a general picture of TCP client/server connections. The previous chapter covered why each PostgreSQL connection costs memory and a backend process. This chapter covers the remedy, and the next one covers how PgBouncer implements it.
The core idea: separate clients from server connections
Without a pool, every client connection is a server connection. If 800 application workers each open a connection, PostgreSQL runs 800 backend processes, even if only 15 of them are executing a query at any given moment. The other 785 hold memory and a slot in max_connections while they wait for the application to do something else.
A connection pool breaks that one-to-one link. The application opens connections to the pool, and the pool owns a smaller set of real connections to PostgreSQL. When a client has work to do, the pool lends it a server connection. When the work is done, the pool takes the connection back and can hand it to someone else.
This works because most application connections are idle most of the time. A web request spends its time rendering templates, calling other services, and waiting on the network. The database sees only short bursts of activity from each connection.
What a pool saves you
Pooling helps in three separate ways. They matter in different situations, so it is worth keeping them apart.
- Fewer backend processes. PostgreSQL forks one process per connection. A pool that keeps 20 server connections means 20 backends, however many clients exist. This reduces memory use and the cost of managing many processes, such as snapshot computation, which scales with the number of connections.
- No repeated connection setup. Opening a PostgreSQL connection involves a TCP handshake, optional TLS negotiation, authentication, and a fork. A pool does this once and reuses the connection. This matters most for short-lived clients, such as scripts, serverless functions, and applications that open a connection per request.
- A limit on concurrency. If a traffic spike sends 2000 queries at once, an unpooled database tries to run all of them and slows down for everyone. A pool with 20 server connections runs 20 at a time and queues the rest. Total throughput often stays higher, because the database is not thrashing between too many active processes.
The third point surprises people. Queuing at the pool is often faster overall than letting everything run at once, because a database server has a finite number of CPU cores and disk channels. Past a certain point, more concurrent queries add contention, not throughput. Chapter 9 covers how to choose the pool size.
The lifecycle of a pooled connection
A pooled server connection moves between two main states. It is either idle in the pool or assigned to a client.
When a client sends a query and no idle server connection is available, one of two things happens. If the pool has not yet reached its size limit, it opens a new server connection. If it has reached the limit, the client waits in a queue until another client releases a connection. That wait is the price of the concurrency limit, and it is the first thing to check when a pooled application feels slow.
When the connection is returned
The most important design choice in a pool is when a server connection goes back to the pool. The answer decides which PostgreSQL features still work, so it determines how safely you can pool.
| Release point | Server connection is held for | Sharing efficiency | Session features preserved |
|---|---|---|---|
| End of client session | The whole time the client is connected | Low | All of them |
| End of transaction | One transaction at a time | High | Only features scoped to a transaction |
| End of statement | One statement at a time | Highest | Almost none, and multi-statement transactions are not allowed |
PgBouncer names these options session pooling, transaction pooling, and statement pooling. Session pooling mostly saves connection setup cost. Transaction pooling is the one that lets thousands of clients share a few dozen server connections. Chapter 5 compares them in detail, and Chapter 7 covers what breaks under transaction pooling.
What the pool has to clean up
PostgreSQL connections carry state: session settings from SET, temporary tables, prepared statements, advisory locks, and listeners from LISTEN. If a pool hands a connection to a new client with the previous client's state still attached, the second client sees surprising behavior.
A pool therefore does one of two things when it takes a connection back:
- It resets the connection, typically by running
DISCARD ALLor an equivalent, which drops session state and gives the next client a clean connection. - It restricts the sharing so that state cannot leak, for example by keeping the connection with one client for the whole session.
Resetting costs a small amount of time per release. Restricting costs sharing efficiency. Every pooling mode is a different trade between these two.
A short example shows the risk. Suppose two clients share a server connection and the pool does not reset it:
-- Client A, on a shared server connection
SET search_path = tenant_a;
SELECT count(*) FROM orders; -- reads tenant_a.orders
-- Connection returns to the pool, then Client B receives it
SELECT count(*) FROM orders; -- may read tenant_a.orders, not B's tableClient B never set search_path, yet it inherits Client A's setting. Pools avoid this with resets or by limiting where sharing happens, which is why the pool mode matters for correctness and not only for speed.
What a pool does not do
A pool is easy to over-credit, so be clear about its limits.
- It does not make queries faster. A slow query runs at the same speed through a pool. The pool only manages connections.
- It does not add capacity. It protects the database from too many connections, but a database that is short on CPU or I/O stays short. A pool can hide that problem as queue time.
- It does not fix long transactions. A client that opens a transaction and idles holds a server connection the whole time. With a small pool, a few such clients can starve everyone else.
- It does not remove the need for application-side limits. If your application opens an unbounded number of client connections, the pool becomes the place where they pile up.
Where a pool can live
Pooling can happen in three places, and they are not mutually exclusive.
| Location | Example | Strength | Limitation |
|---|---|---|---|
| In the application process | A driver or framework pool, such as HikariCP, SQLAlchemy's pool, or pgx pool | No extra component to run, low latency | Each application process has its own pool, so total server connections grow with the number of processes |
| A separate proxy process | PgBouncer | One pool shared by all applications, regardless of how many instances exist | One more component to run, monitor, and keep available |
| Inside the database or a managed service | A pooler offered by a cloud provider | Operated for you | Less control over settings and behavior |
Application-side pools are common and useful, but they have an arithmetic problem. If each of 50 application instances keeps a pool of 20, the database sees up to 1000 connections. Adding instances to handle load increases the connection count, which is the opposite of what you want. A shared external pooler caps the number of server connections independent of how many application instances exist. This is the main reason teams add PgBouncer even when their application already has a pool.
You can combine both. Keep a small application-side pool for connection reuse inside each process, and point it at PgBouncer, which does the cross-process sharing. In that setup, size the application pool for per-process concurrency and let PgBouncer enforce the global limit.
Recognizing a case that needs pooling
Pooling is a good fit when you see these symptoms:
FATAL: sorry, too many clients alreadyerrors from PostgreSQL.- A high connection count in
pg_stat_activitywhere most rows havestate = 'idle'. - Memory pressure on the database host that scales with the number of connections.
- Frequent short-lived connections, such as from scripts, cron jobs, or serverless functions.
- Many application instances that each hold a pool.
You can check the first two with a query against pg_stat_activity:
SELECT state, count(*) AS connections
FROM pg_stat_activity
WHERE backend_type = 'client backend'
GROUP BY state
ORDER BY connections DESC;If most connections show idle, the database is paying for connections that do no work, and a pooler can reduce that cost. If most show active, the database is busy running queries. A pooler will not help much there, and you should look at query performance and hardware instead.
Trade-offs to accept
Adding a pool changes your system in ways you should plan for.
- An extra network hop. Each query now passes through the pooler. On a local network this adds well under a millisecond, but it is not zero.
- A new failure point. If the pooler is down, the application cannot reach the database. Chapter 14 covers availability.
- Restricted session features. Depending on the mode, some PostgreSQL features stop working or need workarounds.
- Queueing instead of errors. Under overload, clients wait rather than fail immediately. This is usually better, but it needs timeouts so waits do not grow without bound. Chapter 10 covers them.
Exercise
An application runs 40 instances, each with its own driver pool of up to 25 connections. PostgreSQL has max_connections = 200. Why can this fail under load, and how does a shared external pooler change the arithmetic?
Show answer
The instances can open up to 40 × 25 = 1000 connections, which exceeds max_connections = 200, so PostgreSQL rejects the excess with "too many clients already". Adding more instances makes it worse. A shared pooler such as PgBouncer accepts the 1000 client connections but opens only a fixed number of server connections, for example 20 per user and database pair, so the database stays under its limit. Excess clients queue at the pooler instead of failing.
Exercise
A pool returns a server connection to the idle list without resetting it. Client A had run SET searchpath = tenanta. Why is this a correctness problem, and what are the two general ways a pool avoids it?
Show answer
The next client receives a connection that still has tenanta in its searchpath, so its unqualified table names resolve to the wrong schema. A pool avoids this by resetting the connection when it is returned (for example with DISCARD ALL), or by limiting sharing so that session state stays with one client, such as holding the connection for the whole client session.