skip to content

connections and pooling

a process per connection, why 5,000 connections hurt, and pgbouncer's three modes.

address
everything.scale.connections_and_pooling
part
part 17, scale and distribution
chapter
chapter 1 of 10
reading time
8 min

every connection to postgres is its own process on the server, forked when you connect and gone when you leave. connecting costs milliseconds, and thousands of them cost memory and contention. a connection pool keeps a few server connections open and lends them out; pgbouncer lends them per session, per transaction or per statement, and the tighter it lends, the more session state you lose.

the picture

you know how an app with 50 pods, each with a pool of 20, wants 1,000 connections, and postgres says too many clients already at 100? that number isn't stingy. it's counting processes.

think of a restaurant where every guest gets a dedicated waiter for the whole visit (a backend process), even while they stare at the menu. a pool is a smaller team of waiters who serve whichever table has its hand up. here's a real postgres 18.6 server with three clients connected:

pg_stat_activity on a native server with clients A, B and C connected (plus the capture tool's own connection). each client backend is a separate operating system process with its own pid; the rest are the server's helpers. autovacuum is switched off for captures, so its launcher isn't listed.

the postmaster listens on the port. every time a client connects, it forks a new process that serves only that client until it disconnects. that's postgres's design since the beginning, and the manual says so plainly.

the page you're reading is the odd one out. its postgres runs inside your browser tab as a single process with exactly one session, so there's nothing to fork and nothing to pool:

sqlempty db
SELECT backend_type, pid = pg_backend_pid() AS is_me FROM pg_stat_activity ORDER BY backend_type;
SHOW max_connections;
output, from postgres 18.6
#1 · SELECT 1
backend_typetextis_mebool
standalone backendt
(1 row)
#2 · SHOW
max_connectionstext
100
(1 row)

what a connection costs

two things: time to open one, and resources while it's open.

opening one means a TCP handshake, a fork, authentication, and a backend warming up its caches. against a throwaway postgres 18.6 on the same machine, with SELECT 1 as the work:

reuse, unix socket0.022 ms
reuse, tcp0.041 ms
connect, unix, trust1.92 ms
connect, tcp, scram3.165 ms
log scale
measured on this mac (m4 pro), node-postgres 8, a throwaway postgres 18.6 with the shop dataset, client and server on the same machine. 2,000 SELECT 1 on one open connection vs 2,000 (unix socket) or 500 (tcp) rounds of connect, SELECT 1, disconnect. mean per round, two runs
mean time per round, on one machine (no network in between). reusing an open connection vs connecting, running the query and disconnecting. with password authentication over TCP, opening a connection costs about 76x the query.

a few milliseconds sounds cheap until it's per request. an app that connects for every web request spends more time saying hello than asking anything.

while it's open, each backend has private memory. a brand-new backend in the capture above had allocated 2.0 MB across 126 memory contexts before running anything (it asked pg_backend_memory_contexts). a busy one grows: every sort or hash in a running query can use up to work_mem on top. and every open connection, busy or idle, is one more process for the operating system to keep and schedule.

that's why max_connections is 100 by default, with 3 slots held back for superusers. you can raise it, but past the point where the CPUs are all busy, more connections don't do more work. they queue for the same cores and locks, just less visibly.

predict the output
your app runs 40 pods, each with a pool of 25 connections, against max_connections = 100. what happens at deploy?
text
40 pods × 25 = 1,000 connections wanted
max_connections = 100

a pool, three ways

a pool sits between the app and postgres (inside each app process, or as a separate proxy like pgbouncer) and keeps a few server connections open. the question is when it takes a connection back. pgbouncer's pool_mode has three answers:

pool_mode =
tickserver conn1server conn2waiting for a connection
1bob BEGINalice SET statement_timeout
2bob UPDATEalice PREPARE qcarol
3bob COMMITcarol SELECTdan
4dan SELECT·
5bob SELECTcarol BEGINdan
6dan SELECTcarol INSERT
7alice EXECUTE qcarol COMMIT

tick 1nothing unusual this tick: statements run wherever the pool put them.

a connection goes back to the pool at every COMMIT. four clients share two connections easily, but session state stays behind on the connection: alice's timeout leaks to whoever comes next, and her prepared statement isn't where her next transaction lands.

tick 1/7
clients finished: 4/4errors: 1ran with someone else's setting: 4
errorinherited session stateidle but held, or waiting
model of a pooler: 4 clients, 2 server connections, one statement per tick. not pgbouncer output
four clients, two server connections. step through each mode. watch alice's setting reach other clients, and her prepared statement go missing, under transaction pooling.
  • session: a client keeps one server connection from connect to disconnect. everything works, but you only multiplex the idle time between clients' sessions.
  • transaction: the connection goes back at COMMIT or ROLLBACK. a handful of server connections can serve hundreds of clients that spend most of their time idle. this is what people usually mean by "put pgbouncer in front".
  • statement: back after every statement, and multi-statement transactions are refused.

what transaction pooling breaks

anything that lives in the session instead of the transaction stays on the server connection when your transaction ends, and the next client to get that connection inherits it. here are two real backends doing exactly what a pooler would forward to them:

c1
·
c2
·
1
SET statement_timeout = '50ms'

alice is on c1. she sets a statement timeout for her session, she thinks.

step 1/9
real output, a postgres 18.6 server · pool-leaks
c1 and c2 are two real server connections. alice's SET outlives her transaction and reaches bob; her next transaction lands on c2, where her prepared statement doesn't exist; and her session advisory lock stays with c1, out of her reach.

pgbouncer's own feature table lists what never works in transaction mode: SET/RESET, LISTEN, WITH HOLD cursors, SQL PREPARE/DEALLOCATE, temp tables that outlive a transaction, LOAD, and session-level advisory locks. the fixes are mostly "say it per transaction":

sqlempty db
BEGIN;
SET LOCAL statement_timeout = '50ms';
SHOW statement_timeout;
COMMIT;
SHOW statement_timeout;
output, from postgres 18.6
#1 · BEGIN
#2 · SET
#3 · SHOW
statement_timeouttext
50ms
(1 row)
#4 · COMMIT
#5 · SHOW
statement_timeouttext
0
(1 row)

SET LOCAL ends with the transaction, and pg_advisory_xact_lock is released at COMMIT (see advisory locks). session mode cleans up between clients with server_reset_query, DISCARD ALL by default, which wipes exactly the state that leaked above:

sqlempty db
SET statement_timeout = '50ms';
PREPARE order_total(int) AS SELECT $1 * 2;
DISCARD ALL;
SHOW statement_timeout;
EXECUTE order_total(21);
output, from postgres 18.6
#1 · SET
#2 · PREPARE
#3 · DISCARD ALL
#4 · SHOW
statement_timeouttext
0
(1 row)
#5 · ERROR 26000
ERROR 26000: prepared statement "order_total" does not exist

sizing it

a pool's job is to keep postgres at the number of connections it can actually run at once, and make everyone else wait in the pool, where waiting is cheap, instead of in the database, where it isn't. so the pool size follows the server's cores and disks, not the number of clients. start small, measure, and raise it while throughput still rises. two things to watch while you do: idle in transaction sessions hold a server connection doing nothing (and, under transaction pooling, block everyone queued behind it), and long transactions hold the xmin horizon back no matter who pools them.

keylines

  • one connection = one postgres process, forked at connect.
  • connecting costs milliseconds; holding thousands costs memory and scheduling.
  • a pool keeps postgres near the work it can do at once and queues the rest.
  • session, transaction, statement: when the pool takes the connection back.
  • under transaction pooling, anything session-scoped leaks or vanishes. use SET LOCAL and xact locks.