0%
PostgreSQL Deep Dive: MVCC, Vacuum, Plans, and Replication
Architecture and Storage
MVCC and Vacuum
Indexes and Query Planning
Connection Pooling
Postgres serves each client connection with a dedicated operating system process. This design is robust, since a crash in one backend cannot corrupt another, but it makes connections expensive to create and expensive to keep in large numbers. Applications that open thousands of connections, or open a new one per request, hit limits long before the database runs out of CPU for queries. This section explains what a connection costs, why too many connections hurt throughput and why pooling is essential for almost every production deployment.
A process per connection
When a client connects, the postmaster forks a new backend process, which authenticates the client, loads catalog caches as queries need them and then serves every query for that session. The fork, authentication, TLS handshake and cache warmup take from a few milliseconds to tens of milliseconds, and the first queries of a new session run slower while caches fill. For a web request that runs one 2 millisecond query, opening a connection can cost five or ten times more than the query itself.
Memory per backend
Each backend has a baseline memory footprint of a few megabytes for its process, plus private caches of catalog entries and compiled plans that grow with the number of tables, functions and prepared statements used. Sessions that have touched many relations in a schema with thousands of partitions can hold tens of megabytes each. On top of this, every sort or hash in a query can use up to work_mem. A thousand mostly idle connections can therefore consume many gigabytes that would otherwise serve as page cache.
max_connections
max_connections sets the maximum number of concurrent client connections, 100 by default. Several shared memory structures are sized from it, including the lock table and the array of process states, so raising it to several thousand increases memory use even when connections are idle. Each backend also appears in every snapshot computation, which historically made snapshot building slower as the number of connections grew. Version 14 greatly improved snapshot scalability, but many connections still add overhead throughout the system.
Why more connections can mean less throughput
A server with 16 cores can execute at most 16 queries at once. If 500 connections are active, the operating system switches among 500 processes, each query takes longer, caches are shared among more work, and lightweight locks on shared structures see more contention. Throughput typically rises with active connections up to a small multiple of the core count, then flattens and falls. Beyond that point, adding connections only adds queueing inside the database, where it is less efficient than queueing in a pool.
Idle connections are not free
Idle connections use memory and process slots, keep catalog caches alive, and count toward max_connections. An idle connection inside an open transaction is worse: it holds locks and a snapshot that blocks vacuum. Applications with many instances, each with its own connection pool of twenty, can reach thousands of connections that are almost all idle, wasting resources and hitting the limit during deploys when old and new instances overlap.
Connection storms
When an application restarts, scales out or recovers from a network blip, every instance may try to open its connections at once. Hundreds of simultaneous forks and authentications, especially with expensive password hashing such as SCRAM and TLS, can saturate the CPU of the database and slow everything else. Connection storms often turn a brief network problem into a longer outage. Pools that open connections gradually and limit the rate of new connections soften these storms.
Serverless and short lived clients
Serverless functions and short lived jobs are an extreme case: each invocation may open a connection, run one query and exit. At thousands of invocations per second, the database spends most of its time setting up and tearing down sessions, and can hit max_connections during traffic spikes. These environments require an external pooler or a proxy service between the clients and the database, since in process pools do not survive between invocations.
Superuser reserved connections
superuser_reserved_connections, three by default, keeps a few slots available for superusers even when max_connections is reached, so an administrator can still log in to diagnose and fix a connection exhaustion incident. Since version 16, reserved_connections adds slots for roles granted pg_use_reserved_connections, useful for monitoring agents. Ensuring that operational tools have reserved access, and that applications never run as superuser, keeps a way in during the worst incidents.
Measuring connection usage
pg_stat_activity shows every connection with its state: active, idle, idle in transaction and others. Counting connections by state, by application_name and by client address shows who uses the connection budget and how much of it is idle. A healthy pooled system has few active connections, close to the number of cores, and a pool that keeps them busy. A system with hundreds of idle connections and a handful of active ones is a candidate for consolidating pools.
The pooling idea
A connection pool keeps a set of open server connections and lends them to clients for the duration of a unit of work, then takes them back for the next client. The expensive setup happens once per server connection, the number of server connections stays bounded regardless of the number of clients, and excess demand waits in the pool queue instead of overloading the database. Pools can live inside the application process, in a separate pooler service such as PgBouncer, or in both layers.
Authentication cost
SCRAM-SHA-256, the recommended password method, deliberately performs thousands of hash iterations to make stolen verifiers hard to crack. That cost is paid on every new connection, so a connection storm with SCRAM consumes noticeable CPU on the server. Pools amortize it by authenticating each server connection once. Certificate authentication and TLS session resumption reduce handshake cost, but the general lesson is that each new connection carries security work that should not be repeated per request.
Catalog caches and large schemas
Each backend builds its own caches of catalog entries, relation descriptors and function definitions as queries touch them. In schemas with thousands of tables or partitions, a long lived backend that has touched most of them can hold large caches, and a new backend pays to rebuild them on first use. This is one reason why recycling connections too aggressively hurts, and why very large schemas benefit from fewer, longer lived server connections.
Connection limits in managed services
Managed Postgres services often set max_connections from the instance size and reserve some slots for their own agents. Smaller instances may allow only a few hundred connections, which an application with many instances reaches quickly. Since raising the limit usually means paying for a larger instance, pooling is often the cheapest way to fit a growing application on a modest database, and many providers bundle a pooler for this reason.
Threads versus processes
Some databases serve connections with threads, which share memory and switch more cheaply, and the Postgres community has discussed moving to a threaded model. Even with threads, though, the fundamental limit remains: a server can only run as many queries at once as it has cores, and too much concurrency causes contention. Pooling and admission control stay useful whatever the execution model, because they address queueing, not only setup cost.
Connection setup in numbers
On a typical server, forking a backend takes around a millisecond, a TLS handshake adds one or two network round trips, SCRAM authentication adds CPU work measured in milliseconds, and the first queries pay for catalog lookups. Across a data center network the total is often 5 to 20 milliseconds, and across regions it can exceed 100. Measuring it once with a simple loop of connect and disconnect makes the case for pooling concrete for any team.
Connections and failover
After a failover, every client reconnects to the new primary at once, so a system with thousands of direct connections creates a storm at the worst moment, when the new primary is also warming its caches. A pooled system reconnects only its bounded set of server connections. Fewer, pooled connections make failovers faster and gentler, which is another argument for pooling beyond everyday efficiency.
Each connection is a backend process with setup cost, memory and scheduling overhead. Throughput peaks at a small multiple of the core count, so thousands of connections hurt rather than help. Pool connections, bound the number of server connections and let excess work wait in the pool.