Connection pooling: what it is, how to size a pool, and the pitfalls
Reuse a small set of open database connections, instead of opening one per request.
By devskills editorial team · Last updated
What problem does connection pooling solve?
A connection pool is a set of database connections that your application opens once and keeps open. When a request needs the database it borrows a connection from the pool, runs its queries, and hands the connection back for the next request. Nobody opens or closes a connection on the hot path.
Opening a database connection is expensive. There is a TCP handshake, TLS, a login, and on PostgreSQL a whole new server process per connection. Doing that for every request can take longer than the query itself.
Worse, databases have a hard limit on how many connections they allow at once (max_connections is 100 by default on PostgreSQL). Go past it and new connections are refused, which looks like a total outage even though the database is barely doing any work.
What connection pooling costs you
When to reach for connection pooling, and when not to
Use it when
- Always, for any service that talks to a relational database. This is a default, not a decision.
- Especially when your application servers scale up and down. Each new server multiplies your connection count.
Do not, when
- Serverless functions that scale to hundreds of instances, each with its own pool. There you need a separate pooler sitting between them and the database, or you will hit the limit quickly.
How connection pooling actually works
Sizing is the part worth knowing. Your instinct says a big pool. The right answer is usually a small one. A database with 8 cores cannot truly do more than a couple of dozen things at once. So 500 connections do not run side by side. They queue inside the database, where you cannot see them, and every query gets slower together. A common starting point is a few times the core count. Then measure.
The failure has a recognisable shape. Response times climb on every endpoint at once. Database CPU is not high. Errors say "timed out waiting for connection". That is pool exhaustion. The usual cause is slow queries holding connections, rather than too much traffic. One endpoint running a 10-second report can starve the whole service.
Set a timeout on getting a connection. Waiting forever turns a slow dependency into an endless pile of stuck requests. Failing fast lets you drop traffic and stay up.
For serverless, or for a very large number of instances, put a dedicated pooler in front. In transaction mode it lends a real connection to a request only for the length of one transaction, so hundreds of clients share a handful of connections. The cost is that anything spanning transactions breaks, including session-level settings and some prepared-statement behaviour.
Sizing with arithmetic, not instinct. A connection is busy only while a query or transaction runs, so the number you need is throughput times hold time (Little's law). 2,000 queries a second that each hold a connection for 5 ms keep about 10 connections busy on average. Add headroom for bursts and you get a pool in the low tens, not hundreds. The HikariCP project's well-known starting formula points the same way: connections = (cores × 2) + effective spindle count, so about 17 for an 8-core server on SSD. Treat either number as a starting point and load test.
Budget across the fleet. The figure that matters to the database is the total: pool size × instances, plus migrations, cron jobs, admin consoles and replicas of your workers. Keep that total below max_connections with room for superuser and maintenance connections. If autoscaling can double your instances, the budget must survive the doubled count.
Two layers of pooling. Most stacks have an in-process pool (HikariCP in Java, database/sql in Go, the pool inside node-postgres or SQLAlchemy). It removes the connect cost and caps one process. An external pooler such as pgbouncer, RDS Proxy or Supavisor sits between many processes and the database and caps the whole fleet. Small services need only the first; serverless and large fleets need both.
Pitfalls that show up in production: connections leaked because a result set or transaction was never closed; a transaction left open while the code calls another service; connections silently killed by a firewall or load balancer idle timeout, so the first query after a quiet period fails (set a max lifetime shorter than that timeout); session state such as SET search_path or temporary tables leaking to the next borrower; and prepared statements or advisory locks breaking under transaction-mode pooling.
db, err := sql.Open("pgx", dsn) // *sql.DB is a pool, not one connectionif err != nil { return err}db.SetMaxOpenConns(20) // default 0 means unlimited: always set itdb.SetMaxIdleConns(20) // default is 2, which causes connection churndb.SetConnMaxLifetime(30 * time.Minute) // recycle before any idle timeout in betweendb.SetConnMaxIdleTime(5 * time.Minute)// database/sql has no "wait for a connection" timeout of its own:// the context deadline covers both waiting for a connection and the query.ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)defer cancel()rows, err := db.QueryContext(ctx, "SELECT id, name FROM users WHERE team_id = $1", teamID)if err != nil { return err}defer rows.Close() // forgetting this leaks the connectionspring.datasource.hikari.maximum-pool-size=20 # default 10spring.datasource.hikari.minimum-idle=20 # fixed-size pool, as HikariCP recommendsspring.datasource.hikari.connection-timeout=2000 # ms to wait for a connection; default 30000spring.datasource.hikari.max-lifetime=1800000 # 30 min; keep below any network idle timeoutspring.datasource.hikari.leak-detection-threshold=10000 # log connections held over 10 s[databases]app = host=10.0.0.5 port=5432 dbname=app[pgbouncer]listen_port = 6432pool_mode = transaction ; lend a server connection per transactionmax_client_conn = 2000 ; app-side connections pgbouncer will acceptdefault_pool_size = 20 ; real server connections per database/user pairmax_prepared_statements = 100 ; 1.21+: protocol-level prepared statements in transaction mode- Fixing timeouts by making the pool bigger. That usually moves the queue into the database and makes it worse.
- Holding a database connection while calling an external API. Never do work you do not control while holding something scarce.
- Forgetting that pool size multiplies by the number of application instances.
The follow-up an interviewer will ask about connection pooling
"You added more application servers and the database got slower. Why?"
Because each new server brought its own pool. Total connections went up, while the database's ability to do work at the same time stayed the same. Past a point, more connections means more fighting inside the database: context switching, waiting on locks, memory per connection. So everything slows down together. Adding capacity made things worse, which is why it is a good interview question. The fix is a pooler in front, so the database sees a fixed small number of connections no matter how many app servers exist, and the waiting happens somewhere you can see and control. The cost: the pooler is another hop and another thing to run, and transaction-mode pooling quietly breaks session-scoped features.
Connection pooling: common questions
What is connection pooling?
Keeping a set of open database connections and lending them to requests, instead of opening and closing a connection for each request. It removes the connect cost (TCP, TLS, authentication, and on PostgreSQL a new backend process) and caps how many connections the database has to handle.
How big should a database connection pool be?
Smaller than most people expect. Start from throughput × average time a connection is held, add headroom, and sanity-check against the HikariCP rule of thumb of (cores × 2) + spindles on the database server. Then multiply by the number of application instances and make sure the total fits under the database's max_connections. Load test and watch pool wait time, not just CPU.
What is the difference between session, transaction and statement pooling in pgbouncer?
In session mode a client keeps one server connection until it disconnects, which is safe but saves little. In transaction mode it holds a server connection only for one transaction, which lets thousands of clients share a few connections but breaks session-level features such as SET, LISTEN and session advisory locks. Statement mode returns the connection after every statement and forbids multi-statement transactions.
Is Go's sql.DB a connection pool?
Yes. *sql.DB manages a pool and is safe for concurrent use, so open it once and share it. Set SetMaxOpenConns, because the default is unlimited, and raise SetMaxIdleConns above its default of 2. See Postgres and SQL in Go.
Do I still need pgbouncer if my application already has a pool?
For a few long-lived servers, usually not: the in-process pools are enough if their total fits the database. You need an external pooler when instance count is large or unpredictable, as with serverless functions or aggressive autoscaling, because every instance brings its own pool.
How do I tell that the pool is the bottleneck?
Latency rises on every endpoint at once, errors mention timeouts acquiring a connection, and the database itself is not busy. Pool metrics confirm it: active connections pinned at the maximum and a growing wait count. HikariCP exposes these as metrics; Go exposes them through db.Stats().
Your turn
Your service times out under load, but database CPU is only 30%. What is the most likely cause?
Learn it from the source
- PostgreSQL — Connection Settings ↗What max_connections costs on the server side, which is the reason pooling exists.
- HikariCP — About Pool Sizing ↗The argument for small pools, with the cores × 2 + spindles starting formula.
- PgBouncer — Configuration ↗pool_mode, default_pool_size, max_client_conn and the features each pool mode breaks.
- Go — Managing connections (database/sql) ↗What SetMaxOpenConns, SetMaxIdleConns and the lifetime settings actually do.
Related concepts
All concepts on one page: system design cheat sheet