The Postgres Connection Pool Math That Nearly Bit Me

The most dangerous problems in my homelab are the ones that have not happened yet. This one was sitting quietly in two connection strings, and it only showed up because I did arithmetic I had never bothered to do: how many database connections could my applications open if they all decided to?

The setup

One of my PostgreSQL servers backs several applications. It is configured with max_connections = 1200, of which roughly 1,197 are usable by normal clients once a few are reserved. When I looked at it on a normal day, there were only about 48 backends connected. Cache hit ratio was excellent, nothing was waiting on locks, no errors in the log. Everything said healthy.

I almost stopped there. I am glad I did not.

What I wrongly assumed

I assumed that “currently connected: 48” meant “not at risk.” That is the same mistake as judging a bridge by looking at today’s traffic. The current number tells you about demand today. It says nothing about the ceiling your configuration permits.

So I read the connection strings of every app that talks to this server. Two of them, a web frontend and a background worker service for the same project, both used Npgsql, the .NET PostgreSQL driver. Each had this in its configuration:

Maximum Pool Size=1800; Minimum Pool Size=80

Each of them was permitted to open up to 1,800 connections. Not 1,800 combined. Each.

The arithmetic

The worst case from just those two services was 3,600 backend connections against 1,197 usable. That is about three times over the server’s limit. They would never both reach their cap through ordinary traffic, but “never” is a strong word for something driven by crawler spikes, retry storms and background jobs that wake up together.

It was dormant for a simple reason: the apps had not warmed up their pools. A connection pool opens connections as concurrency demands them. If concurrency stays low, you never find out what the maximum would have done. A bad cap only reveals itself during exactly the event that makes everything worse, a traffic spike or a slow query that holds connections longer than usual. A slow query is especially nasty, because a pool facing slow responses opens more connections to maintain throughput, which loads the database further, which slows the queries further.

Other clients made things worse in a smaller way. Some Node.js apps used Prisma with no explicit connection limit. Prisma’s default pool size is derived from CPU count, which gave each of them somewhere between 30 and 70 connections depending on the machine it ran on. Nobody chose those numbers. They fell out of a default.

The tempting wrong fix

The obvious reaction to “I could run out of connections” is to raise max_connections. Do not do this without thinking about memory.

Each PostgreSQL connection is a separate backend process. Its memory use depends on what it is doing, and the biggest lever is work_mem, which is the amount each sort or hash operation can use before spilling to disk. On this server work_mem was 19.7 MB. A single sort per backend across 3,600 backends is already about 70 GiB. Queries with several sort or hash nodes can use that amount multiple times over, which pushes the realistic worst case past 230 GiB. That is far more memory than the machine has.

So “just allow more connections” does not fix an overcommitted pool. It converts a connection-limit error, which is a clean and recoverable failure, into an out-of-memory kill of the database server, which is neither.

-- how much headroom do you actually have?
SHOW max_connections;
SHOW superuser_reserved_connections;
SHOW work_mem;

-- who is connected right now, by application and state
SELECT application_name, state, count(*)
FROM pg_stat_activity
GROUP BY 1, 2
ORDER BY 3 DESC;

The fix: cap the clients, not the server

The right place to enforce a limit is where the demand is created. My plan was to cap each pool to a number a human would choose on purpose:

  • web frontend: maximum 150, minimum 10, idle connections released after 60 seconds
  • background worker: maximum 100, minimum 5
  • each Prisma app: an explicit connection_limit of 5

That brings the combined worst case to roughly 380, which is about 32 percent of the usable ceiling. The server could then absorb a bad day without any single service starving the others.

# before
Maximum Pool Size=1800; Minimum Pool Size=80

# after (the values I ended up deploying were 110 per service)
Maximum Pool Size=110; Minimum Pool Size=10; Connection Idle Lifetime=60

Both services now run with pools of 110, comfortably under the limit.

Why caps beat hope

It is easy to think a bigger pool is a faster pool. It is not. A database can only do useful work with a limited number of concurrent queries, bounded by CPU cores and disk. Beyond that, extra connections just queue inside the database instead of queueing in your application, and they cost memory while they wait. A smaller pool pushes the waiting to the application tier, where it is cheap and where you can add timeouts and shed load deliberately.

There is a well-known rule of thumb that the best pool size for a database is a small multiple of its core count, not hundreds or thousands. I did not need to be dogmatic about it. I just needed the sum of all caps to fit under the server’s limit, with room to spare.

A check you can run today

You do not need anything elaborate to keep an eye on this. The one number I now look at is how much of the usable ceiling is in use, expressed as a percentage, because a raw count means nothing without the limit next to it:

SELECT count(*) AS in_use,
       current_setting('max_connections')::int
         - current_setting('superuser_reserved_connections')::int AS usable,
       round(100.0 * count(*) /
         (current_setting('max_connections')::int
          - current_setting('superuser_reserved_connections')::int), 1) AS pct_used
FROM pg_stat_activity
WHERE backend_type = 'client backend';

On a normal day mine read about 4 percent. That is the number that made me comfortable for too long. The point of the exercise is that 4 percent today and a configuration that permits 300 percent are both true at once, and only the second one tells you what a bad day looks like. I keep both numbers on the same page now: current use, and the sum of every pool maximum.

What the change cost

Nothing that I have noticed. That surprised me a little, because every instinct says a smaller pool must be a slower pool. The apps were only using a few dozen connections on normal days, far under the new limits, and the days when they might hit a limit are exactly the days when a hard cap protects the database. If a service genuinely needs more concurrency than its cap allows, it will show up as queueing in the application, with timeouts I can see and tune, rather than as a database-wide connection failure that takes every neighbour down with it.

Things I will do next time

  • Add up the maximums, not the current counts. Maintain a one-line table: service name, maximum pool, sum. Compare the sum to the server’s usable connections every time a service is added.
  • Treat defaults as decisions someone else made. A pool size derived from CPU count is a number nobody reasoned about for your situation.
  • Do not use the server limit as the safety mechanism. It is the last line of defence, and it fails by refusing everyone at once.
  • Do the memory math before touching max_connections. Connections multiplied by work_mem is an optimistic floor, not a ceiling.
  • Dormant is not safe. A limit that has never been hit is a limit you have never tested.

The nicest thing about this class of problem is that the fix is a one-line configuration change, and the diagnosis needs nothing but a calculator and a text editor. It is also the kind of problem you only find if you go looking on a day when everything is green.

By Alex Rivers

I write hands-on guides to web development and programming: JavaScript and React patterns, Python scripting, CSS layout and the developer tools that tie it all together. I like explanations that start with working code and end with knowing why it works. If a post saves you an afternoon of debugging, it did its job.

Leave a Reply