Skip to content
Latchkey

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.

Terminal
FATAL:  sorry, too many clients already

Common 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.

.github/workflows/ci.yml
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=200

Reduce concurrency or pool connections

Lower test worker count or share a connection pool so total open connections stay under the cap.

Terminal
# pytest example: cap workers
pytest -n 4

How to prevent it

  • Close database connections in test teardown to avoid leaks.
  • Size test parallelism against max_connections minus reserved slots.
  • Use a connection pool with a bounded maximum size.

Frequently asked questions

What causes "Postgres "sorry, too many clients already""?
The default max_connections is 100, minus superuser-reserved slots. Many parallel workers, each with a pool, exhaust it.
How do I fix Postgres "sorry, too many clients already"?
Pass a command argument to the Postgres image to increase the limit for the test database.

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card