Skip to main content

Fine at 50 Users, Down at 500: Database Connection Pooling Explained

Updated 6 min readMarkdown

Our app worked perfectly in testing. Fifty people used it during the pilot. Pages loaded in under 200 ms. Everyone was happy.

Then marketing sent an email to the full customer list. Around 500 people opened the app within ten minutes.

The app fell over. Users saw "500 Internal Server Error" and spinning loaders. The logs were full of one line:

FATAL: sorry, too many clients already

The database CPU was at 15%. Memory was fine. Queries were fast. The database was not overloaded with work. It was overloaded with connections.

This post explains what happened, how connection pooling fixed it, and how to answer this in an interview.

What actually happened

The app was a set of web servers running behind a load balancer. Each request did roughly this:

  1. Open a new connection to PostgreSQL.
  2. Run two or three quick queries.
  3. Close the connection.

At 50 users, that is fine. At 500 users, it breaks in three ways.

1. Opening a connection is expensive. A new PostgreSQL connection means a TCP handshake, often a TLS handshake, authentication, and the database starting a new backend process for that connection. That can take 20–50 ms, sometimes more. Our queries took 2 ms. We were spending ten times longer saying hello than doing the work.

2. The database has a hard limit. PostgreSQL has max_connections, which was 100 on our managed instance. Every connection also uses memory on the database server. When request 101 tried to connect, it got "too many clients already".

3. Autoscaling made it worse. When errors went up, latency went up, and the autoscaler added more web servers. More servers meant more connection attempts. We scaled the part that was not the problem and pushed harder on the part that was.

What connection pooling means

A connection pool keeps a small set of database connections open and reuses them.

Instead of "open, query, close" on every request, the app does:

  1. Borrow a connection from the pool.
  2. Run the queries.
  3. Give the connection back.

The connection stays open, already authenticated, ready for the next request. No handshake. No new database process. If all connections are busy, the request waits briefly in a queue instead of hammering the database with new connection attempts.

The surprising part: a small pool is usually faster than a big one. A database server only has so many CPU cores and disks. Ten busy connections doing real work often finish more requests per second than 200 connections fighting over the same resources.

How we fixed it

Step 1: Use the pool in the app

Most frameworks have a pool built in; we just were not using it properly. In Python with SQLAlchemy:

from sqlalchemy import create_engine

engine = create_engine(
    "postgresql+psycopg://app:***@db.internal/shop",
    pool_size=10,        # connections kept open per app process
    max_overflow=5,      # short bursts above pool_size
    pool_timeout=3,      # wait max 3s for a free connection, then fail fast
    pool_recycle=1800,   # replace connections every 30 min
    pool_pre_ping=True,  # check a connection is alive before using it
)

In Java, HikariCP does the same job with maximumPoolSize, connectionTimeout and maxLifetime.

Step 2: Do the maths across all servers

This is the step most people miss. The pool size is per process, not per application.

total connections = web servers x processes per server x (pool_size + max_overflow)

We had 8 servers, 4 worker processes each, pool of 15. That is 8 x 4 x 15 = 480 possible connections against a limit of 100. Even with pooling, a scale-out would break us again.

We reduced it to pool_size 5 and max_overflow 2, and capped the autoscaler, keeping total possible connections safely under the limit with room for admin tools and migrations.

Step 3: Add PgBouncer in front of the database

For many app servers, serverless functions or Kubernetes pods that scale up and down, a pool inside each process is not enough. We added PgBouncer, a lightweight proxy that sits between the app and PostgreSQL.

[pgbouncer]
pool_mode = transaction
max_client_conn = 2000
default_pool_size = 40

Now 2,000 app connections can share 40 real database connections. In transaction mode, a real connection is only held for the duration of one transaction. (One catch: session-level features like some prepared statements, SET and advisory locks need care in transaction mode.)

On AWS, RDS Proxy does a similar job and is very useful with Lambda, where every function instance would otherwise open its own connection. On GCP, Cloud SQL works with PgBouncer or the language connectors.

Step 4: Monitor the pool, not just the database

We added three alerts:

  • Pool wait time: how long requests wait to get a connection. Rising wait time is the earliest warning.
  • Active vs idle connections on the database (pg_stat_activity).
  • Connections close to max_connections (alert at 80%).
SELECT state, count(*)
FROM pg_stat_activity
GROUP BY state;

A lot of connections stuck in idle in transaction usually means code that opened a transaction and forgot to commit, or is doing slow work (like calling another API) while holding a connection.

Common mistakes I still see

  • Raising max_connections to 1000 as the fix. Each connection costs memory; you just move the crash.
  • Setting a huge pool size "to be safe". It makes the database slower under load.
  • No pool timeout. Requests wait forever for a connection and threads pile up, the same cascading failure as a slow dependency.
  • Holding a connection during slow work, like an HTTP call or file upload inside a transaction.
  • Forgetting that every new pod brings its own pool when Kubernetes HPA scales out.

The interview angle

A common question: "Your app works fine with a few users, but at a few hundred users the database starts refusing connections even though CPU is low. What is going on and how do you fix it?"

A weak answer: "Scale up the database."

A strong answer covers:

  1. Diagnosis: connection exhaustion, not query load. Check pg_stat_activity, connection count vs max_connections, and connection errors in the logs.
  2. App-level pooling with sensible pool size and timeouts.
  3. The multiplication problem: servers x processes x pool size, and how autoscaling changes it.
  4. A pooler like PgBouncer or RDS Proxy for many clients or serverless.
  5. Monitoring pool wait time and idle-in-transaction connections.

Bonus points if you mention that a smaller pool can give higher throughput.

The lesson

In 14+ years of running production systems, I have seen this pattern many times: the database is not slow, it is just being asked to say hello too many times. Before you buy a bigger database, count your connections.


Let's connect: Free 15-min Cloud & DevOps Interview Guidance Call 👆 link in bio (topmate.io/cloudtechbydevang)

About the author

  • I help engineers learn cloud, DevOps, SRE and AI in simple English, crack interviews and follow clear roadmaps. 14+ years building and running platforms on AWS, GCP, Kubernetes and Terraform. One topic a day.

No comments yet. Be the first to comment.