Connection Pooling: Why Your App Runs Out of Database Connections

2026-12-03来源 dev.toEnglish

Everything works in development. Then traffic grows, or you scale the API from two instances to twenty, and the logs fill with errors like FATAL: sorry, too many clients already or remaining connection slots are reserved. Requests hang, then time out. The database CPU is fine. The problem is not the queries. It is the connections.

This article explains why database connections are a scarce resource, how a connection pool works, and how to size one so your app stops running out.

Why a connection is expensive

A database connection is not just a socket. Opening one usually means:

  1. A TCP handshake, and a TLS handshake if the connection is encrypted.
  2. Authentication (for example a SCRAM password exchange in PostgreSQL).
  3. The server setting up a session: memory, settings, state.

In PostgreSQL, each connection is served by its own backend process on the server. Every process uses memory, and the server has a hard limit set by max_connections. MySQL uses a thread per connection, with its own max_connections limit. Either way, connections cost memory and CPU on the database even when they sit idle, and there is a ceiling.

So two problems appear when an app opens a fresh connection for every request:

  • Latency. The handshake and authentication can take longer than the query itself, especially across a network with TLS.
  • Exhaustion. Under load, the number of open connections grows with the number of concurrent requests, until the server refuses new ones.

What a connection pool does

A connection pool keeps a set of open connections and lends them out. The flow looks like this:

  1. At startup (or lazily), the pool opens some connections and keeps them.
  2. When code needs the database, it borrows a connection from the pool.
  3. It runs its queries.
  4. It returns the connection. The pool resets it if needed and keeps it open for the next borrower.
  5. If all connections are busy, the next borrower waits in a queue, up to a timeout.

The handshake cost is paid once per connection instead of once per request, and the total number of connections is capped by the pool size, no matter how many requests arrive.

Here is a minimal example with Python and psycopg_pool:

from psycopg_pool import ConnectionPool pool = ConnectionPool("postgresql://app@db/app", min_size=2, max_size=10) def get_user(user_id): with pool.connection() as conn: # borrow return conn.execute( "SELECT id, name FROM users WHERE id = %s", (user_id,) ).fetchone() # returned when the block ends 

Most stacks have the same thing built in: HikariCP in Java, the pool inside SQLAlchemy, pg.Pool in Node.js, database/sql in Go, and connection handling in frameworks like Django (CONN_MAX_AGE) or Rails.

The math that bites: pools multiply

Here is the most common way teams run out of connections even with a pool. A pool lives inside each process. The total load on the database is:

instances x processes per instance x pool max size

Example: 20 API containers, each running 4 worker processes, each with a pool of 10. That is up to 800 connections. Add background workers, a cron job, and a migration running at deploy time, and you blow past a max_connections of a few hundred without any single pool looking large.

Autoscaling makes this worse: the moment traffic spikes, new instances start, and each brings its own full pool.

A bigger pool is not faster

When requests wait for a connection, the instinct is to raise the pool size. Often that makes things worse. A database server has a limited number of CPU cores and limited disk I/O. Past a point, more concurrent queries do not run faster. They compete for the same cores, locks and buffers, and each one takes longer.

A small pool with a short queue in front of it usually gives better throughput and more stable latency than a huge pool. A common starting point is a pool size in the order of the database's CPU core count (times a small factor), measured from there, rather than one connection per expected concurrent user.

External poolers: PgBouncer and friends

When many app processes need to share one database, a pool inside each process is not enough. An external pooler sits between the app and the database. PgBouncer is the classic one for PostgreSQL. Others include Pgpool-II, the Supavisor and PgCat projects, managed options such as Amazon RDS Proxy, and ProxySQL for MySQL.

The app opens many cheap connections to the pooler. The pooler keeps a small number of real connections to the database and multiplexes clients onto them. PgBouncer has three modes:

  • Session pooling: a client keeps a server connection for its whole session. Safe, but saves the least.
  • Transaction pooling: a client gets a server connection only for the duration of a transaction. Saves the most, and is the common choice.
  • Statement pooling: per statement. Multi-statement transactions are not allowed.

Transaction pooling has a catch: anything that depends on session state may break, because the next transaction can run on a different server connection. Session-level SET commands, advisory locks held across transactions, LISTEN, and server-side prepared statements are the usual suspects. Recent PgBouncer versions added support for protocol-level prepared statements, but check your version and driver settings before relying on it.

Common mistakes

Leaking connections. Code borrows a connection and never returns it, often on an error path. The pool slowly drains until every request waits. Always use with, try/finally, or your framework's request scope.

Holding a connection during slow work. Calling an external API or sending an email while holding a connection (or worse, an open transaction) keeps it out of the pool for seconds. Do the slow work first, then borrow.

Idle in transaction. A transaction that is opened and never committed holds locks and a connection. In PostgreSQL, idle_in_transaction_session_timeout can end such sessions automatically.

No timeouts. Set a timeout for borrowing from the pool, and a statement timeout on the database. A clear error after a few seconds is better than requests piling up forever.

Ignoring serverless. Each function instance may open its own connection, and there can be hundreds of instances. Serverless apps almost always need an external pooler or a data API.

Not watching the numbers. Track pool wait time, active versus idle connections, and on PostgreSQL look at pg_stat_activity to see who holds connections and what state they are in.

In short

  • Database connections are expensive to open and limited in number on the server.
  • A pool reuses a fixed set of connections and makes extra requests wait instead of opening more.
  • Total connections are instances x processes x pool size. Do that math before you scale out.
  • Bigger pools are not faster. Size for the database's capacity and measure.
  • With many app processes, put an external pooler such as PgBouncer in front, and know what transaction pooling breaks.
  • Return connections promptly, set timeouts, and monitor.

Watch the animated version: https://youtu.be/mw6rL5D_hkI

Originally published at abdeldjalilchougui.biz.

原文:https://www.a8q9.cn/en/article/connection-pooling-why-your-app-runs-out-of-database-connections-13d5fe.html

相关文章