database resource_error ai_generated true

psycopg2.OperationalError: FATAL: too many connections for role "myuser"

ID: database/too-many-connections

Also available as: JSON · Markdown
90%Fix Rate
92%Confidence
68Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
16 active

Root Cause

All available PostgreSQL connection slots are occupied. Default max_connections is 100. Caused by connection leaks in application code, missing connection pooling, or too many application instances.

generic

Workarounds

  1. 94% success Deploy a connection pooler like PgBouncer in front of PostgreSQL
    Install PgBouncer, configure it to proxy connections to PostgreSQL with pool_mode=transaction and a reasonable pool_size (e.g., 20-50). Point application connection strings to PgBouncer instead of PostgreSQL directly.
  2. 88% success Fix connection leaks in application code by ensuring connections are properly closed
    Audit code for connections that are opened but not closed. Use context managers (Python 'with' blocks), try/finally, or connection pool libraries (SQLAlchemy pool, HikariCP). Monitor with: SELECT count(*) FROM pg_stat_activity;

Dead Ends

Common approaches that don't work:

  1. Setting max_connections to an extremely high value (e.g., 10000) without connection pooling 85% fail

    Each PostgreSQL connection consumes significant memory (~10MB). Setting max_connections very high without adequate RAM causes OOM kills or severe performance degradation from context switching.

  2. Restarting PostgreSQL repeatedly as a fix for connection exhaustion 80% fail

    Restarting forcibly disconnects all clients, causing data loss in active transactions. Without fixing the leak or adding pooling, connections will be exhausted again shortly after restart.

Error Chain

Leads to:
Preceded by:
Frequently confused with: