Why 200 Database Connections Made Your App Slower

Throughput fell 53% and latency rose 106x going from 8 to 400 Postgres connections. Here is the benchmark, and what to do instead.

17 min read
AI-assisted

Author's AI disclosure

The author reports using AI to help with this article.

The author confirms reviewing this article.

Why 200 Database Connections Made Your App Slower

The database CPU was pegged, so someone raised the connection pool to 200. Latency got worse. I measured why on Postgres, from 1 to 400 connections, and what to do instead.


The story is familiar. Traffic grows, the app starts timing out, and the database looks busy. Someone raises max_connections, or the pool size, from 20 to 200. The reasoning is "more connections means more concurrency, and more concurrency means more throughput."

That reasoning is true for a while, and then it isn't. Past a certain point, every extra connection only makes the database slower.

I measured where that point is on a real Postgres server, for three kinds of workload. I also measured what a small pool does for the same traffic, and whether idle connections hurt.

TL;DR (measured on a 2-CPU Postgres server):

  • Reads: from 8 to 400 connections, throughput fell 53% (84,995 to 40,335 queries/s) and latency rose 106× (0.09 ms to 10.1 ms). The CPUs stayed about 99% busy.

  • Writes: best at 16 connections (6,252 tx/s). At 400, throughput fell 48% and latency rose 48×.

  • A pool of 8 kept up with 60,000 reads/s. 100 or 400 direct connections could not.

  • When transactions mostly wait, more connections do help. That workload scaled up to 200.

  • Idle connections cost about 1.3 MB each but did not slow anything down.

Every number here is measured, not estimated. Each point is a 15-second pgbench run against a real Postgres 16 server. I repeated the sweeps (3 runs for reads, 2 for read-write and waiting) and averaged them. The scripts are in the "Run it yourself" section near the end.


What a connection actually is

Postgres doesn't use a thread pool. From the official docs: the server "starts ('forks') a new process for each connection."

So 400 connections means 400 operating-system processes, all asking the scheduler for time on the same few CPU cores. Postgres can only run as many queries at once as you have cores. Everything beyond that waits, and the waiting just moves from your pool into the database.

flowchart LR
  subgraph good["A pool of 8"]
    direction LR
    A2["App instances<br/>400 requests at once"] --> P["Pool<br/>392 wait their turn here"]
    P --> B2["8 backend processes"]
    B2 --> C2["2 CPU cores<br/>busy doing queries"]
  end
  subgraph bad["400 direct connections"]
    direction LR
    A1["App instances<br/>400 requests at once"] --> B1["400 backend processes"]
    B1 --> C1["2 CPU cores<br/>busy switching and queuing"]
  end
  style good fill:#ebfbee,stroke:#2f9e44,color:#000
  style bad fill:#fff5f5,stroke:#e03131,color:#000
  classDef app fill:#e7f5ff,stroke:#1971c2,color:#000
  classDef pool fill:#d3f9d8,stroke:#2f9e44,color:#000
  classDef proc fill:#fff3bf,stroke:#f08c00,color:#000
  classDef cpu fill:#ffe3e3,stroke:#e03131,color:#000
  class A1,A2 app
  class P pool
  class B1,B2 proc
  class C1,C2 cpu

The question is where you want the queue: in a pool that costs almost nothing, or inside the database, where every waiting request is a live process.

How I tested it

  • Server: Postgres 16.15 on a 2-vCPU, 8 GB VM. The only setting I changed was max_connections = 600.

  • Data: pgbench scale 50, 5 million accounts, about 750 MB. It fits in RAM, so the read tests measure CPU rather than disk.

  • Load: pgbench with prepared statements, each point 15 seconds, connections from 1 to 400. Three workloads:

    • Read-only: one indexed lookup per transaction (pgbench -S).

    • Read-write: pgbench's default TPC-B-like transaction: three updates, a select and an insert, with a commit that must reach disk.

    • Waiting: a lookup, then 5 ms of pg_sleep inside the transaction. It stands in for an app that holds a transaction open while it calls another service.

  • Variance: the median difference between runs of the same point was 5%, and the largest was 30% (the 400-connection read-only point, which ranged from 35,430 to 47,736 tx/s).

Three caveats, so you can judge the numbers fairly:

  1. The benchmark client shares the machine. pgbench used 9% to 18% of the machine's CPU time in the runs I measured, and Postgres plus the kernel used the rest. A real app would run elsewhere, so absolute numbers would be higher. The shape is what matters.

  2. Low connection counts are noisy. More on that below.

  3. Your numbers will differ. The point where throughput peaks depends on your cores, your queries, and your disk. Run the scripts on your own hardware.

Experiment 1: reads that use the CPU

Every transaction here is one cached, indexed lookup, so the only resource that matters is CPU.

Connections

Queries/s

vs. 8 connections

Latency (ms)

CPU busy

1

19,668

23%

0.05

47%

2

125,219

147%

0.02

99%

4

67,103

79%

0.06

99%

8 (baseline)

84,995

100%

0.09

100%

16

78,962

93%

0.20

99%

32

70,961

83%

0.45

99%

64

57,851

68%

1.11

99%

100

56,962

67%

1.76

99%

200

54,688

64%

3.67

99%

400

40,335

47%

10.1

99%

From 8 connections up, the trend is a steady fall:

  • Throughput at 100 connections was 33% lower than at 8, at 200 it was 36% lower, and at 400 it was 53% lower.

  • The CPUs were about 99% busy at every point from 2 connections up. So the machine was never idle. It was doing less useful work for the same CPU time.

  • Latency per query went from 0.09 ms to 10.1 ms.

I did not profile why the throughput falls.

Context switches per transaction didn't rise (1.35 at 8 connections, 1.25 at 400), so the popular explanation, "too many context switches," isn't what my counter shows.

My hypothesis is that hundreds of processes with different working sets keep evicting each other's data from the CPU caches. Treat that as a guess, not a result.

The first rows need a note:

  • 1 connection is slow (19,668 queries/s). The client and server just take turns, and one connection can't use both CPUs.

  • 2 connections gave the highest number of all (125,219), and 4 dipped to 67,103.

That dip is partly my benchmark's doing. When I gave pgbench one thread per connection, 4 connections ran at 108,666 queries/s instead of 75,743, and 8 connections at 99,169 instead of 81,409.

At 100 connections and above, the thread count didn't change the picture. At 400 connections, more threads made things slightly worse, not better (33,542 queries/s with 2 threads, 24,662 with 400 threads).

So I don't draw conclusions from 1 to 4 connections, other than that very few connections already keep both CPUs busy.

Latency and Little's Law

There's a tidy relationship behind the latency column. Little's Law says the long-term average number of items in a stationary system equals the average arrival rate times the average time each item spends in it: L = λW (Wikipedia).

It doesn't depend on the arrival pattern or the service-time distribution.

Here, L is the number of connections that always have a query in flight, λ is throughput, and W is latency. Rearranged: latency = connections ÷ throughput.

At 400 connections the read-only throughput was 40,335 queries/s, so the law predicts 9.92 ms. pgbench measured 10.1 ms. Across all 70 measurements in my sweeps, the prediction was within 2% of the measurement (median 0.01%).

That's nearly an identity for a closed-loop test, so it's not a surprise. What matters is what it implies.

If throughput stops growing, every extra connection adds latency in direct proportion. Going from 200 to 400 connections doubled the queue and took away a quarter of the throughput. It couldn't have helped.

Experiment 2: writes that wait for the disk

The read-write workload has locks on hot rows and a commit that waits for the disk, so it behaves a little differently.

Connections

Transactions/s

vs. best (16)

Latency (ms)

CPU busy

1

2,118

34%

0.47

39%

2

3,476

56%

0.58

62%

4

5,312

85%

0.75

75%

8

5,598

90%

1.43

86%

16 (baseline)

6,252

100%

2.56

88%

32

6,044

97%

5.30

90%

64

5,525

88%

11.7

92%

100

5,304

85%

18.9

92%

200

4,118

66%

48.7

93%

400

3,269

52%

122

94%

  • The best throughput was at 16 connections, which is 8 times the core count.

  • That's higher than for cached reads because each commit waits for the disk, and while one transaction waits, another can use the CPU. The CPUs were only 75% to 88% busy at 4 to 16 connections.

  • After that the decline was gentler but still clear: 85% of the best at 100 connections, 66% at 200, and about half (48% lower) at 400.

  • Latency went from 2.56 ms at the best point to 122 ms at 400, a 48× increase for half the throughput.

%%{init: {"themeVariables": {"xyChart": {"plotColorPalette": "#1971c2, #e8590c"}}}}%%
xychart-beta
  title "Throughput vs. connections (% of best result, higher is better)"
  x-axis ["8", "16", "32", "64", "100", "200", "400"]
  y-axis "% of best" 0 --> 110
  line [100, 93, 83, 68, 67, 64, 47]
  line [90, 100, 97, 88, 85, 66, 52]

Blue: read-only lookups, relative to 8 connections. Orange: read-write, relative to 16 connections.

Experiment 3: when more connections do help

If the story ended there, "fewer connections is always better" would be the lesson. It's not. This workload spends most of each transaction waiting for 5 ms, doing very little CPU work.

Connections

Transactions/s

vs. best (200)

Latency (ms)

CPU busy

1

184

1%

5.44

3%

2

368

2%

5.44

4%

4

734

5%

5.45

7%

8

1,463

10%

5.47

14%

16

2,923

19%

5.47

26%

32

5,823

38%

5.50

48%

64

11,152

73%

5.74

71%

100

14,782

97%

6.77

85%

200 (baseline)

15,211

100%

13.2

94%

400

13,885

91%

28.9

95%

Throughput roughly doubled each time the connection count doubled, up to 64 connections (1,463 tx/s at 8, 11,152 at 64), because the CPU had almost nothing to do (14% busy at 8 connections).

It flattened as the CPUs filled up (85% at 100), peaked at 200 connections (15,211 tx/s), and then fell to 91% of that peak at 400, with latency more than doubling (13.2 ms to 28.9 ms).

%%{init: {"themeVariables": {"xyChart": {"plotColorPalette": "#2f9e44"}}}}%%
xychart-beta
  title "Transactions/s with a 5 ms wait inside each transaction"
  x-axis ["1", "2", "4", "8", "16", "32", "64", "100", "200", "400"]
  y-axis "transactions per second" 0 --> 17000
  bar [184, 368, 734, 1463, 2923, 5823, 11152, 14782, 15211, 13885]

This is what the HikariCP pool-sizing guide says in words: "More threads only perform better when blocking creates opportunities for executing."

It's also why a pool of 200 can look fine in a test whose queries spend most of their time waiting, and then fall apart on a CPU-heavy day.

It also points to a cheaper fix than any pool setting: don't hold a transaction open while you wait for something else. Every millisecond a transaction sits idle waiting on an HTTP call is a millisecond a scarce connection is not doing work.

What about idle connections?

A common worry is that hundreds of idle connections slow the database down. I opened 100, 250 and 500 idle connections (each had run one lookup, like a real app connection) and measured two things.

  • Memory: each backend held about 1.3 MB of private memory (1.4 MB including its share of shared memory). That makes 500 idle connections about 635 MB. This is a light session. A connection that has run many different queries, or holds a large work_mem allocation, uses more.

  • Speed: I measured 8 busy clients while the idle connections sat there.

Idle connections

Memory used

Busy clients' queries/s

Range of the 2 runs

0

-

80,010

79,778 to 80,242

100

127 MB

95,972

86,204 to 105,741

250

318 MB

87,048

80,665 to 93,431

500

635 MB

87,950

85,125 to 90,774

I found no slowdown.

The same setup varied by up to about 20% between its two runs, so a small effect would be hidden. But the runs with idle connections were not lower than the baseline (80,010 queries/s with none).

This matches the PostgreSQL 14 release notes, which say the faster MVCC snapshot computation "also improves performance when there are many idle sessions."

So the danger isn't idle connections. It's connections that are active at the same time. A big pool of mostly idle connections is cheap. The trouble starts when a spike makes all of them busy together.

The fix: a small pool, and a queue in front of it

The PostgreSQL wiki gives a starting point: "for optimal throughput the number of active connections should be somewhere near ((core_count * 2) + effective_spindle_count)."

  • Core count excludes hyperthreads.

  • Effective spindle count "is zero if the active data set is fully cached."

  • Beyond that point, "throughput starts to fall off due to the overhead from that contention."

My results fit that as a starting point to tune from, not a law. On this 2-core machine:

  • Cached reads: the formula gives 4, and the CPUs were saturated from 2 connections up.

  • Read-write: the best was 16, because commits wait on the disk.

  • Waiting workload: it wanted 100 to 200.

To test the idea, I sent the same traffic through different connection counts. I didn't have PgBouncer on this machine, so I imitated a pool with pgbench's --rate mode.

It sends transactions at a fixed average rate, the way real users do, and measures each one's latency from the moment it was scheduled. So time spent waiting for a free connection counts, and a small -c behaves like a small pool with a queue in front.

A real pooler adds a proxy hop, which this test doesn't include.

"Kept up" means the achieved rate was at least 95% of the offered rate. Where the two runs differed, the table shows both values.

Read-only lookups (pool of 8, versus 100 and 400 direct connections):

Offered tx/s

Connections

Kept up?

Achieved tx/s

Median latency (ms)

Mean latency (ms)

20,000

8

yes, both runs

20,002

0.21 to 0.23

0.33 to 2.88

100

yes, both runs

19,888

0.27 to 0.29

0.71 to 0.76

400

yes, both runs

19,529

0.53 to 0.83

6.06 to 7.00

40,000

8

yes, both runs

40,014

0.21

0.35 to 0.40

100

yes, both runs

39,773

0.49 to 0.63

2.34 to 2.80

400

in 1 of 2 runs

35,402

6.87 to 2171

72.8 to 2563

60,000

8

yes, both runs

59,923

0.35 to 0.72

6.73 to 64.9

100

no

54,180

1012 to 2652

1279 to 2608

400

no

42,115

2515 to 6143

2679 to 6290

Read-write (pool of 16, versus 100 and 400 direct connections):

Offered tx/s

Connections

Kept up?

Achieved tx/s

Median latency (ms)

Mean latency (ms)

2,000

16

yes, both runs

2,000

0.98 to 1.17

1.43 to 1.86

100

yes, both runs

1,978

1.25 to 1.67

45.0 to 144

400

yes, both runs

1,955

1.46 to 2.28

55.1 to 148

3,500

16

yes, both runs

3,481

1.43 to 1.44

3.02 to 35.6

100

yes, both runs

3,460

1.66 to 2.97

6.61 to 8.31

400

in 1 of 2 runs

3,077

124 to 3687

393 to 3643

5,000

16

yes, both runs

4,968

2.06 to 3.30

4.85 to 22.6

100

yes, both runs

4,972

5.03 to 264

54.8 to 302

400

no

3,067

5613 to 7433

5656 to 6951

What the tables show:

  • At 20,000 reads/s every setup kept up, but with 400 direct connections the median latency was 0.68 ms and the mean 6.53 ms, against 0.22 ms and 1.60 ms for the pool of 8. That's about 4× higher mean latency for the same traffic.

  • At 60,000 reads/s the pool of 8 delivered 59,923 reads/s. 100 direct connections managed 54,180, and 400 managed 42,115. Where a setup falls behind, requests keep piling up, so the latencies in the "no" rows grow the longer the test runs. Those rows are measured over 15 seconds.

  • For read-write at 5,000 tx/s, the pool of 16 delivered 4,968 tx/s with a mean latency of 13.7 ms. 400 direct connections delivered 3,067 tx/s, with a mean latency of 6304 ms.

I'm not quoting 99th-percentile latencies. They swung too much between runs on this VM: the same setup showed 3 ms in one run and 132 ms in another. The means and medians were stable enough to compare.

Two practical points about poolers:

  • PgBouncer has three pool modes. In transaction mode, "a server connection is assigned to a client only during a transaction" (PgBouncer docs). That's the mode that lets 400 clients share a handful of connections.

  • Transaction mode has restrictions. The docs list SET/RESET, LISTEN, session-level advisory locks, WITH HOLD cursors and SQL-level PREPARE as unsupported. Protocol-level prepared statements work if you set max_prepared_statements to a non-zero value. Check your app for these before switching.

flowchart TD
  S["Sweep connections with<br/>your real queries"] --> W{"Do transactions mostly<br/>wait on something else?"}
  W -->|"No: CPU-bound"| C["Start near 2 to 4 times cores,<br/>test up to about 8 times"]
  W -->|"Yes: waits on disk,<br/>network or other services"| F["Fix the waiting first,<br/>then size up from there"]
  C --> T["Total = app instances x pool size"]
  F --> T
  T --> Q{"Total above what<br/>the sweep says is best?"}
  Q -->|"No"| D["Done: keep monitoring"]
  Q -->|"Yes"| P["Put a pooler in front:<br/>PgBouncer in transaction mode"]
  classDef start fill:#e7f5ff,stroke:#1971c2,color:#000
  classDef ask fill:#fff3bf,stroke:#f08c00,color:#000
  classDef act fill:#d3f9d8,stroke:#2f9e44,color:#000
  classDef warn fill:#ffe3e3,stroke:#e03131,color:#000
  class S start
  class W,Q ask
  class C,F,D,P act
  class T warn

Checklist

  1. Add up the connections across every app instance. The surprise is usually multiplication: 20 pods with a pool of 10 each is 200 connections.

  2. Find your own knee. Run the sweep below on hardware like production, using queries like yours. The best count can be anywhere from a few times the core count (CPU-bound) to a hundred or more (mostly waiting).

  3. Don't hold a connection while you wait. Release it before calling other services, or at least keep transactions short.

  4. Queue in front of the database, not inside it. Use a pool in the app, and PgBouncer in transaction mode when many instances share one database.

  5. Don't fear idle connections, fear simultaneous ones. Set max_connections for your worst-case active load, and watch pg_stat_activity for how many are running at once.

Run it yourself

You need Postgres (I used 16) with max_connections of at least 600 and the pg_prewarm contrib extension, plus the matching pgbench. Set PGHOST, PGPORT and PGUSER for a scratch server. The memory test reads /proc and needs to run as root or the postgres user on the same machine.

./setup.sh                          # creates the connbench database (scale 50)
export PGDATABASE=connbench
python3 sweep.py 1 ro rw wait       # ~10 min per run; appends to sweep.csv
python3 idle_cost.py                # ~4 min; memory and speed with idle connections
python3 pool_test.py 1              # ~6 min; small pool vs. many direct connections
python3 cpu_split.py 400 -S         # how the CPUs were shared with pgbench
./client_threads.sh                 # does pgbench's thread count change the result?
setup.sh: the test database
#!/usr/bin/env bash
# setup.sh: a scratch database with pgbench scale 50 (5 million accounts, ~750 MB, fits in RAM).
# Postgres must allow enough connections (the tests open up to 500): max_connections = 600.
set -euo pipefail
createdb connbench
export PGDATABASE=connbench
pgbench -i -s 50 -q
psql -X -q -c "create extension if not exists pg_prewarm" -c "select pg_prewarm('pgbench_accounts')" \
     -c "select pg_prewarm('pgbench_accounts_pkey')"
sweep.py and bench/wait.sql: throughput and latency from 1 to 400 connections
"""sweep.py <run> <workload>...  -- throughput and latency from 1 to 400 connections.

Workloads: ro (pgbench -S, single-row lookups), rw (pgbench's TPC-B-like read-write),
wait (bench/wait.sql: a lookup plus 5 ms of waiting inside the transaction).
Appends to sweep.csv. Connection settings come from PGHOST / PGPORT / PGUSER / PGDATABASE.
"""
import csv, os, re, subprocess, sys, time

CLIENTS = [int(x) for x in os.environ.get('CLIENTS', '1 2 4 8 16 32 64 100 200 400').split()]
SECONDS = int(os.environ.get('SECONDS_PER_POINT', 15))
ARGS = {"ro": ["-S"], "rw": [], "wait": ["-f", "bench/wait.sql"]}

def psql(sql):
    subprocess.run(["psql", "-X", "-q", "-v", "ON_ERROR_STOP=1", "-c", sql], check=True, capture_output=True)

def ctxt():
    for line in open("/proc/stat"):
        if line.startswith("ctxt"):
            return int(line.split()[1])

def busy():
    v = list(map(int, open("/proc/stat").readline().split()[1:]))
    return sum(v) - v[3] - v[4], sum(v)

run, workloads = sys.argv[1], sys.argv[2:]
new = not os.path.exists("sweep.csv")
out = open("sweep.csv", "a", newline="")
w = csv.writer(out)
if new:
    w.writerow(["run", "workload", "clients", "tps", "latency_ms", "failed", "ctx_per_txn", "cpu_busy_pct"])
psql("select pg_prewarm('pgbench_accounts'), pg_prewarm('pgbench_accounts_pkey')")

for wl in workloads:
    for c in CLIENTS:
        if wl == "rw":
            psql("truncate pgbench_history")
            psql("vacuum pgbench_branches, pgbench_tellers")
            psql("checkpoint")
        time.sleep(3)                                    # let the previous run's backends exit
        c0, (b0, t0) = ctxt(), busy()
        res = subprocess.run(["pgbench", "-n", "-M", "prepared", "-c", str(c), "-j", str(min(c, 2)),
                              "-T", str(SECONDS)] + ARGS[wl], capture_output=True, text=True)
        c1, (b1, t1) = ctxt(), busy()
        o = res.stdout
        tps = float(re.search(r"tps = ([\d.]+)", o)[1])
        lat = float(re.search(r"latency average = ([\d.]+)", o)[1])
        failed = re.search(r"number of failed transactions: (\d+)", o)
        txns = int(re.search(r"number of transactions actually processed: (\d+)", o)[1])
        row = [run, wl, c, round(tps, 1), lat, int(failed[1]) if failed else 0,
               round((c1 - c0) / txns, 2), round(100 * (b1 - b0) / (t1 - t0), 1)]
        w.writerow(row); out.flush()
        print(*row, flush=True)
-- A transaction that holds its connection while it waits 5 ms (think: a call to another
-- service inside an open transaction). Mostly waiting, little CPU.
\set aid random(1, 5000000)
BEGIN;
SELECT abalance FROM pgbench_accounts WHERE aid = :aid;
SELECT pg_sleep(0.005);
END;
idle_cost.py and bench/idle.sql: memory and speed with idle connections
"""idle_cost.py -- what do idle connections cost?

1. Memory: open N idle connections, then add up what each backend process holds privately
   (USS, from /proc/<pid>/smaps_rollup) and its proportional share (PSS).
2. Speed: how fast do 8 busy clients run while N other connections sit idle?
Appends to idle_cost.csv. Needs root (or the postgres user) to read other processes' smaps.
"""
import csv, os, re, subprocess, sys, time

COUNTS = [0, 100, 250, 500]
ROUNDS = 2
SECONDS = 15

def psql(sql):
    return subprocess.run(["psql", "-X", "-At", "-c", sql], check=True, capture_output=True, text=True).stdout.strip()

def backend_pids():
    return [int(p) for p in psql("select pid from pg_stat_activity where application_name = 'pgbench'").split()]

def smaps(pid):
    d = {}
    for line in open(f"/proc/{pid}/smaps_rollup"):
        m = re.match(r"(\w+):\s+(\d+) kB", line)
        if m:
            d[m[1]] = int(m[2])
    return d

def start_idle(n):
    if n == 0:
        return None
    p = subprocess.Popen(["pgbench", "-n", "-c", str(n), "-j", "2", "-T", "600", "-f", "bench/idle.sql"],
                         stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    for _ in range(60):                       # wait until all n are connected
        time.sleep(1)
        if int(psql("select count(*) from pg_stat_activity where application_name = 'pgbench'")) >= n:
            break
    time.sleep(2)
    return p

new = not os.path.exists("idle_cost.csv")
out = open("idle_cost.csv", "a", newline="")
w = csv.writer(out)
if new:
    w.writerow(["round", "idle_connections", "uss_mb_per_connection", "pss_mb_per_connection", "busy_tps"])

for rnd in range(1, ROUNDS + 1):
    for n in COUNTS:
        time.sleep(3)
        holder = start_idle(n)
        uss = pss = ""
        if n:
            pids = backend_pids()
            s = [smaps(p) for p in pids]
            uss = round(sum(x["Private_Clean"] + x["Private_Dirty"] for x in s) / len(s) / 1024, 2)
            pss = round(sum(x["Pss"] for x in s) / len(s) / 1024, 2)
        res = subprocess.run(["pgbench", "-n", "-S", "-M", "prepared", "-c", "8", "-j", "2", "-T", str(SECONDS)],
                             capture_output=True, text=True).stdout
        tps = float(re.search(r"tps = ([\d.]+)", res)[1])
        if holder:
            holder.terminate(); holder.wait()
        row = [rnd, n, uss, pss, round(tps, 1)]
        w.writerow(row); out.flush()
        print(*row, flush=True)
-- An idle connection: runs one lookup (so it has touched a table, like a real app
-- connection), then does nothing for ten minutes. The test kills it long before that.
\set aid random(1, 5000000)
SELECT abalance FROM pgbench_accounts WHERE aid = :aid;
\sleep 600 s
pool_test.py: a small pool vs. many direct connections
"""pool_test.py <run> -- the same traffic through a small pool vs. many direct connections.

pgbench --rate sends transactions at a fixed average rate (Poisson arrivals), like real users,
instead of "as fast as possible". Each transaction's latency is measured from the moment it was
*scheduled*, so time spent waiting for a free connection counts. That makes a small -c act like
a pool: requests wait for one of its few connections. Appends to pool.csv.
"""
import csv, glob, os, re, subprocess, sys, time

SECONDS = 15
# workload -> (extra pgbench args, offered rates in tx/s, pool size, direct connection counts)
PLAN = {
    "ro": (["-S"], [20000, 40000, 60000], 8, [100, 400]),
    "rw": ([], [2000, 3500, 5000], 16, [100, 400]),
}

def psql(sql):
    subprocess.run(["psql", "-X", "-q", "-v", "ON_ERROR_STOP=1", "-c", sql], check=True, capture_output=True)

def pct(xs, p):
    return xs[min(len(xs) - 1, int(len(xs) * p))]

run = sys.argv[1]
new = not os.path.exists("pool.csv")
out = open("pool.csv", "a", newline="")
w = csv.writer(out)
if new:
    w.writerow(["run", "workload", "offered_tps", "connections", "achieved_tps", "p50_ms", "p99_ms", "avg_ms"])
os.makedirs("logs", exist_ok=True)

for wl, (args, rates, pool, direct) in PLAN.items():
    for rate in rates:
        for c in [pool] + direct:
            if wl == "rw":
                psql("truncate pgbench_history"); psql("vacuum pgbench_branches, pgbench_tellers"); psql("checkpoint")
            for f in glob.glob("logs/pool.*"):
                os.remove(f)
            time.sleep(3)
            res = subprocess.run(["pgbench", "-n", "-M", "prepared", "-c", str(c), "-j", "2", "-T", str(SECONDS),
                                  "-R", str(rate), "-l", "--log-prefix=logs/pool"] + args,
                                 capture_output=True, text=True).stdout
            tps = float(re.search(r"tps = ([\d.]+)", res)[1])
            lat = []
            for f in glob.glob("logs/pool.*"):
                for line in open(f):
                    p = line.split()          # client, txn no, latency us, script, epoch, epoch us, schedule lag us
                    lat.append((int(p[2]) + int(p[6])) / 1000)
            lat.sort()
            row = [run, wl, rate, c, round(tps), round(pct(lat, .50), 2), round(pct(lat, .99), 2),
                   round(sum(lat) / len(lat), 2)]
            w.writerow(row); out.flush()
            print(*row, flush=True)
cpu_split.py and client_threads.sh: checks on the benchmark client
"""cpu_split.py <clients> [pgbench args]: split the machine's CPU time between pgbench (client) and everything else."""
import os, resource, subprocess, sys, time

def cpu_total():
    f = open("/proc/stat").readline().split()[1:]
    v = list(map(int, f))
    return sum(v) - v[3] - v[4], sum(v)          # busy (excl. idle, iowait), all

c = sys.argv[1]
time.sleep(3)                                     # let backends from the previous run exit
b0, t0 = cpu_total(); r0 = resource.getrusage(resource.RUSAGE_CHILDREN)
out = subprocess.run(["pgbench", "-n", "-M", "prepared", "-c", c, "-j", "2", "-T", "10"] + sys.argv[2:],
                     capture_output=True, text=True).stdout
b1, t1 = cpu_total(); r1 = resource.getrusage(resource.RUSAGE_CHILDREN)
hz = os.sysconf("SC_CLK_TCK")
wall = (t1 - t0) / hz / 2                          # seconds, 2 CPUs
pgb = (r1.ru_utime + r1.ru_stime - r0.ru_utime - r0.ru_stime)
busy = (b1 - b0) / hz
tps = [l.split()[2] for l in out.splitlines() if l.startswith("tps")][0]
print(f"clients={c:>3}  tps={float(tps):>9,.0f}  machine busy={100*busy/(wall*2):.0f}%  "
      f"pgbench={100*pgb/(wall*2):.0f}% of the machine  postgres+kernel={100*(busy-pgb)/(wall*2):.0f}%")
#!/usr/bin/env bash
# client_threads.sh: with only 2 CPUs shared by pgbench and Postgres, does the number of
# pgbench threads change the read-only result? (2 repeats each)
set -euo pipefail
for round in 1 2; do
  for cfg in "2 1" "2 2" "4 1" "4 2" "4 4" "8 2" "8 8" "100 2" "100 100" "400 2" "400 64" "400 400"; do
    set -- $cfg; sleep 3
    tps=$(pgbench -n -S -M prepared -c "$1" -j "$2" -T 8 | grep -oP '^tps = \K[0-9]+')
    echo "round=$round  connections=$1  pgbench_threads=$2  tps=$tps"
  done
done

The bottom line

A connection is a process, and a database can only run as many queries at once as it has cores. Past that point, extra connections add no capacity. They just move your queue from the pool, where it's cheap, into the database, where it's expensive.

In these tests that cost was large and consistent:

  • Read-only throughput fell 53% between 8 and 400 connections.

  • Read-write throughput fell 48% from its best point.

  • Latency rose 106× and 48×, while the CPUs were busy the whole time.

  • A pool of 8 served traffic that 100 or 400 direct connections couldn't.

Two things keep this from being a simple rule:

  • The right number depends on how much of each transaction is spent waiting, so measure it on your own workload.

  • Idle connections are cheap, so the thing to control is how many are active at the same moment.

Size the pool for the cores and the waiting, put a pooler in front when many clients share one database, and keep the queue out of Postgres.

Comments0

Log in to join the discussion.

No comments yet.

Emma Clements

Read articles by this author.

Subscribe to Emma Clements's newsletter

Get the articles this author chooses to send by email.