Sphere
Log in Join

Postgres `FATAL: remaining connection slots are reserved` after a deploy — pgbouncer fix

The deploy finished at 09:28 and by 09:31 the API was returning 500s. Nothing in the code review looked risky. The app log had this, repeated several times a second:

psycopg2.OperationalError: FATAL:  remaining connection slots are reserved for non-replication superuser connections

Postgres 15.4 on a 16 vCPU VM, max_connections still at the default 100. Classic, but the cause wasn't what I guessed.

## Counting connections per process

First I checked the basics:

sql
SHOW max_connections;
SELECT count(*) FROM pg_stat_activity;

 max_connections
-----------------
100
count
-------
98

Then grouped them:

sql
SELECT application_name, state, count(*)
FROM pg_stat_activity
GROUP BY 1, 2
ORDER BY 3 DESC;

 application_name | state               | count
------------------+---------------------+-------
api | idle in transaction | 61
api | idle | 22
worker | idle | 12

Most were from api, which only had a pool of 25. That didn't add up until I remembered we run eight API pods now instead of four, and each pod had its own pool. Eight times 25 is 200, well over the server limit. The deploy hadn't leaked anything; it had doubled a number that was already too high.

Before that deploy, four pods at 25 each still fit under 100 with room for the worker and the migration job. That margin was thinner than anyone had written down, and nobody had opened pg_stat_activity since the database was created. We were one modest scale-up away from this either way.

I cleared the stuck ones so we could breathe:

sql
SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE application_name = 'api'
AND state = 'idle in transaction'
AND state_change < now() - interval '5 minutes';

## Putting pgbouncer in front

Raising max_connections to 400 would have made Postgres spawn more backends and eat RAM, so we added pgbouncer 1.21.0 on a small sidecar. The config that matters:

ini
[databases]
app = host=10.0.2.14 port=5432 dbname=app

[pgbouncer]
listen_port = 6432
auth_type = scram-sha-256
pool_mode = transaction
max_client_conn = 1000
default_pool_size = 20

The app now points at port 6432. Eight pods times 20 server connections is 160, but in transaction mode a server connection is returned to the pool after each transaction, so the real number sits around 30 to 40. Check with SHOW POOLS; on the pgbouncer admin DB.

## The part that broke afterward

About an hour later, errors changed to:

psycopg.errors.InvalidSQLStatementName: prepared statement "_pg3_0" does not exist

Transaction pooling and named prepared statements don't mix, because a session can get a different server connection between prepare and execute. With psycopg 3 we set prepare_threshold = None in the connection string. For a JDBC service on the same database we added prepareThreshold=0. If you're on SQLAlchemy, prepare=False in the connect args does the same thing.

Worth knowing before you switch pool_mode, since it looks like a database bug and isn't. Connection counts have been flat for two months now, and SHOW POOLS; is part of our weekly check. I'd still rather have fixed the pool sizes in the app, but pgbouncer gives us room to be a bit sloppy without taking the API down.