Summary
Connection pooling is the most misconfigured part of database performance. Most teams assume a bigger pool means a faster system. The reality is the opposite: an oversized pool slows the database down. Every connection consumes memory, forces context switching, and increases lock contention. In this guide you will learn how to calculate the correct pool size, how to use application pools together with external poolers like PgBouncer / ProxySQL, how to diagnose a full pool, and how to choose safe production values.
Scenario
There is a system. 8 application servers, each opens a 50-connection pool. Total 400 connections. Database server: 8 CPUs, 32 GB RAM. The system is slow. The team increases the pool from 50 to 100. Total connections become 800. The system gets even slower. The team scales up the server. Still slow. Then a DBA looks and sees the truth: the number of connections actively doing work never exceeds 20. 780 of 800 connections are idle. But those 780 idle connections are still load the database must check every second, allocate memory for, and scan in the lock table. The problem is not a small pool. It is a large pool. This guide shows how to find the correct pool size.
Concept: Why Does a Connection Pool Exist?
Opening a new connection for every database request is expensive. A TCP connection is established, authentication happens, session settings are loaded, then the query runs. This process can take longer than the query itself. A connection pool opens connections in advance and reuses them. So every request does not pay the connection cost.
But a pool has a cost. Every open connection:
- •Consumes memory. In PostgreSQL, 5 to 10 MB per connection on average.
- •Consumes CPU. The database must regularly check open connections.
- •Grows the lock table. Every connection is a row in the lock table.
- •Causes context switching. The OS must switch between 800 connections.
So a pool is neither better when smaller nor better when larger. The correct size is the number of connections actively doing work.
Formula: How to Calculate the Correct Pool Size?
The classic formula, suggested by the creator of PostgreSQL and used in production for years, is:
Pool Size = ((Number of Cores * 2) + Number of Effective Disks)Example for 8 cores, 1 effective disk:
(8 * 2) + 1 = 17This number sounds very small. Most teams expect 100. But the logic is this: one CPU core does 1 job at a time. 8 cores run at most 8 active queries at once. The 2x factor is so another query can run while one waits for disk. Disk count is for I/O parallelism. Connections beyond this do not work actively, they wait in a queue.
▸Adapting the Formula to Real Life
The formula is a starting point for one database server and one application. Real life needs 3 corrections.
Correction 1: If there are multiple applications, split the total.
If the total pool is 17 and you have 4 application servers, it does not mean 17 per server. It means 17 total. So about 4 per server. This looks very small. That is why an external pooler is needed. See the PgBouncer section.
Correction 2: Keep reporting and maintenance connections separate.
Reporting queries are long. Maintenance operations are long. If you put them in the main pool, short web requests queue up. Use a separate user, separate pool, and separate connection limit for reporting.
Correction 3: If transactions are long, the formula becomes meaningless.
If transactions stay open for 5 seconds, 17 connections are not enough. Because connections are not working, they are waiting. First shorten transactions. As you saw in the N+1 article, first reduce query count, then calculate the pool.
▸Practical Starting Table
| Server | Cores | Total Pool (Starting Point) | Per App Server (4 servers) |
|---|---|---|---|
| Small | 4 CPU | 9 | 2 - 3 |
| Medium | 8 CPU | 17 | 4 - 5 |
| Large | 16 CPU | 33 | 8 |
| Very large | 32 CPU | 65 | 16 |
This table is for the application pool. If you use an external pooler, numbers change. See the next section.
Application Pool vs External Pooler
A two-layer pool architecture is the correct architecture in production.
▸Layer 1: Application Pool (HikariCP, SQLAlchemy Pool, Go database/sql)
Each application server has a small pool. Example with HikariCP in Java:
# HikariCP example
maximumPoolSize=10
minimumIdle=2
connectionTimeout=10000
idleTimeout=600000
maxLifetime=1800000Important settings:
- •
maximumPoolSize: This is per server, not total. 8 servers x 10 = 80 total connections. - •
connectionTimeout: If no idle connection exists in the pool, how long should a request wait? 10 seconds is ideal. Infinite waiting leads to system lockup. - •
maxLifetime: How long should a connection live? 30 minutes is ideal. Connections that live forever carry memory leaks and old plans.
▸Layer 2: External Pooler (PgBouncer, ProxySQL, RDS Proxy)
As the number of application servers grows, total connections explode. 20 servers, each with 10 connections, means 200 total connections. The database cannot manage 200 connections efficiently. At this point an external pooler enters.
PgBouncer sits between the application and the database. It looks like 200 connections to the application. But it opens only 20 real connections to the database. While an application connection is idle, the real database connection is given to another application.
Application (200 connections) -> PgBouncer -> Database (20 real connections)Without this architecture, as microservices grow, the database collapses.
PgBouncer Modes — Which One Should You Choose?
PgBouncer works in three modes. Choosing the wrong mode removes the benefit of pooling.
▸Session Mode
The connection is reserved for the whole client session. The safest but least efficient mode. Until the application closes the connection, the real connection is not given to anyone else. If your application keeps connections open for a long time, this mode removes the pool benefit.
▸Transaction Mode — Most Common and Recommended
The connection is reserved only for the transaction duration. When the transaction ends, the connection returns to the pool. Another client can use it. If there is no N+1 and long-transaction problem, this mode is the most efficient.
Most production systems use this mode.
# pgbouncer.ini
pool_mode = transaction
max_client_conn = 1000
default_pool_size = 20
min_pool_size = 5
reserve_pool_size = 5In this example, 1000 client connections are served by 20 real database connections.
▸Statement Mode
The connection is reserved for a single query. The most efficient but most restricted mode. Prepared statements, temporary tables, and SET commands do not work. It is used only in very special cases.
Practical advice: Use transaction mode by default. Switch to session mode only if prepared statements and temporary tables make it mandatory.
MySQL Side: ProxySQL and Application Pool
In MySQL the logic is the same but the tool is different. Instead of PgBouncer, ProxySQL is used.
ProxySQL pools MySQL connections and separates read and write traffic. Write traffic goes to the primary, read traffic goes to replicas. So pool pressure decreases.
-- Pool status in ProxySQL
SELECT hostgroup, srv_host, ConnUsed, ConnFree, ConnOK, ConnERR
FROM stats.stats_mysql_connection_pool;If ConnUsed is constantly at maximum and ConnERR is increasing, the pool is full. First reduce query count, then grow the pool.
In MySQL the same formula applies for the application side. For HikariCP, SQLAlchemy, Go database/sql pools, the starting value is cores * 2 + disks.
Diagnosis: Is the Pool Full, or Is It Another Problem?
Pool-full symptoms are confused with lock and N+1 symptoms. For correct diagnosis, check 3 places.
▸1. Active Connection Count on the Database Side
PostgreSQL:
SELECT state, count(*) AS cnt
FROM pg_stat_activity
GROUP BY state
ORDER BY cnt DESC;If active count is low but the application gets timeouts, the problem is not in the database, it is in the application pool. The application pool is full, the request never reaches the database.
If active count is high and idle in transaction count is high, the problem is transactions. Pool is not the problem, transaction design is.
▸2. Pool Metrics on the Application Side
Check HikariCP metrics:
- •
activeConnections: Connections currently in use - •
idleConnections: Idle connections - •
threadsAwaitingConnection: Threads waiting for a connection
If threadsAwaitingConnection is constantly above 0, the pool is full. But do not grow the pool immediately. First check why activeConnections stay full for a long time. Usually there is a long transaction or N+1.
▸3. Wait Time
-- PostgreSQL: Longest waiting queries
SELECT pid, now() - query_start AS wait_time, state, wait_event, left(query, 120)
FROM pg_stat_activity
WHERE state <> 'idle'
ORDER BY query_start
LIMIT 20;If wait time is longer than 10 seconds and wait_event is empty, the query is waiting in the application pool, not in the database. It does not appear in database logs. Because it never reached the database.
Step-by-Step Pool Tuning
▸Step 1: Measure Current State
For 1 week, collect these 3 metrics:
- •Highest active connection count
- •Highest waiting thread count
- •Average query time
If highest active connections is 15, waiting threads are 0, a pool of 50 is unnecessary. 20 is enough.
▸Step 2: Shrink the Pool — Yes, Shrink
In most systems the first step is not to grow the pool, but to shrink it. Drop the pool from 100 to 20, monitor for 24 hours. Usually the system gets faster. Because the database does less context switching and fewer lock checks.
▸Step 3: Add an External Pooler
If application server count exceeds 5, add PgBouncer or ProxySQL. Keep the application pool small, run the external pooler in transaction mode.
▸Step 4: Set Timeouts
There must be no infinite waiting in the pool.
On the PostgreSQL side:
ALTER SYSTEM SET statement_timeout = '30s';
ALTER SYSTEM SET lock_timeout = '10s';
SELECT pg_reload_conf();On the application side:
connectionTimeout=10000
validationTimeout=5000These settings prevent one query from waiting forever in the pool. A request that errors and returns is better than a locked system.
▸Step 5: Measure Again
24 hours after the change, measure the same 3 metrics again. Success criteria:
- •Waiting thread count dropped to 0?
- •Average query time dropped?
- •Active connection count approached the formula?
- •Application timeout count dropped?
If you cannot say yes to these questions, the problem is not the pool, it is query or transaction design. Do not grow the pool further.
7 Common Mistakes
First mistake: Growing the pool and thinking the problem is solved. Growing the pool hides N+1 and long-transaction problems. The root cause stays.
Second mistake: Giving the same large pool to every application server. 10 servers x 50 connections = 500 total connections. Do not set per-server pool without calculating the total.
Third mistake: Putting reporting and web traffic in the same pool. A long reporting query queues short web requests. Separate pools.
Fourth mistake: Not setting maxLifetime and idleTimeout. Connections that live forever carry old plans and memory leaks.
Fifth mistake: Not monitoring pool metrics. Understanding that the pool is full only when users complain is too late. Set an alarm for threadsAwaitingConnection.
Sixth mistake: Running PgBouncer in session mode and expecting benefit. Session mode holds the connection for the whole session. Without transaction mode, the pooler does not help.
Seventh mistake: Not setting timeouts. In a system without timeouts, one bad query can lock the whole pool.
Checklist
- Total core count and disk count noted
- Starting pool size calculated with the formula
- Total connections calculated with application server count
- Reporting and web pools separated
- Application pool metrics are monitored
- Alarm set for
threadsAwaitingConnection - Pool tested by shrinking first
- Need for external pooler (PgBouncer / ProxySQL) evaluated
- PgBouncer runs in transaction mode
connectionTimeoutandstatement_timeoutset- Baseline measurement taken before change
- Measurement repeated 24 hours after change
- Waiting thread count confirmed to be 0
Conclusion
The correct pool size is not a large pool, it is the right pool. The formula gives you the starting point, measurement gives you the truth. First shorten transactions, fix N+1, then calculate the pool. If you break this order, the pool becomes the problem itself, not the solution.
Next cluster: Partitioning Blueprint.
Related Articles
- •Pillar: Performance Guide — Performance & Query Optimization
- •Cluster: [Universal] N+1 Query Problem and Connection Pool Relationship
- •Cluster: [PostgreSQL] Memory Tuning — shared_buffers, work_mem, effective_cache_size
- •Cluster: [PostgreSQL] Lock Diagnosis — pg_locks + pg_stat_activity in 5 Minutes
- •Next: [Universal] Partitioning Blueprint — When to Split, When Not to Split