Sub topic 1
Why PostgreSQL Connections Are Expensive
Prerequisites
This chapter assumes you can:
- Run basic SQL and use the
psqlclient. - Describe PostgreSQL roles, databases, and the
max_connectionssetting. - Edit configuration files and run commands on a Linux shell.
- Explain what a TCP connection is and how a client talks to a server.
You do not need any PgBouncer knowledge yet. This chapter explains the problem that PgBouncer solves. Later chapters cover the tool itself.
The process-per-connection model
PostgreSQL does not use threads for client connections. When a client connects, the main process (the postmaster) calls fork() and creates a new operating system process called a backend. That backend serves this one client until the client disconnects.
You can see this on any running server:
SELECT pid, usename, datname, state, backend_start
FROM pg_stat_activity
WHERE backend_type = 'client backend';Each row is one backend process. The pid column matches an operating system process ID, so you can also find the same processes with ps.
ps -ef | grep "postgres:" | headThe one-process-per-client design is simple and robust. A crash in one backend does not corrupt the memory of another. The cost is that every connection carries the weight of a full process, whether or not it is doing any work.
What a connection costs
The cost appears in four places: setup time, memory, scheduling, and shared bookkeeping.
Setup time
Opening a connection involves several steps before the first query can run:
- The client opens a TCP connection to the server.
- If TLS is enabled, both sides negotiate encryption.
- The postmaster forks a backend process.
- The client and server run authentication. With
scram-sha-256, this includes deliberately expensive password hashing work. - The backend loads catalog caches and other per-session state as it runs its first queries.
On a local network this often takes a few milliseconds. With TLS and a distant server it can take tens of milliseconds. An application that opens a new connection for each web request pays this on every request.
Memory
Each backend uses private memory. A freshly started idle backend commonly uses a few megabytes. A backend that has run complex queries uses more, because of these settings and caches:
work_memis allocated per sort or hash operation inside a query, not per connection. A single query with several such operations can use several multiples of it.temp_buffersis allocated per session for temporary tables.- The catalog and plan caches grow as the session touches more tables and functions.
maintenance_work_memapplies to maintenance commands such asCREATE INDEXandVACUUM.
Memory grows with the number of backends, so a high connection count multiplies these costs. Idle backends hold on to what they have already cached.
Scheduling
Each active backend competes for CPU. The operating system must switch between processes, and every switch has a cost. When many more processes are runnable than there are CPU cores, throughput stops rising and then falls, while latency rises. The database spends more time switching and waiting for locks than doing useful work.
Shared bookkeeping
Backends coordinate through shared memory. PostgreSQL keeps a list of running transactions so that every query can build a snapshot (the set of transactions it can see). Taking a snapshot requires scanning that list, and the work grows with the number of connections. Lock tables, buffer mapping, and other shared structures also see more contention as the backend count rises.
This is the main reason that adding connections does not add capacity. Past a point, each extra backend slows the others down.
Idle connections still cost something
Many teams believe that only active queries matter. Idle connections are cheaper than busy ones, but they are not free:
- Each holds its memory.
- Each occupies one of the
max_connectionsslots. - Each is a candidate for the snapshot scan in older PostgreSQL versions. Improvements in recent versions reduced this cost, but it has not disappeared.
- An
idle in transactionconnection is worse. It can hold locks and keep old row versions from being cleaned up byVACUUM.
You can measure how your connections are spread across states:
SELECT state, count(*)
FROM pg_stat_activity
WHERE backend_type = 'client backend'
GROUP BY state
ORDER BY count(*) DESC;A common result for an application with large per-instance pools is a large count of idle and a small count of active. That ratio is the signal that a pooler can help.
The max_connections limit
max_connections sets a hard upper bound on concurrent client backends. The default is 100. When the limit is reached, new clients receive this error:
FATAL: sorry, too many clients alreadySome slots are also reserved. superuser_reserved_connections (default 3) keeps slots free for superusers, and newer versions add reserved_connections for a designated role. Applications can therefore use fewer slots than max_connections suggests.
It is tempting to fix the error by raising max_connections to 2000 or more. This has three problems:
- Shared memory sizing depends on it, so changing it requires a restart.
- The per-connection overheads listed above increase.
- The server may perform worse under load, not better.
Check the current value and usage:
SHOW max_connections;
SELECT count(*) AS in_use
FROM pg_stat_activity
WHERE backend_type = 'client backend';Why application pools are not enough
Most application frameworks include a connection pool inside each process. This reuses connections within one application instance and removes the setup cost per request. It does not solve the total count problem, because the numbers multiply:
total connections = instances x processes per instance x pool size per processConsider a service with 20 containers, 4 worker processes in each, and a pool size of 10 per process. That is 800 potential connections. If most of them are idle most of the time, the database still carries 800 backends. Autoscaling makes this worse, because new instances raise the total without any change to the database.
Serverless functions and short-lived jobs are a related case. They may open a connection, run one query, and exit. Each call pays the full setup cost, and a burst of calls can exhaust max_connections in seconds.
Active work versus connected clients
The key idea for the rest of this tutorial is the difference between two numbers:
- Connected clients: how many applications hold an open connection.
- Concurrent active queries: how many are running right now.
A database with 16 CPU cores usually gets its best throughput when the number of active queries is a small multiple of the core count. Having 800 connected clients does not mean you need 800 backends. At any instant most of those clients are waiting on the network, on application code, or on user input.
A pooler exploits this gap. It holds the many client connections itself, which is cheap, and lends a small number of real server connections to clients only while they run work. The next chapter describes that idea in general terms.
Measuring the cost yourself
You can observe connection setup cost with pgbench. The -C option opens a new connection for every transaction, which shows the overhead directly.
# Reuse one connection per client (baseline)
pgbench -c 10 -j 2 -T 30 -S appdb
# Reconnect for every transaction
pgbench -c 10 -j 2 -T 30 -S -C appdbCompare the tps and latency average lines. The reconnecting run is typically several times slower for simple read queries, because the connection work dominates the query time. The exact ratio depends on your hardware, network, TLS use, and authentication method.
To see the memory side, look at resident memory per backend:
ps -o pid,rss,cmd -C postgres --sort=-rss | head -15rss includes shared memory that the backend has touched, so it overstates private use. For a more accurate view, use smem or read /proc/<pid>/smaps_rollup and check the Pss value.
Common mistakes
| Mistake | Why it hurts | Better approach |
|---|---|---|
| Raising `max_connections` to absorb spikes | More memory use and contention, and a restart is required | Cap active backends and queue the rest in a pooler |
| Sizing each app pool for peak load | Total connections multiply across instances | Size from a total budget divided across instances |
| Leaving transactions `idle in transaction` | Holds locks and blocks `VACUUM` cleanup | Commit promptly and set `idle_in_transaction_session_timeout` |
| Judging load by connection count | Idle connections look like load but are not | Watch the number of `active` sessions and CPU usage |
Summary of the cost model
- Each connection is an operating system process created by
fork(). - Setup involves networking, optional TLS, authentication, and cache warm-up.
- Memory use grows with the number of backends and with the work each has done.
- CPU scheduling and shared-structure contention worsen as the backend count rises.
max_connectionsis a hard cap, and raising it is rarely the right fix.- Per-application pools reduce setup cost but multiply total connections across instances.
- The useful number is concurrent active queries, which is usually far smaller than connected clients.
Exercise
A service runs 15 containers. Each container starts 4 worker processes, and each worker holds a pool of 8 connections. PostgreSQL has max_connections = 200. Do the app pools fit within the limit if every pool fills? What would you measure to decide whether a pooler would help?
Show answer
The total is 15 x 4 x 8 = 480 connections, which exceeds 200, so the service will hit "sorry, too many clients already" if the pools fill, and it would also exceed the limit once reserved slots are subtracted. To decide whether a pooler would help, group pg_stat_activity by state. If most connections are idle and only a small number are active at any moment, the clients hold many more connections than the database needs for its real work, so a pooler can multiplex them onto far fewer server connections.
Exercise
Why does pgbench -C report lower throughput than a run without it, even though both run the same queries?
Show answer
The -C option opens a new connection for every transaction. Each one pays the cost of the TCP handshake, optional TLS negotiation, process fork, and authentication. For short read queries this setup time is larger than the query time, so throughput falls.