Deep Engineering
Advanced·Published·55 MIN

Database connection pools: why more is not better

In PostgreSQL every connection is a separate process, and no more processes can run on the CPU at once than the machine has cores; the rest wait for a core, the disk or a lock. On two cores, transactions per second stopped growing at just two clients, never rose above that peak again and by 256 clients had fallen more than threefold, while latency grew faster than the number of clients. A pooler cuts the number of backends; on TPC-B it shortened the tail at the cost of the median and some TPS — and in transaction mode it breaks everything that relies on the session.

Full technical treatment

TL;DR

  • PostgreSQL serves every connection with a process of its own: in our run, 20 connections produced 20 new child processes of the postmaster. No more of them can run on the CPU at once than the machine has cores — two here; the rest wait for a core, the disk or a lock.
  • Once the work is bound by such a resource, past a certain number of connections throughput stops growing: on this machine the limit for reads is the cores, for TPC-B the row locks. On two cores the read-only profile peaks at 88,972 transactions per second with two clients; at 256 clients it is 25,887, and p99 grows from 0.056 to 21.481 ms. In the TPC-B-like profile throughput plateaus as early as four clients (4,661, peaking at 4,724 with 16); at 256 it is 2,814 with a p99 of 540 ms, and nearly every backend is waiting for a lock. The read peak at two clients gives no rule for pool size: a separate measurement shows that the gap between one and two clients is almost entirely the cost of handing a lone client's requests between cores.
  • Little's law checks out on our own numbers: for TPC-B, λ·W/L is between 0.974 and 0.997. Where it "fails" (down to 0.703 for read-only at 256 clients), clients are waiting inside the load generator itself, and the latency measurement does not see that wait.
  • A new connection costs 1.9 ms over TCP, 4.5 ms with TLS and 8.4 ms with TLS and SCRAM — against 0.06 ms for the query itself on an open connection.
  • pgbouncer in transaction mode: 256 clients on 16 connections instead of 256 backends. On TPC-B, p99 fell from 560 to 142 ms, but the median rose from 52 to 99 ms, and TPS was 2,548 against 2,795; on plain reads the pooler, sharing the same two cores with the database, took almost half a core and TPS went down. The extra hop through the pooler costs a single client 42 µs per transaction.
  • Transaction mode breaks session state: client A's SET leaked to B, A's temporary table vanished for A and turned up for B, both clients got the same advisory lock, a NOTIFY reached nobody, and a statement from SQL PREPARE was not found. pgbouncer 1.22 tracks protocol-level prepared statements only if max_prepared_statements is above zero, and by default it is zero.

Why should I care?

The number of connections to a database usually grows on its own: every service instance has its own pool, the pool size was set "with headroom", the number of instances grew — and so did the number of connections. Eight pods with fifty connections each means four hundred PostgreSQL processes on a machine that may have eight cores. None of these settings looks like a mistake, and nobody added them up.

Intuition says more connections mean more parallel work. For PostgreSQL that holds as long as there are free resources for the work: cores, the disk and locks do the work, not connections. Once the resource is busy, surplus connections turn into a queue — for the CPU, for row locks, for the disk — and on this machine that happened at just a few clients. The queue does not show up as an error. It shows up as a longer latency tail, or, with luck, as FATAL: remaining connection slots are reserved in the middle of a deploy.

Everything below runs on one PostgreSQL 16.15 cluster on a two-core machine, with pgbench and pgbouncer 1.22.0 on the same machine. First, what a connection means to PostgreSQL and what it costs to open one; then the main measurement; then the pooler and what you pay for it.

The model: a connection is a process, and resources do the work

language contractPostgreSQL 16, How Connections Are Established (doc/src/sgml/arch-dev.sgml, REL_16_15)

The PostgreSQL 16 documentation states the model in one sentence: PostgreSQL implements a “process per user” client/server model. In this model, every client process connects to exactly one backend process. A supervisor process, the postmaster, listens on the port and for every connection request spawns a new backend process.

Three consequences follow, and each is measured below.

  1. Opening a connection means spawning a process, authenticating and possibly doing a TLS handshake. That is expensive next to a simple query.
  2. The number of connections is capped by max_connections, and the cap is hard: a surplus connection does not wait, it is refused.
  3. Processes do the work, not connections. A process with a query is either running on a core or waiting for a core, a lock or the disk. When there are more processes ready to compute than cores, the rest wait for a core, and throughput is capped by the cores; when they wait for a lock or the disk, it is capped by those. Load, not arithmetic, shows which resource becomes the limit and at how many connections.

The third is an ordinary queue, and there is an exact relation for it — Little's law: the mean number of requests in the system equals the arrival rate times the mean time spent in it, L = λ·W. If 256 clients each keep one transaction in flight (L = 256) and the database completes 2,814 transactions per second (λ, the TPC-B-like profile below), then each transaction spends on average W = L/λ ≈ 91 ms in the system — however little of that it spends actually executing; the measured mean latency there is 88.9 ms. More clients at the same λ only mean a larger W.

First: a connection is a process

measured observationbench/conn-pool/backend.py, PostgreSQL 16.15, Linux 6.18, 2 cores. No timing at all: the postmaster's children are counted through /proc and compared with the PIDs pg_backend_pid() returns.

We open twenty connections through psycopg and list the postmaster's child processes before and after:

1. ONE BACKEND PROCESS PER CONNECTION
-------------------------------------
postmaster children before: 5
  autovacuum launcher
  background writer
  checkpointer
  logical replication launcher
  walwriter
client connections opened: 20
postmaster children after: 25 (+20)
distinct pg_backend_pid(): 20, all of them new children: True

Twenty connections, twenty new processes, and each connection's pg_backend_pid() points at one of them.

The cap on those processes is max_connections. The documentation describes it as follows: it Determines the maximum number of concurrent connections to the database server, and it can only be changed by restarting the server. Some slots are reserved: superuser_reserved_connections (three by default) for superusers, and reserved_connections, new in 16 (zero by default), for roles with pg_use_reserved_connections. With max_connections = 300 an ordinary role opens connections until it is refused:

2. MAX_CONNECTIONS IS A HARD CAP
--------------------------------
max_connections = 300, superuser_reserved_connections = 3, reserved_connections = 0
connections opened by an ordinary role: 297
connection 298: remaining connection slots are reserved for roles with the SUPERUSER attribute
a superuser connection on top of them: accepted

297 = 300 − 3. Connection 298 does not wait in a queue — it gets a FATAL straight away. In a service this shows up as a connection error just when there are more connections than usual — for example, during a deploy, if old and new instances hold their pools at the same time for a while.

How much memory a backend takes

Going by a backend's RSS, it is easy to conclude that every connection takes tens of megabytes. But RSS also counts shared memory — the shared_buffers pages the process has touched. The honest measure of what one connection adds is its private pages (Private_Clean + Private_Dirty in /proc/<pid>/smaps_rollup):

Median over twenty backends, bench/conn-pool/backend.py, block 3; shared_buffers = 768MB, huge_pages = off.

whatRSSprivate memory
a backend after SELECT 118.0 MiB1.1 MiB
after 1000 index lookups and a full pass over pgbench_accounts153.0 MiB1.5 MiB
200 idle backends together3619 MiB228 MiB

RSS grew eight and a half times because the process read the table through the shared buffer cache, while private memory went only from 1.1 to 1.5 MiB. RSS summed over two hundred backends is 3,619 MiB, about 3.5 GiB — more than all of shared_buffers: the same shared pages are counted two hundred times. This measurement uses simple queries. Sorts and hash operations take private memory on top of this: according to the documentation, work_mem (4 MB here) sets the base limit for each such operation, and a complex query may run several of them at once. The conclusion is not "connections are free" but "memory is not their main cost": the main cost comes next.

Second: what it costs to open a connection

measured observationbench/conn-pool/connect_cost.py: pgbench -C -S, one client, three interleaved 10-second runs, median and range. PostgreSQL 16.15 and pgbench 16 on the same machine, 127.0.0.1.

pgbench -C opens a new connection for every transaction and prints the average time spent connecting; the documentation says exactly that: This is useful to measure the connection overhead. The transaction is one primary-key read.

bench/conn-pool/connect_cost.py, block 2, median of three runs.

how we connectedconnect, mstransactions per second with -Con one open connection
Unix socket, trust1.82841018905
TCP, trust, no TLS1.93639217656
TCP, trust, TLS 1.34.47119614611
TCP, SCRAM, TLS 1.38.36311114515
through pgbouncer, no TLS0.12638959593

A TCP connect takes almost 2 ms, while the query itself on an open connection takes about 0.06 ms (17,656 transactions per second for one client). A service that opens a connection per request spends more than thirty times as long connecting as working. TLS more than doubles the price of a connect, and SCRAM authentication nearly doubles it again.

Connecting to pgbouncer is fifteen times cheaper than connecting to PostgreSQL over TCP: it does not spawn a process, and its connection to the database is already open. The price of this shows in the last column: over an open connection through the pooler, one client completes almost half as many transactions. More on that in the pgbouncer section.

language contractPostgreSQL 16, libpq, sslmode (doc/src/sgml/libpq.sgml, REL_16_15)

One more detail can make connecting more expensive than expected. By default libpq uses sslmode=prefer: first try an SSL connection; if that fails, try a non-SSL connection. If the server has ssl = on, a client over TCP encrypts the connection even though nobody asked it to:

1. WHAT THE DEFAULT SSLMODE GIVES OVER TCP
------------------------------------------
psql (libpq 16) to 127.0.0.1, the server has ssl = on
sslmode (not set)  ssl=true  TLSv1.3 TLS_AES_256_GCM_SHA384
sslmode disable    ssl=false -
sslmode require    ssl=true  TLSv1.3 TLS_AES_256_GCM_SHA384

That is why every other measurement in this article sets sslmode=disable explicitly: otherwise encryption would have crept into them unnoticed.

Third: more clients, no more transactions

measured observationbench/conn-pool/sweep.py: PostgreSQL 16.15, two cores, pgbench 16 on the same machine, TCP 127.0.0.1 without TLS, scale 30 (about 450 MB) in shared_buffers 768MB. Each point is three 15-second runs, the order of points alternates between repeats; runs during which other processes took more than 5% of the machine were discarded and repeated.

The main measurement. One database, one data set, and only the number of pgbench clients changes: 1, 2, 4 and so on up to 256. Each client holds its own connection for the whole run — which is how an ordinary application pool works too. There are two profiles:

  • read-only (pgbench -S): one primary-key read per transaction. The data is entirely in memory and there is nothing to wait for — this profile is bound by the CPU;
  • TPC-B-like (the default pgbench profile): three UPDATEs, a SELECT and an INSERT in one transaction, a commit with fsync. Here there is something to wait for — the disk and row locks: pgbench_branches has as many rows as the scale, that is 30, and every transaction updates one of them.

Latency is taken not from what pgbench prints at the end but from its journal, which records the time of every transaction (a 10% sample for read-only). Why that matters is explained in the section on Little's law below.

1. SELECT-ONLY: THROUGHPUT AND LATENCY BY CLIENTS
-------------------------------------------------
latency from --log (sampling 0.1), ms; median of 3 runs; tps: median (min-max)
clients                    tps     mean      p50      p95      p99 failed
      1    17821 (17631-18031)    0.056    0.054    0.072    0.104      0
      2    88972 (88413-92610)    0.022    0.020    0.031    0.056      0
      4    85012 (84389-85397)    0.045    0.041    0.068    0.105      0
      8    64123 (62086-72190)    0.108    0.102    0.171    0.244      0
     16    66264 (66023-70030)    0.207    0.195    0.321    0.456      0
     32    48877 (43823-51582)    0.562    0.565    0.904    1.316      0
     64    45894 (43903-46206)    1.120    1.243    1.855    2.565      0
    128    40876 (40035-42380)    2.317    2.524    4.339    5.797      0
    256    25887 (25003-38649)    6.783    5.769   15.008   21.481      0

The peak is 88,972 transactions per second with two clients; with four it is 85,012, 4% less, and then the curve goes down: 256 clients do 25,887 transactions per second — 71% below the peak. Over the same range median latency grew from 0.020 to 5.769 ms and p99 from 0.056 to 21.481 ms. The database did no more work; the queue grew.

Why one client is five times slower than two

Doubling the clients gave almost five times the throughput — from 17,821 to 88,972 transactions per second — and a transaction takes 0.056 ms for one client against 0.022 ms for two. A second core can account for at most a doubling; the rest calls for a separate measurement, not a guess.

measured observationbench/conn-pool/single_client.py: the same pgbench -S, five interleaved 10-second runs per condition; context switches from /proc/stat for the whole machine and from getrusage for pgbench itself; pinning to cores with taskset, applied to the postmaster before pgbench connects so the backend it forks inherits the mask. The record was taken on a machine with a 2.10 GHz Xeon, so the absolute numbers differ from the main measurement; only rows of the same record are compared.

First, the points for one, two and four clients are repeated:

1. ONE, TWO AND FOUR CLIENTS AGAIN
----------------------------------
                               tps median (min-max)  mean, us    CPU  cs/xact   pgbench
                                                                      machine  vcs/xact
1 client(s)                  17068 (15800-17474)      58.1    49%     4.00      1.00
2 client(s)                  73834 (70341-79251)      26.8   100%     2.00      1.00
4 client(s)                  71089 (67697-72727)      53.4   100%     1.51      0.44

The picture is the same: 17,068 against 73,834. Then the single client gets one condition changed at a time:

2. ONE CLIENT, ONE CONDITION CHANGED AT A TIME
----------------------------------------------
                               tps median (min-max)  mean, us    CPU  cs/xact   pgbench
                                                                      machine  vcs/xact
1 client, plain              16681 (15817-16861)      59.7    49%     4.00      1.00
1 client, idle-spin          14962 (13805-19034)      66.1   100%     4.00      1.00
1 client, same-core          37934 (36355-39309)      26.1    51%     2.00      1.00
1 client, split-cores        16420 (15949-17527)      60.5    49%     4.01      1.00

With pgbench and the backend pinned to one core, one client completes 37,934 transactions per second — 2.3 times as many as without pinning — and the context switches per transaction drop from four to two. Pinning them explicitly to different cores gives the same result as no pinning. Two busy loops under SCHED_IDLE, which keep the cores from going idle, did not make it faster: there were still four switches, and the spread grew.

3. TWO CLIENTS ON ONE CORE
--------------------------
                               tps median (min-max)  mean, us    CPU  cs/xact   pgbench
                                                                      machine  vcs/xact
2 clients, plain             73834 (70341-79251)      26.8   100%     2.00      1.00
2 clients, same-core         35551 (34572-37340)      55.8    50%     2.01      1.00

Two clients on one core complete 35,551 transactions per second — almost as many as one client on one core (37,934). Two clients without pinning do 73,834, that is, two cores at the same rate each, again with two switches per transaction, as with pinning.

What follows from this and what does not. It follows that almost the whole gap between one and two clients is not the database's work but the fact that one client's request and reply are handed between cores: on one core the same transaction takes 26 µs, across two cores 60 µs, and a lone client has nothing to overlap those two extra switches per transaction with. This measurement cannot tell what exactly makes that handover expensive — waking an idle virtual CPU, caches or the scheduler: there are no tools like perf on the machine, and the busy-loop experiment gave no answer. Nor does it follow that "the optimal pool equals the number of cores". Two clients here mean two cores, each of which, judging by the two switches per transaction, works without such a handover. That gives no rule for pool size, and four clients did almost as well.

Where the time goes

measured observationbench/conn-pool/sweep.py, blocks 2 and 5: core load and CPU time per transaction from /proc/stat and the measurement's cgroup; the queue of processes ready to run is procs_running from /proc/stat; the state of the backends is pg_stat_activity, sampled every 0.2 s from a separate connection.

The answer is in the neighbouring block of the same record:

bench/conn-pool/sweep.py, block 2, median of three runs.

read-only, clientscore loadCPU per transaction, µsof it pgbench, µsready to run
149%54.916.81.1
2100%22.54.62.3
16100%30.24.36.4
25699%76.48.016.2

From two clients on, the cores are fully busy, and everything beyond that waits for the CPU: with 256 clients, on average 16.2 processes are ready to run on two cores. Meanwhile the same transaction costs more than three times as much CPU time — 76.4 µs against 22.5 — and almost all of the increase goes not to the load generator but to everything else: the database and the OS kernel. The measurement does not break down where exactly the extra goes; it shows that surplus connections are not free even for the CPU.

TPC-B shows a different mechanism with the same outcome:

4. TPCB-LIKE: THROUGHPUT AND LATENCY BY CLIENTS
-----------------------------------------------
latency from --log (sampling 1), ms; median of 3 runs; tps: median (min-max)
clients                    tps     mean      p50      p95      p99 failed
      1       1603 (1587-1709)    0.622    0.587    0.811    1.074      0
      2       2598 (2591-3438)    0.765    0.750    1.029    1.415      0
      4       4661 (4142-4692)    0.851    0.782    1.418    2.071      0
      8       4521 (4490-4868)    1.749    1.660    2.749    3.592      0
     16       4724 (4677-5037)    3.326    3.126    5.726    7.913      0
     32       4613 (4424-4891)    6.777    6.314   12.064   16.847      0
     64       4134 (4124-4256)   15.105   12.997   31.445   48.167      0
    128       3576 (3413-3646)   34.904   24.977   94.651  168.628      0
    256       2814 (2814-2893)   88.882   50.557  284.421  540.199      0

Throughput reaches a plateau by four clients (4,661) and holds it up to 32; the formal peak is 4,724 at 16 clients, but the differences between 4, 16 and 32 are smaller than the spread between runs. Then it declines: 2,814 at 256. And p99 at 256 clients is 540 ms, 68 times the value at 16.

Here the wait is not for the CPU. Of 198.1 active backends at 256 clients, 193.7 are waiting for a lock — Lock or LWLock; the measurement does not separate these two wait types. Every transaction updates one of the 30 rows of pgbench_branches, and 256 transactions on 30 rows form a queue in which each extra transaction takes one more place.

bench/conn-pool/sweep.py, block 5, median of three runs.

TPC-B, clientscore loadactive backendsof them waiting on Lock/LWLockready to run
478%1.70.72.9
1691%5.64.16.5
6493%25.523.210.8
25694%198.1193.713.4

Different mechanisms — a queue for cores and a queue for rows — and one conclusion: once the resource the work depends on is busy, an extra connection adds no throughput, only waiting.

Little's law on our own numbers

implementation detail · pgbench 16 (REL_16_15)src/bin/pgbench/pgbench.c, printResults

Before checking Little's law, you have to know what pgbench prints. Unless -P, --rate or --latency-limit is given, the "latency average" in its output is not measured but computed — the branch commented no measurement, show average latency computed from run time prints total_duration * nclients / total_cnt, that is, L/λ. Checking L = λ·W with it means checking an identity. So the measurement turns -P on, and W is the mean over the journal.

measured observationbench/conn-pool/sweep.py, blocks 3 and 6: L is the number of clients, λ the run's TPS, W the mean latency from the same run's --log journal; the ratio is computed per run, and the table shows the median of three.

bench/conn-pool/sweep.py, blocks 3 and 6.

clientsread-only: λ·W/LTPC-B: λ·W/L
10.9960.997
160.8800.982
640.8020.974
1280.7410.977
2560.7030.978

For TPC-B the law holds at all nine points: the ratio is between 0.974 and 0.997. 256 clients, 2,814 transactions per second, a measured mean latency of 88.9 ms: 2814 × 0.0889 ≈ 250 transactions in flight out of 256. Every extra connection really does add 1/λ to the time of every transaction — that is the same law read backwards.

For read-only the ratio drops to 0.703 — and that is not a violation of the law but a finding. The law holds for any system if all of the time is counted; a ratio below one means the client spent almost a third of its time outside the measured interval. pgbench starts timing a transaction only when its thread gets round to it, and with 256 clients its two threads share the two cores with 256 backends and cannot keep up: a client ready for its next transaction waits for its turn inside the generator itself. The load generator runs on the same two cores; that is a limitation of the measurement, and Little's law is what exposes it. In TPC-B a transaction is long in itself — it waits for the disk and for locks — and against that, this share is negligible: 0.978 at the same 256 clients.

The practical consequence matters more than any table: if a client application measures the latency of its database queries and the wait for a connection in its own pool is not part of that measurement, then λ·W/L is below one — and that is the first sign that the time is going somewhere other than the database.

Fourth: a pooler in front of the database

A pooler keeps a small number of connections to the database and hands them out to clients. pgbouncer has three modes, and they differ in when a server connection goes back to the pool.

language contractPgBouncer 1.22.0, doc/config.md, the pool_mode setting
  • session — Server is released back to pool after client disconnects. This is the default. Several clients connected at the same time cannot share one server connection in it: each needs its own for its whole session. The gain is in the cost of connecting and in reusing server connections when clients connect briefly; with short transactions, the main saving in backends comes from transaction.
  • transaction — Server is released back to pool after transaction finishes. 256 clients can share 16 connections as long as they do not keep transactions open.
  • statement — the same after every query; multi-statement transactions are not allowed.

Both of the last two modes reduce the number of backends, but statement cannot run a multi-statement transaction, and TPC-B has seven statements. Everything below is about transaction.

language contractPgBouncer Features, SQL feature map (revision ccb120f, in force for 1.22.0); PgBouncer 1.22.0 doc/config.md (max_prepared_statements); PostgreSQL 16: SET LOCAL, advisory locks. The “what to use instead” column is a conclusion drawn from these documents, not their text.

Which session state survives transaction mode is clear before any measurement, from pgbouncer's compatibility table and the PostgreSQL documentation:

what lives in the sessionsessiontransactionwhat to use instead in transaction mode
SET / RESETworksNeverSET LOCAL inside the transaction; the connection parameters pgbouncer tracks itself: client_encoding, DateStyle, IntervalStyle, TimeZone, standard_conforming_strings, application_name
a temporary table with PRESERVE ROWS or DELETE ROWSworksNeverON COMMIT DROP, and all work with it in one transaction
a session-level advisory lockworksNeverpg_advisory_xact_lock — released at the end of the transaction
LISTENworksNevera separate direct connection that bypasses the pooler; NOTIFY works through the pooler
a WITH HOLD cursorworksNevera WITHOUT HOLD cursor inside the transaction
SQL-level PREPARE / DEALLOCATEworksNeverprotocol-level preparation by the driver
protocol-level prepared statementsworkswith max_prepared_statements > 0 (since 1.21; 0 by default in 1.22)turn the setting on; DEALLOCATE ALL and DISCARD ALL are supported since 1.22
LOADworksNever—

A preliminary audit of an application before the switch means searching the code, and the SQL the ORM generates, for everything in the "Never" rows, and running the tests through pgbouncer in transaction mode with a small pool. On a pool of two connections, the breakages from the "Fifth" section reproduced in every one of our runs.

The price of the extra hop

measured observationbench/conn-pool/bouncer.py, block 1: one client, pgbench -S, three interleaved 15-second runs; direct and through pgbouncer, both over TCP 127.0.0.1 without TLS.
1. THE EXTRA HOP: ONE CLIENT, SELECT-ONLY
-----------------------------------------
path                          tps     mean      p50      p99
direct        17197 (17067-17616)    0.058    0.054    0.109
pgbouncer       9997 (9293-10044)    0.100    0.095    0.199
pgbouncer adds 42 us to the mean transaction (x1.73)

The pooler is one more process on the request's path: accept, find a server connection, forward, receive the reply, forward it back. Here that adds 42 µs to a transaction that takes 58 µs on its own. For a query of a few milliseconds that is little; for one of tens of microseconds it is noticeable. And the cost is paid on every statement: a transaction of seven statements passes through the pooler seven times.

256 clients on a small pool

measured observationbench/conn-pool/bouncer.py, blocks 2 and 3: 256 pgbench clients, direct and through pgbouncer 1.22.0 (transaction, default_pool_size 4–32); three interleaved 15-second runs. pgbouncer is single-threaded and runs on the same two cores. The state of the server connections comes from pg_stat_activity, sampled every 0.2 s.

The same 256 clients as in the main measurement — direct, and through a pool of 4, 8, 16 and 32 connections. Let us start with the profile where the pool helps.

bench/conn-pool/bouncer.py, block 3, median of three runs.

TPC-B-like, 256 clientsbackendsTPSp50, msp95, msp99, mswaiting for the client mid-transaction
direct256279551.573292.899559.85744.1
pool 441977127.735157.710173.2783.0
pool 882221113.469138.436154.9726.2
pool 1616254899.090123.465142.00812.3
pool 3232255397.821118.000137.93223.1

With a pool of 16 connections p99 dropped almost fourfold — from 560 to 142 ms, p95 from 293 to 123 ms — and there are sixteen times fewer backends. The price was throughput (2,548 against 2,795, minus 9%) and the median: 99 ms against 52.

Why the tail is shorter. With direct connections, nearly all 256 backends queue for locks (in the main measurement 193.7 of 198.1 active backends wait on Lock or LWLock), and they wait very unevenly: half of the transactions finish within 52 ms, while one in a hundred waits more than half a second. Through the pool the database holds at most 16 transactions at a time, the rest wait in pgbouncer, and the distribution becomes narrow: p99 is less than one and a half times the median. Transactions wait longer on average, but predictably.

Why does the pool of 4 manage so few — 1,977 transactions per second, when four direct clients in the main measurement did 4,661? The answer is in the last column: of four server connections, 3.0 on average are in the idle in transaction state. In transaction mode a connection is taken for the whole transaction, and TPC-B is seven statements; between them the connection waits for the client to send the next one through pgbouncer. With a pool of 16, 12.3 connections out of 16 wait like that. A pool has to cover not only the work in the database but also every round trip to the client inside a transaction — which is why long, chatty transactions need a bigger pool than the core count suggests.

The read-only profile on the same machine tells a different story:

bench/conn-pool/bouncer.py, block 2, median of three runs.

read-only, 256 clientsbackendsTPSp50, msp99, mscores used by pgbouncer
direct256319325.02119.071—
pool 44254629.28216.9110.44
pool 88256219.76516.4250.43
pool 16162364810.49316.5860.40
pool 32322267511.02918.0000.38

Here a pool of 4 or 8 lost a fifth of the throughput (a pool of 32 lost 29%), the median almost doubled, and p99 moved little. There are two reasons, and both are in the record. First, pgbouncer is single-threaded and in this measurement sits on the same two cores as the database and pgbench: it took 0.44 of a core, almost a quarter of the machine. And each transaction's work is tiny, so forwarding it through the pooler costs about as much as the work itself. Second, the 256 direct clients look better than they really are. Their λ·W/L is 0.697: almost a third of the time a client is waiting not in the database but in pgbench itself, and that wait does not show up in the latency. Through the pooler λ·W/L is between 0.993 and 0.997: the wait moved into pgbouncer and is honestly counted in the latency.

The conclusion for this machine is narrow: the pooler does not buy extra transactions per second — it gives the database no extra cores — and on very short queries, when it shares the same cores, it even takes some away. Its job is to keep the number of backends and the latency tail under control when there are many clients and their transactions compete. In a real system pgbouncer usually runs on separate cores or a separate machine, and the first of the two reasons does not apply there.

Fifth: what transaction mode breaks

language contractPgBouncer 1.22.0, doc/config.md (server_reset_query); PgBouncer Features, revision ccb120f

In transaction mode a client may land on a different server connection between transactions — that is, on a different backend with a different session state. The pgbouncer 1.22 documentation says so in the description of server_reset_query: in this mode clients must not use any session-based features, since each transaction ends up in a different connection and thus gets a different session state. The compatibility table on the project's site marks "Never" for SET/RESET, LISTEN, WITH HOLD cursors, PREPARE/DEALLOCATE, temporary tables with PRESERVE/DELETE ROWS, LOAD and session-level advisory locks.

The documentation says "do not use"; it does not show what happens if you do. The measurement reproduces five cases. A pool of two server connections, clients A and B in autocommit, every step a transaction of its own, and every step prints which backend served it (server#1, server#2 are labels, not PIDs).

measured observationbench/conn-pool/session_state.py, PostgreSQL 16.15, pgbouncer 1.22.0, pool_mode = transaction, default_pool_size = 2, psycopg 3.3.9. The order of steps is fixed, so the outcome repeats from run to run.

The first case is a session setting — the kind that per-tenant row policies, for example, rely on:

1. SET: A's SETTING LEAKS TO B AND IS GONE FOR A
------------------------------------------------
direct to PostgreSQL:
  A  [server#1]  SET app.tenant = 'acme'                              -> ok
  A  [server#1]  SELECT current_setting('app.tenant', true)           -> 'acme'
  B  [server#2]  SELECT current_setting('app.tenant', true)           -> NULL
  B  [server#2]  SELECT 'B holds a transaction open'                  -> 'B holds a transaction open'
  A  [server#1]  SELECT current_setting('app.tenant', true)           -> 'acme'
through pgbouncer (transaction mode):
  A  [server#1]  SET app.tenant = 'acme'                              -> ok
  A  [server#1]  SELECT current_setting('app.tenant', true)           -> 'acme'
  B  [server#1]  SELECT current_setting('app.tenant', true)           -> 'acme'
  B  [server#1]  SELECT 'B holds a transaction open'                  -> 'B holds a transaction open'
  A  [server#2]  SELECT current_setting('app.tenant', true)           -> NULL

With direct connections, A and B each have their own backend, and A's setting stays with A. Through the pool, B's next step landed on the same server#1 and read someone else's 'acme', while A, with B holding a transaction open, landed on server#2 and did not find its own setting. Neither of them got an error — both got a plausible answer.

A temporary table behaves the same way: A created cart on server#1, A's next INSERT landed on server#2 and got relation "cart" does not exist, while B on server#1 calmly read someone else's table (count(*) returned 0).

A session-level advisory lock is the worst case, because mutual exclusion breaks:

3. SESSION ADVISORY LOCK: A AND B BOTH GET IT
---------------------------------------------
direct to PostgreSQL:
  A  [server#1]  SELECT pg_try_advisory_lock(42)                      -> True
  B  [server#2]  SELECT pg_try_advisory_lock(42)                      -> False
  C  [direct]   SELECT pg_try_advisory_lock(42)                      -> False
  B  [server#2]  SELECT 'B holds a transaction open'                  -> 'B holds a transaction open'
  A  [server#1]  SELECT pg_advisory_unlock(42)                        -> True
through pgbouncer (transaction mode):
  A  [server#1]  SELECT pg_try_advisory_lock(42)                      -> True
  B  [server#1]  SELECT pg_try_advisory_lock(42)                      -> True
  C  [direct]   SELECT pg_try_advisory_lock(42)                      -> False
  B  [server#1]  SELECT 'B holds a transaction open'                  -> 'B holds a transaction open'
  A  [server#2]  SELECT pg_advisory_unlock(42)                        -> False
                 WARNING: you don't own a lock of type ExclusiveLock

pg_try_advisory_lock(42) returned True to both A and B. That is not a PostgreSQL bug but part of its contract: If a session already holds a given advisory lock, additional requests by it will always succeed — and through the pool A and B share the same session. A third client connected directly sees the lock as taken, so it does exist and is held by server#1. When A later tries to release it, A lands on server#2 and gets False with a warning: the lock stays on a backend that may be serving anyone at any moment.

With LISTEN it is not state that is lost but an event:

4. LISTEN: THE SUBSCRIPTION STAYS ON A SERVER CONNECTION
--------------------------------------------------------
direct to PostgreSQL:
  A  [server#1]  LISTEN jobs                                          -> ok
  C  [direct]   SELECT pg_notify('jobs', 'job-1')                    -> sent
  B  [server#2]  SELECT 'B holds a transaction open'                  -> 'B holds a transaction open'
  A  [server#1]  SELECT 'A asks for anything'                         -> 'A asks for anything'
  B  [server#2]  SELECT 'B asks for anything'                         -> 'B asks for anything'
  notifications received by A: ['job-1']
  notifications received by B: none
through pgbouncer (transaction mode):
  A  [server#1]  LISTEN jobs                                          -> ok
  C  [direct]   SELECT pg_notify('jobs', 'job-1')                    -> sent
  B  [server#1]  SELECT 'B holds a transaction open'                  -> 'B holds a transaction open'
  A  [server#2]  SELECT 'A asks for anything'                         -> 'A asks for anything'
  B  [server#1]  SELECT 'B asks for anything'                         -> 'B asks for anything'
  notifications received by A: none
  notifications received by B: none
  pgbouncer log: bench/bench@127.0.0.1:55532 got packet 'A' from server when not linked

A's subscription stayed on server#1. The notification arrived there while the connection was sitting in the pool, assigned to nobody, and pgbouncer dropped it — the only trace is one line in its log. Nobody received it, not even B, who later worked on that same server#1.

The fifth case is SQL PREPARE: the statement was prepared on server#1, EXECUTE went to server#2 and got prepared statement "get_one" does not exist.

Prepared statements

language contractPgBouncer 1.22.0, doc/config.md (max_prepared_statements) and NEWS.md (1.21.0, 1.22.0)

Prepared statements come in two kinds, and pgbouncer treats them differently. It does not track the SQL level — PREPARE/EXECUTE — at all: so PREPARE, EXECUTE and DEALLOCATE are forwarded straight to Postgres, and case 5 above shows how that ends. The protocol level — when the driver sends Parse with a statement name and afterwards only Bind and Execute — pgbouncer has supported since 1.21: with a non-zero max_prepared_statements it tracks protocol-level named prepared statements related commands sent by the client in transaction and statement pooling mode and prepares the statement again, if needed, on whichever server connection the client landed on. In 1.22 the setting defaults to zero — that is, off.

measured observationbench/conn-pool/session_state.py, blocks 6 and 7: psycopg with prepare=True and pgbench -M prepared through pgbouncer 1.22.0, a pool of two connections.

A driver that prepares statements at the protocol level — psycopg with prepare=True:

6. PROTOCOL-LEVEL PREPARED STATEMENT: PSYCOPG PREPARE=TRUE
----------------------------------------------------------
the driver prepares the statement once (Parse with a name) and then only
sends Bind/Execute with that name; psycopg names it _pg3_0
direct to PostgreSQL:
  A  [server#1]  SELECT abalance FROM pgbench_accounts WHERE aid = 1  -> 0
  B  [server#2]  SELECT 'B holds a transaction open'                  -> 'B holds a transaction open'
  A  [server#1]  SELECT abalance FROM pgbench_accounts WHERE aid = 1  -> 0
through pgbouncer, max_prepared_statements = 0:
  A  [server#1]  SELECT abalance FROM pgbench_accounts WHERE aid = 1  -> 0
  B  [server#1]  SELECT 'B holds a transaction open'                  -> 'B holds a transaction open'
  A  [server#2]  SELECT abalance FROM pgbench_accounts WHERE aid = 1  -> ERROR: prepared statement "_pg3_0" does not exist
through pgbouncer, max_prepared_statements = 100:
  A  [server#1]  SELECT abalance FROM pgbench_accounts WHERE aid = 1  -> 0
  B  [server#1]  SELECT 'B holds a transaction open'                  -> 'B holds a transaction open'
  A  [server#2]  SELECT abalance FROM pgbench_accounts WHERE aid = 1  -> 0

With zero, the statement _pg3_0 prepared on server#1 was not found on server#2. With 100, the same step on server#2 returned its result: pgbouncer prepared the statement there itself, under its own internal name.

pgbench -M prepared shows the same problem from the other side. Every client prepares the same text under the same name, P_0, so through the pool some run into "already exists" (the name is taken by another client on that backend) and others into "does not exist":

7. PGBENCH -M PREPARED THROUGH THE POOL
---------------------------------------
pgbench -S -c 8 -j 2 -T 10 through pgbouncer, pool size 2; every client
prepares the same statement text under the same name, P_0
max_prepared_statements = 0    -M simple    clients aborted 0 of 8, failed transactions 0, transactions 228077, error lines 0
max_prepared_statements = 0    -M prepared  clients aborted 8 of 8, failed transactions 0, transactions 32, error lines 15
    server error: prepared statement "P_0" already exists
    server error: prepared statement "P_0" does not exist
max_prepared_statements = 100  -M prepared  clients aborted 0 of 8, failed transactions 0, transactions 232560, error lines 0

In this record, with zero, all eight clients aborted after 32 transactions between them; the outcome depends on which backend each client lands on and whether somebody had prepared P_0 there before, so it differs from run to run. With 100 there are no errors, and there are as many transactions as with the simple protocol.

Pool size: one budget per database, checked under load

language contractPostgreSQL wiki, Number Of Database Connections (last edited 14 March 2014); HikariCP wiki, About Pool Sizing

The formula that is often quoted comes from the PostgreSQL wiki. The section "How to Find the Optimal Database Connection Pool Size" says that for optimal throughput the number of active connections should be somewhere near ((core_count * 2) + effective_spindle_count); cores are counted without hyperthreading, and spindles are zero if the working set is fully cached. HikariCP quotes the same formula and credits the source: The formula below is provided by the PostgreSQL project as a starting point. It is a heuristic, and not a new one: the wiki page that records it was last edited on 14 March 2014, and the same page says: There hasn't been any analysis so far regarding how well the formula works with SSDs.

For the machine in this measurement the formula gives 2 × 2 + 0 = 4. The measurement agrees with it halfway, and that is instructive. Reads, with nothing to wait for, hit the cores almost at once: the peak is at two clients, four are 4% below it, and the gap between one and two clients, as shown above, is the cost of handing over between cores, not an argument for "the pool equals the number of cores". TPC-B reached its plateau at four direct clients, right at the formula's number; but through pgbouncer a pool of 4 did worst of all, and only a pool of 16 came close to the direct result: in transaction mode a server connection stays occupied even while the transaction waits for the client between statements. The formula is right in spirit — there should be as many active connections as the database's resources can serve — but the number itself depends on how much of a transaction's time goes into work and how much into waiting, in the database and on the way to the client. So the formula is a starting point, and values around it are checked under load.

The number of cores is therefore an input, not the answer. Pool size also depends on the kind of queries, how much of a transaction is spent waiting, how long a connection is held (in transaction mode, the whole transaction with its round trips to the client), the number of service instances, memory and max_connections. It is found with a load test around the starting point, watching TPS, p50, p99 and the time spent waiting in the pool's queue. The test does not help if its load is unlike the real one: a different mix of queries gives a different limit.

Three practical rules follow.

  1. There is one budget per database. The sum of the pools of all instances of all services, not the size of one pool, has to fit what the database can serve. Eight pods of 50 make 400 processes; with autoscaling, more. If the sum does not fit, that is an argument for a pooler next to the database: instances hold as many client connections to pgbouncer as they like, and the database has as many backends as there are connections in pgbouncer's pool.
  2. Keep connections open. One connect costs as much as dozens of simple queries; a pool on the application side is needed even when pgbouncer is there.
  3. The pooler needs cores too. pgbouncer is single-threaded: in the measurement it took up to 0.44 of a core on reads at 25,462 transactions per second. Put it where it has enough CPU, and watch its load the same way as the database's.

The connection budget and the queue in the application

language contractPostgreSQL 16, max_connections, superuser_reserved_connections, reserved_connections (doc/src/sgml/config.sgml, REL_16_15)

The overall limit is max_connections, and ordinary roles cannot use the part of it set aside by superuser_reserved_connections (3 by default) and reserved_connections (since 16, 0 by default): the first is kept for superusers, the second for roles granted pg_use_reserved_connections. Beyond the limit a connection does not wait but is refused — in the measurement, the 298th. So the sum of all pools' maximum sizes — instances × the largest pool size of each service, plus pgbouncer's pools, background jobs, migrations and manual connections — has to fit into what is left, with room for a deploy, when old and new instances run side by side for a while.

What follows is a conclusion from Little's law and the measurement above. When the application has more concurrent requests than connections in its pool, a request first waits for a connection in the pool's queue, and that wait does not enter the latency of the database query — just like the wait inside pgbench that pulled λ·W/L on reads down to 0.703. So in the application's pool, the time spent waiting for a connection, the share of busy connections and the queue length are measured separately, and the timeout for acquiring a connection is set no longer than what is left of the request's time budget: a request that can no longer make it should not take a connection. This measurement gives no specific values — they depend on the service's load.

Before switching to transaction mode

The compatibility table is in the "Fourth" section. The check works the same way as in the measurement: run the application's tests through pgbouncer in transaction mode with a small pool (two connections in the measurement) and several clients at once, so that one client's transactions land on different backends. A test that passes at low concurrency proves little: according to the documentation, pgbouncer by default hands out connections in LIFO order, so that few connections get the most load, and a lone client often gets the same backend back, so the breakage does not show.

Reproducing the numbers

One script does everything: it creates a throwaway cluster in /tmp on its own port, fills it, runs six scripts and removes the cluster on exit.

sudo apt-get install -y postgresql-16 pgbouncer
sudo ./run.sh      # in the measurement directory; records go to runs/*.txt

It needs PostgreSQL 16, pgbouncer 1.22, openssl and python3; psycopg 3.3.9 is installed into .venv on the first run. The published run: PostgreSQL 16.15 and pgbench 16.15 from Ubuntu 24.04, pgbouncer 1.22.0, Linux 6.18, two Intel Xeon 2.30 GHz virtual CPUs, November 2026; single_client.py was recorded separately on the same kind of machine with a 2.10 GHz Xeon, and its numbers are compared only with each other. While it measures, the script watches for other load on the machine: a run during which other processes took more than 5% of the CPU is thrown away and repeated. Absolute numbers on another machine will differ; what carries over is the shape of the curves and the mechanism.

The conditions that affect the numbers, visible without opening the scripts:

  • the machine is a Firecracker microVM under KVM (kernel 6.18.44-fc) with two virtual CPUs; frequency and governor are not visible inside the VM — it has no cpufreq; the disk is ext4 on virtio;
  • PostgreSQL 16.15 from Ubuntu 24.04 packages: max_connections = 300, shared_buffers = 768MB, huge_pages = off, max_wal_size = 8GB, checkpoint_timeout = 30min, fsync and synchronous_commit at their defaults (on), autovacuum on; data from pgbench -i -s 30, then VACUUM ANALYZE and pg_prewarm of all pgbench tables and indexes;
  • warm-up: in the main measurement and the pooler measurement, 10 s of pgbench with 8 clients before each profile, not part of the record;
  • the --log journal is written to a temporary directory on the same disk: a 10% sample of transactions for read-only, all of them for TPC-B; the cost of logging was not measured separately;
  • pgbench, PostgreSQL and pgbouncer share the same two cores; placing pgbouncer on separate cores or a separate machine cannot be checked on this setup, and the numbers in the "Fourth" section apply only to the shared placement.

What measured this

The numbers in this article come from these scripts. Each one opens from here, together with the record of the run: what it was measured on, what came out, and with what spread.

Take to work

  • Budget connections for the whole database, not for one service: the sum of the pools of all instances has to fit what the database can serve, and the pool is sized with a load test — the number of cores is only a starting point. In the measurement on two cores TPS never rose above the peak again: by 256 clients it had fallen more than threefold on reads and 1.7-fold on TPC-B.
  • Keep connections open and take them from a pool: a TCP connect cost 1.9 ms, with TLS and SCRAM 8.4 ms, while the query itself on an open connection took about 0.06 ms.
  • Put pgbouncer in transaction mode when there are many clients and their transactions compete: on TPC-B a pool of 16 connections instead of 256 backends cut p99 from 560 to 142 ms — at the cost of the median (99 ms against 52) and 9% of TPS. Size the pool with room for waiting on the client inside a transaction — in a pool of 4, on average three connections out of four sat idle in transaction — and give pgbouncer CPU of its own: on the same cores it took almost half a core.
  • Before switching to transaction mode, clear out session state: SET becomes SET LOCAL, temporary tables become ON COMMIT DROP, advisory locks become pg_advisory_xact_lock, LISTEN moves to a direct connection, SQL PREPARE goes away.
  • Turn on max_prepared_statements if the driver prepares statements at the protocol level: in pgbouncer 1.22 it defaults to 0, and a statement the driver prepared is not found once the client lands on another server connection.

Common misconceptions

Claim

“More connections to the database mean more parallel work.”

Actually

Cores, the disk and locks do the work, not connections: in PostgreSQL every connection is a process, and no more processes run on the CPU at once than there are cores. In the measurement on two cores, reads peaked at 88,972 transactions per second with two clients and managed 25,887 at 256, while p99 grew from 0.056 to 21.481 ms. The surplus connections turned into a queue: on average 16.2 processes were ready to run on two cores.

Claim

“Every connection eats tens of megabytes — RSS shows it.”

Actually

RSS also counts shared memory — the shared_buffers pages the process has touched. After reading a table, a backend's RSS in the measurement was 153.0 MiB and its private memory 1.5 MiB; RSS summed over two hundred backends (3,619 MiB) is more than all of shared_buffers, because the same pages were counted two hundred times. On simple queries the main cost of a surplus connection is not memory but the queue for cores and locks.

Claim

“pgbouncer increases the database's throughput.”

Actually

The pooler gives the database no extra cores. In the measurement TPS through the pool was lower than direct: on TPC-B 2,548 against 2,795 with a pool of 16, on plain reads 25,462 against 31,932 with a pool of 4 — single-threaded pgbouncer on the same two cores took 0.44 of a core. The pool gains something else: 16 backends instead of 256, and a TPC-B p99 of 142 ms instead of 560; the median meanwhile rose from 52 to 99 ms.

Claim

“pgbouncer's transaction mode is transparent to the application.”

Actually

Only to whatever does not live in the session. In the measurement client B read the setting client A had made with SET, B found A's temporary table while A itself got “relation does not exist”; pg_try_advisory_lock(42) returned True to both clients, because a session that already holds a lock gets it again; the notification after LISTEN reached nobody, and pgbouncer logged “got packet 'A' from server when not linked”.

Claim

“pgbench prints latency average, so latency was measured.”

Actually

Without -P, --rate or --latency-limit, pgbench 16 does not measure it but computes it as “clients × duration / transactions” — which is Little's law, and Little's law cannot be checked with it. The article takes latency from the --log journal, and then you can see where the law “fails”: at 256 clients on reads λ·W/L = 0.703 — part of the time clients wait inside pgbench itself.

Knowledge check

Question 1 of 4

The database has 8 cores, and at peak hours they are already almost fully busy. The service was scaled from 4 to 16 pods, each with a pool of 40 connections. What is most likely to happen to the database's throughput?

Sources & further reading

12 SOURCES

  1. PostgreSQL 16 — How Connections Are EstablishedOfficial documentation. The process-per-connection model, text at tag REL_16_15 (doc/src/sgml/arch-dev.sgml). Verbatim: “PostgreSQL implements a “process per user” client/server model. In this model, every client process connects to exactly one backend process”, and on the postmaster: “Whenever it detects a request for a connection, it spawns a new backend process”.https://www.postgresql.org/docs/16/connect-estab.html
  2. PostgreSQL 16 — Connection Settings: max_connections, reserved_connections, superuser_reserved_connectionsOfficial documentation. Text at tag REL_16_15 (doc/src/sgml/config.sgml). max_connections: “Determines the maximum number of concurrent connections to the database server. The default is typically 100 connections”, and the setting can only be changed at server start. superuser_reserved_connections: three slots by default, and once at least max_connections minus that reserve are in use, “new connections will be accepted only for superusers”. reserved_connections is new in 16 and defaults to zero.https://www.postgresql.org/docs/16/runtime-config-connection.html
  3. PostgreSQL 16 — libpq, the sslmode parameterOfficial documentation. Text at tag REL_16_15 (doc/src/sgml/libpq.sgml): the default is “prefer (default)”, that is, “first try an SSL connection; if that fails, try a non-SSL connection”. Hence the article's observation: a libpq client connecting over TCP to a server with ssl = on uses TLS by default.https://www.postgresql.org/docs/16/libpq-connect.html#LIBPQ-CONNECT-SSLMODE
  4. PostgreSQL 16 — pgbenchOfficial documentation. Text at tag REL_16_15 (doc/src/sgml/ref/pgbench.sgml). The -C option: “Establish a new connection for each transaction, rather than doing it just once per client session. This is useful to measure the connection overhead”. The --log journal: the third field of each line is the “transaction's elapsed time, in microseconds”; the article's percentiles are computed from it.https://www.postgresql.org/docs/16/pgbench.html
  5. src/bin/pgbench/pgbench.c — printResults, tag REL_16_15Source code. Where pgbench's “latency average” comes from. Unless --rate, -P or --latency-limit is given, latency is not measured but computed: the branch commented “no measurement, show average latency computed from run time” prints total_duration * nclients / total_cnt. That is Little's law itself, which is why every run in the article uses -P and takes latency from the --log journal.https://github.com/postgres/postgres/blob/REL_16_15/src/bin/pgbench/pgbench.c
  6. PgBouncer 1.22.0 — configuration (doc/config.md at tag pgbouncer_1_22_0)Official documentation. pool_mode = transaction: “Server is released back to pool after transaction finishes”. The description of server_reset_query explains why there is no session reset in this mode: “clients must not use any session-based features, since each transaction ends up in a different connection and thus gets a different session state”. max_prepared_statements: with a non-zero value pgbouncer “tracks protocol-level named prepared statements related commands sent by the client in transaction and statement pooling mode”, but it “does not work for SQL-level prepared statement commands, so PREPARE, EXECUTE and DEALLOCATE are forwarded straight to Postgres”; the default is 0. server_round_robin: “By default, PgBouncer reuses server connections in LIFO (last-in, first-out) manner, so that few connections get the most load”.https://github.com/pgbouncer/pgbouncer/blob/pgbouncer_1_22_0/doc/config.md
  7. PgBouncer — Features: SQL feature map for pooling modesOfficial documentation. The mode compatibility table, site revision ccb120f of 6 November 2023 — the text in force when 1.22.0 was released (31 January 2024). For transaction pooling the column says “Never” for SET/RESET, LISTEN, WITH HOLD CURSOR, PREPARE / DEALLOCATE, PRESERVE/DELETE ROWS temp tables, LOAD statement and Session-level advisory locks; “Protocol-level prepared plans” is “Yes” with a footnote about max_prepared_statements. Above the table: transaction pooling “breaks client expectations of the server by design”.https://github.com/pgbouncer/pgbouncer.github.io/blob/ccb120f859a47fe3a6f3b2120d16194fd11f562f/features.md
  8. PgBouncer — changelog for 1.21.0 and 1.22.0 (NEWS.md at tag pgbouncer_1_22_0)Source. 1.21.0 (16 October 2023): “Add support for protocol-level named prepared statements!”, enabled by a non-zero max_prepared_statements, “100 is probably reasonable”. 1.22.0 (31 January 2024): support for DEALLOCATE ALL and DISCARD ALL with a non-zero max_prepared_statements; plain DEALLOCATE is still unsupported.https://github.com/pgbouncer/pgbouncer/blob/pgbouncer_1_22_0/NEWS.md
  9. PostgreSQL wiki — Number Of Database ConnectionsSource. The source of the formula HikariCP quotes. The section “How to Find the Optimal Database Connection Pool Size”: “for optimal throughput the number of active connections should be somewhere near ((core_count * 2) + effective_spindle_count)”; cores without hyperthreading, spindles zero if the working set is fully cached. The same page: “There hasn't been any analysis so far regarding how well the formula works with SSDs”. Last edited 14 March 2014; the formula is presented as a starting point, not a rule.https://wiki.postgresql.org/wiki/Number_Of_Database_Connections
  10. HikariCP wiki — About Pool SizingSource. The same formula, with the attribution: “The formula below is provided by the PostgreSQL project as a starting point”, and the conclusion: “You want a small pool, saturated with threads waiting for connections”.https://github.com/brettwooldridge/HikariCP/wiki/About-Pool-Sizing
  11. John D. C. Little — A Proof for the Queuing Formula: L = λW (Operations Research 9(3), 1961)Source. Little's law: the mean number of requests in the system equals the arrival rate times the mean time spent in it, L = λW. The article checks it on its own runs: L is the number of pgbench clients, each always with one transaction in flight; λ is TPS; W is the measured mean latency.https://doi.org/10.1287/opre.9.3.383
  12. PostgreSQL 16 — SET and Advisory LocksOfficial documentation. Text at tag REL_16_15 (ref/set.sgml, mvcc.sgml). SET LOCAL: “The effects of SET LOCAL last only till the end of the current transaction, whether committed or not”. Advisory locks: “Once acquired at session level, an advisory lock is held until explicitly released or the session ends”, while transaction-level ones “are automatically released at the end of the transaction”. And the reason both clients got the lock in the measurement: “If a session already holds a given advisory lock, additional requests by it will always succeed”.https://www.postgresql.org/docs/16/explicit-locking.html#ADVISORY-LOCKS