PostgreSQL "FATAL: sorry, too many clients already" in CI
Postgres reached max_connections and refuses any new connection with "sorry, too many clients already". In CI this is usually parallel test workers each opening their own connections plus a few reserved for superusers.
What this error means
Mid-run, new connections fail with "FATAL: sorry, too many clients already" while earlier ones succeeded. It correlates with test parallelism or leaked connections.
FATAL: sorry, too many clients alreadyCommon causes
Parallel test workers exceed max_connections
The default max_connections is 100, minus superuser-reserved slots. Many parallel workers, each with a pool, exhaust it.
Connections are leaked and never closed
Tests that open connections without closing them accumulate until the cap is hit.
How to fix it
Raise max_connections on the container
Pass a command argument to the Postgres image to increase the limit for the test database.
services:
postgres:
image: postgres:16
env: { POSTGRES_PASSWORD: postgres }
options: --health-cmd "pg_isready -U postgres" --health-retries 10
# raise the cap via command
# (set in a compose file or custom image):
# command: postgres -c max_connections=200Reduce concurrency or pool connections
Lower test worker count or share a connection pool so total open connections stay under the cap.
# pytest example: cap workers
pytest -n 4How to prevent it
- Close database connections in test teardown to avoid leaks.
- Size test parallelism against
max_connectionsminus reserved slots. - Use a connection pool with a bounded maximum size.