← Back to SQL, page 18

sql-0345 · Medium mid

An application starts failing with 'too many connections' under load. What is happening and what would you change?

Each application process opens its own connections until the server's max_connections is reached, and new requests fail. Use a connection pool (in the app and often a server-side pooler such as PgBouncer), cap pool sizes so the total stays below the limit, and look for leaked connections or long transactions holding them.

Full answer

PostgreSQL uses a process per connection, so thousands of connections waste memory and slow the server even before the limit. Raising max_connections is rarely the right fix.

What to change:

  • Pool in the application with a fixed size per instance; total = instances x pool size must fit the server limit with headroom for admin access.
  • Add PgBouncer in transaction mode when there are many app instances or serverless functions; many client connections then share a few server connections. Session features such as prepared statements and advisory locks need care in that mode.
  • Find leaks: connections that are never returned, or sessions left idle in transaction, visible in pg_stat_activity. Set idle_in_transaction_session_timeout.
  • Reduce hold time: shorter transactions free connections faster.

A small pool often gives better throughput than a large one, because the database works best with roughly as many active queries as it has CPU cores and disks to serve them.

Key points

  • Connections are expensive in PostgreSQL
  • Pool in the app and cap totals
  • Use PgBouncer for many clients
  • Find idle-in-transaction leaks
  • Smaller pools often perform better

Common mistakes

  • Raising max_connections to thousands
  • Opening a connection per request without pooling

Follow-ups

  • What breaks under PgBouncer transaction pooling?
  • How would you size a pool?

Tips

  • Explain why raising the limit is a poor fix