Prompt
Why is PostgreSQL connection count such a problem in my app?
Latest observation
PostgreSQL connection count becomes a problem because a database connection is expensive to create and keep open, and PostgreSQL traditionally handles each connection with significant per-connection resources.
Why it hurts
Each active connection can consume:
- Memory: PostgreSQL allocates backend memory per connection.
- CPU / process overhead: each connection is typically its own server process, so lots of connections mean more context switching and scheduling overhead.
- Lock and cache contention: too many clients can make the database spend more time managing sessions than doing useful work.
- Slow startup under load: if your app opens many connections at once, connection setup can become a bottleneck.
- Limited capacity: PostgreSQL has a configurable max connection limit, and once you hit it, new requests wait or fail.
Why apps run into it
This usually happens when:
- you have many app instances (containers, pods, servers),
- each instance has a connection pool,
- the pool size per instance is too large,
- or connections are opened inefficiently per request instead of reused.
Example:
If you run 20 app instances and each keeps 20 DB connections, that’s already 400 connections. That can overwhelm a small or moderately sized Postgres server.
Why pooling matters
Most apps don’t need a separate DB connection for every incoming web request. Instead, they should:
- keep a small pool of reusable connections,
- borrow a connection for a query,
- return it to the pool quickly.
For many workloads, this is much more efficient than opening/closing connections constantly.
Common fixes
- Use connection pooling in the app.
- Reduce pool sizes per instance.
- Avoid long-running transactions that tie up connections.
- Use PgBouncer or another external pooler for high-scale systems.
- Scale the database only after fixing pooling, because more connections often isn’t the right answer.
Rule of thumb
If your app “works fine” at low traffic but falls apart as traffic rises, connection count is often one of the first bottlenecks to check.
If you want, I can also help you figure out whether your issue is:
- too many app instances,
- pool sizes too large, or
- connections leaking / not being closed.
Brands