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:
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:
SELECT backend_type, pid = pg_backend_pid() AS is_me FROM pg_stat_activity ORDER BY backend_type;
SHOW max_connections;| backend_typetext | is_mebool |
|---|---|
| standalone backend | t |
| max_connectionstext |
|---|
| 100 |
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:
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.
40 pods × 25 = 1,000 connections wanted
max_connections = 100a 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:
| tick | server conn1 | server conn2 | waiting for a connection |
|---|---|---|---|
| 1 | bob BEGIN | alice SET statement_timeout | |
| 2 | bob UPDATE | alice PREPARE q | carol |
| 3 | bob COMMIT | carol SELECT | dan |
| 4 | dan SELECT | · | |
| 5 | bob SELECT | carol BEGIN | dan |
| 6 | dan SELECT | carol INSERT | |
| 7 | alice EXECUTE q | carol 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.
- 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:
alice is on c1. she sets a statement timeout for her session, she thinks.
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":
BEGIN;
SET LOCAL statement_timeout = '50ms';
SHOW statement_timeout;
COMMIT;
SHOW statement_timeout;| statement_timeouttext |
|---|
| 50ms |
| statement_timeouttext |
|---|
| 0 |
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:
SET statement_timeout = '50ms';
PREPARE order_total(int) AS SELECT $1 * 2;
DISCARD ALL;
SHOW statement_timeout;
EXECUTE order_total(21);| statement_timeouttext |
|---|
| 0 |
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.