Your Postgres Connection Limit Is Not Your Concurrency Limit

Date:

A database that accepts a hundred connections is not a database that does useful work on a hundred things at once. On a four-core box, throughput stopped scaling at four, and the fix was to stop counting connections and start counting cores.

The short answer: the Postgres connection limit, max_connections, is a ceiling (the point at which a new connection is refused), not a measure of how much work a database can do at once. That number is governed by your CPU cores. On a four-core box, read-only throughput plateaued by eight clients and read-write throughput peaked at four and then fell, while latency climbed roughly a hundredfold. So don’t raise the connection limit to cure a slowdown: cap concurrent heavy jobs near the core count, leave cheap read-only and network-bound queries uncounted, and spend any spare tuning budget on memory instead.

A small data pipeline runs on a self-hosted PostgreSQL on a four-core developer workstation. When several heavy jobs (bulk transforms over a shared set of tables) happened to run at the same time, the machine pinned all four cores at 100% and everything slowed to a crawl. The obvious diagnosis was that the database was running out of connections. The obvious fix was to raise max_connections, or to add more worker processes so the work would finish sooner.

Both were wrong, in the same way, for the same reason.

The connection limit is a ceiling, not a target

max_connections defaults to

  1. It is a hard limit: connection 101 is refused outright. It is

easy to read that number as “how much concurrency the database supports,” and therefore to treat a slowdown as evidence you are near it. But the connection ceiling and the point where more concurrency stops helping are two completely different numbers, and on most hardware the second is far below the first. Raising the ceiling moves the wrong one.

The number that actually governs throughput is the core count. A query that is executing, not waiting on the network but actually computing, needs a core. Past the point where every core is busy, each additional concurrent query does not get its own core; it time-slices one, adds a context switch, and, if it writes, contends for the same locks and the same write-ahead log as the others. You do not buy throughput. You spend it.

You do not buy throughput. You spend it.

The measurement

Rather than argue about it, sweep it. On the four-core box, an isolated scratch database, pgbench driving a rising number of concurrent clients: first read-only (SELECT only, the purest measure of compute-bound throughput), then read-write (the standard mixed transaction, which adds lock and WAL contention). Six seconds per level; throughput and average latency recorded at each.

Read-only throughput climbs to the core count, tops out around twice it, and then goes flat.

Read-only PostgreSQL throughput versus concurrent clients on a four-core host. Transactions per second rise steeply from about 3,700 at one client to about 8,500 at four, peak near 8,800 at eight clients, then flatten and drift slightly down through 16, 32 and 48 clients. A dashed line marks eight clients as twice the core count.

One client did about 3,700 transactions per second. Four, the core count, did about 8,500, most of the total gain. Eight squeezed out a peak near 8,800. After that, adding clients did nothing: 16, 32 and 48 all sat between 7,700 and 8,400. The database took on all forty-eight connections without complaint. It just had no more cores to run them on.

The database accepted every connection happily; it just had no more cores to run them on.

Read-write is sharper: it peaks at the core count and then actively declines.

Read-write PostgreSQL throughput versus concurrent clients on a four-core host. Transactions per second peak at about 1,046 at four clients, then decline through eight, twelve and sixteen clients, recover partially near thirty-two, and collapse to about 207 at forty-eight. A dashed line marks four clients as the core count.

Here the peak, about 1,046 transactions per second, landed exactly at four clients. Beyond it, throughput fell: the writers were fighting each other for locks and for the write-ahead log, and that contention subtracts from the total. This is the curve that matters, because real workloads write.

The part that does not show up in a throughput average: latency

Throughput going flat sounds harmless: you are not losing work, just not gaining it. Latency tells the real story. It is the tax you pay for every connection past the knee, and it is not linear.

Average transaction latency versus concurrent clients for both workloads on a logarithmic scale. Read-only latency rises gently from about 0.3 milliseconds at one client to about 6 milliseconds at forty-eight. Read-write latency rises from about 2 milliseconds to about 231 milliseconds at forty-eight, a roughly hundredfold increase, with the steep climb beginning at the four-client core-count mark.

Read-write latency went from about 2 milliseconds at one client to 231 milliseconds at 48, a hundredfold increase, for a workload that was, by then, doing less total work than it did at four clients. Per-client throughput told the same story from the other side: it collapsed from 3,700 transactions per second per client at one client to 161 at 48, a 23× degradation. Every extra connection made every connection slower.

None of this is a Postgres limitation, and none of it is fixed by a bigger connection ceiling. It is what happens when you ask four cores to run more than four things.

What to cap instead

The corrected mental model is a one-liner: size concurrency to cores, not to the connection ceiling. Concretely, for this pipeline:

  • Cap concurrent heavy jobs at roughly the core count. Not with max_connections, which only refuses the overflow at the door and does not keep you off the inefficient part of the curve. A small connection-count semaphore does the job: a heavy job tags its database connection, and a new heavy job checks how many such tags are already active and refuses to start if the machine is already full (with an override for the rare case you mean it). Cheap read-only queries are not counted, because they are not what saturates the cores.
  • For a network-bound job, the database is not the limit at all. A crawler or an API poller holds one connection and spends its life waiting on the network. Ten of those will not trouble the database; the thing to limit there is politeness to the remote host, not local connections.
  • If you want more headroom, tune memory before you touch concurrency. Against a fixed core count, more connections cannot help; giving the working set more room to stay resident can. On a memory- constrained shared box, a moderate shared_buffers bump (the stock 128 MB is low) buys real headroom. But on Windows, and on a machine also running other services, moderate is the operative word, and the change needs a restart. The core count is still the ceiling; memory just stops you re-reading the same hot pages off disk. If you are consistently core-bound, the honest fix is more cores: a hosting decision, not a configuration one.

Size concurrency to cores, not to the connection ceiling.

When raising the Postgres connection limit is the right fix: idle connections

Everything above is about busy connections. There is one case where the Postgres connection limit really is the number to change: when the connections filling it are idle.

Months later, the same kind of pipeline hit a different wall. It had grown into many network-bound workers on several machines, all writing to one Postgres on a four-core, 16 GB server. Each worker held two connections: one that keeps a lock for as long as the worker runs, and one it does its work on. Both spend most of their life idle, waiting on the network. The cores had room to spare. The connection count did not: at two per worker, with three kept free for an operator, a ceiling of 100 fits 48 workers, and the check that runs before each launch started refusing new ones.

That is the refusal case from the FAQ below, and here raising the ceiling is correct, because an idle connection costs memory, not cores. Two questions decide how far to raise it: what one connection costs, and whether the operating system allows that many.

What an idle connection costs. Postgres reports a session’s own memory in pg_backend_memory_contexts. An idle session on this server held about 1.4 MB. On Windows each connection is also a separate process, which adds a few megabytes more (an estimate, not measured). A query that sorts or hashes adds up to work_mem per step on top. Even at a pessimistic 20 MB each, 200 connections come to about 4 GB, a small share of a 16 GB server running 4 GB of shared buffers.

Whether Windows allows it. Postgres running as a Windows service can start refusing connections before it reaches max_connections. Each connection’s process takes a slice of a fixed memory area that Windows gives services (the non-interactive desktop heap, the third number of SharedSection in the registry). So the setting is a promise, not a proof. The proof is to open the connections. With the workers stopped, a short script opened idle connections one at a time, up to 190 against the new ceiling of 200, then closed them all. All 190 held, in 14 seconds. A failure at 150 would have shown up in that test, not on a busy night.

The setting is a promise, not a proof. The proof is to open the connections.

The change itself. ALTER SYSTEM SET max_connections = 200 writes the value to postgresql.auto.conf, which overrides postgresql.conf. Until the server restarts, pg_file_settings lists the new value as “setting could not be applied”. On Windows, restart the service from a prompt run as administrator: an ordinary one returns “System error 5” (access denied), even on an administrator account.

Why not a pooler. A pooler, the usual advice, could only help with half the connections. The lock connection holds a session-level advisory lock, and a pooler in transaction mode hands a server connection to another client between transactions, so that connection must stay direct. Pooling the work connections means a new service and code changes, to recover half of what one configuration line gave.

The rule from the top still holds, seen from the other side: size busy work to cores, and size the ceiling to every connection you hold, busy or idle.

The short version

  • max_connections is a ceiling, not a target. It says how many clients may connect before the database refuses them, not how many can do useful work at once.
  • Cores set the real limit. On the four-core box, read-only throughput plateaued by eight clients and read-write throughput peaked at four and then declined; latency climbed roughly a hundredfold past the knee while total work fell.
  • Cap concurrent heavy jobs near the core count, using a small connection-count semaphore, not a bigger max_connections. Leave cheap read-only and network-bound queries uncounted.
  • Spend spare tuning budget on memory, not connections. Against a fixed core count more connections cannot help; a moderate shared_buffers bump can.
  • Raise the ceiling when idle connections fill it. Idle connections cost memory, not cores. Measure what one costs, raise the limit, then prove the new limit by opening that many connections, because Windows can refuse connections before max_connections does.
  • The same counting error shows up well beyond databases: in CI, for one, where more parallel jobs don’t mean faster builds.

Frequently Asked Questions

Does raising max_connections ever help?

Only when you are genuinely being refused (errors saying the connection limit is reached), and even then the right fix is usually a connection pooler in front of the database, not a higher ceiling. Raising it to escape a slowdown (rather than an outright refusal) moves a number that was not the bottleneck and can make things worse, because every allowed connection reserves memory. The clear case for raising it is a ceiling filled by idle connections, especially ones that hold session state such as an advisory lock, which a pooler cannot share (see the section on idle connections above).

Does Postgres on Windows accept fewer connections than max_connections?

It can. Each connection is a separate process, and as a Windows service those processes share a fixed memory area (the non-interactive desktop heap). When that runs out, new connections fail even though the setting allows more. Don’t trust the number: after raising it, open that many idle connections with a short script while the server is quiet, and see whether they all hold.

How many concurrent connections should a small server allow to be efficient?

For CPU-bound work, efficiency peaks around the core count and tops out near twice it; past that, throughput is flat and latency climbs. A common starting point for active connections is two to four times the cores, tuned by measurement, but the useful ceiling is much closer to the core count than to the default max_connections of 100. Measure your own workload; the knee is easy to find with a short sweep.

Is this specific to PostgreSQL?

No. The shape is a property of finite cores and shared locks, not of one database engine. Any CPU-bound, contention-prone workload shows the same knee: throughput flattening near the core count and latency rising past it. The connection-limit-versus-core-count confusion is just especially common with databases because the connection number is so visible.

What about adding more worker processes to finish sooner?

That is the same mistake wearing different clothes. More workers past the core count do not finish sooner; they finish at the same total rate while each takes longer, and a write-heavy job finishes later because of the added contention. Fewer workers, run to completion, is faster than many workers thrashing.

Share post:

Subscribe

Popular

More like this
Related

WooCommerce Search by SKU or ISBN Finds Nothing? It Never Looks There

A shopper types the SKU from your catalog, or the ISBN printed on the back of a book, and gets "No products were found". The product is right there, and the number is on its page. Search simply never reads that part of the product.

Computer Slow but CPU and Memory Look Normal? Check the Handle Count

Chrome takes a minute to open, or doesn't open at all. Every click waits. You open Task Manager expecting to find the culprit, and it tells you everything is fine. Here is the number that isn't, and the fix that takes two minutes.

Kernel-Power 41 Tells You Your PC Restarted, Not Why

Your PC restarts with no blue screen, and the only clue is a critical event saying it didn't shut down cleanly. Here is how to get from that event to a short list of suspects.

Set Up WordPress SMTP Without a Plugin, Even on a Multisite Network

WordPress mail goes out as wordpress@ your domain, from the web server, and lands in spam. An SMTP plugin fixes that. So do about twenty lines of code, and on a network of sites the code can give every site its own mailbox and its own password.