Home›Operate›Connection pooling
Course · ScaleLesson 15 of 330 read
Decision 8 · Connection management and pooling

How many connections does a database actually need?

Fewer than you think. So where do all the extra ones come from, and what holds them?

Most "too many connections" incidents are not a database that is too small. They are many application instances each opening a generous pool, multiplied together. This page shows the arithmetic, what each engine pays per connection, and where a pooler fits.

The decision

Small pools, sized from the work, with a pooler in front when the client count is large

A connection only does work while a query runs. If queries take 5 ms and you run 2,000 a second, then on average 2,000 × 0.005 = 10 connections are busy at any moment. That is Little's law, and it is the starting point for every pool size. Add headroom for bursts and slow moments, and a pool of 20 to 40 is usually plenty for that load.

The trouble is multiplication: 60 application instances with a pool of 50 each is 3,000 possible connections, most of them idle. So I size pools from the work, cap the total per service, and put a pooler (PgBouncer, ProxySQL, RDS Proxy) between the clients and the database when there are many clients, short-lived ones such as serverless functions, or frequent deploys.

In one line. Busy connections = queries per second × seconds per query. Size pools from that, not from the server's limit.

What a connection costs

Why the engines differ

PostgreSQLMySQLMongoDB
ModelA separate operating system process per connectionA thread per connection (a thread pool in Percona Server, MariaDB and MySQL Enterprise)A thread per connection on mongod; drivers keep their own pools
Default limitmax_connections = 100max_connections = 151Set by the operating system's file and process limits; drivers default to maxPoolSize 100 per host
Per-connection memorySeveral MB at rest, more while sorting: work_mem is per sort or hash, not per connectionPer-thread buffers (sort, join, read) on top of a small baseAround 1 MB each on the server
When there are thousandsMemory, process scheduling and snapshot work grow; 14 made idle connections much cheaper, but a pooler still helpsThreads compete for CPU; Threads_running is what mattersUsually fine on mongod; mongos also pools to each shard
Where a pooler fits

And what it changes

PoolerEngineNotes
PgBouncerPostgreSQLSession mode keeps one server connection per client. Transaction mode shares server connections between transactions, which is where the savings are, and breaks anything that relies on session state: SET without LOCAL, session advisory locks, LISTEN, temporary tables. Protocol-level prepared statements work in transaction mode since 1.21 with max_prepared_statements.
ProxySQLMySQLMultiplexes client connections onto fewer server connections, routes reads to replicas, and can rewrite or block queries. It stops multiplexing for a connection that uses session state, such as user variables or temporary tables.
RDS ProxyPostgreSQL, MySQL on AWSManaged pooling that also shortens failover for clients. Session state "pins" a client to one connection, and pinning removes the benefit.
The driver's poolAll, and the only one for MongoDBEvery application has one. Its size times the number of instances is what the database sees.
The arithmetic

From traffic to pool size

The numbers on this page are arithmetic from the assumptions written next to them, not measurements. Put in your own sizes and speeds, and measure with your own traffic before you trust any of them.

StepAssumptionResult
Busy connections at average load3,000 queries a second at 4 ms each12
At peak, with slower queries6,000 a second at 8 ms each48
Spread over instances24 application instances2 busy each at peak
Pool per instancebusy at peak × 2, at least 55 each, 120 in total
What most teams configurethe framework default of 20 to 50 per instance480 to 1,200, mostly idle

HikariCP's guide offers another starting point: about twice the database's CPU cores plus the number of disks. Both point the same way: tens of busy connections, not thousands.

What breaks

The incidents I would plan for

What happensWhyWhat I do
"Too many connections" after a deployOld and new instances overlap, each with a full poolCap the total per service; a pooler in front; smaller pools.
Pool timeouts while the database is quietConnections held idle in a transaction while the app calls another serviceDo the outside call before or after the transaction. idle_in_transaction_session_timeout in PostgreSQL.
Everything gets slower as the pool growsMore concurrent queries than cores: they fight for CPU and locksSmaller pools queue in the app, where waiting is cheap.
A storm of reconnects after failoverEvery client retries at onceRetries with backoff and jitter; a pooler or proxy absorbs it.
Strange bugs in transaction modeSession settings leak between clients, or vanishUse SET LOCAL; avoid session-level features behind a transaction pooler.
Serverless functions exhaust the databaseEach invocation opens a connectionA proxy in front, or a data API.
Alternatives rejected

Why not just...

How to operate it

What I watch

-- PostgreSQL: who holds connections, and in what state
SELECT application_name, state, count(*)
FROM pg_stat_activity GROUP BY 1, 2 ORDER BY 3 DESC;
-- PgBouncer admin console
SHOW POOLS;    -- cl_waiting > 0 means clients are queueing
SHOW STATS;

-- MySQL: connected against running
SHOW GLOBAL STATUS WHERE Variable_name IN
  ('Threads_connected', 'Threads_running', 'Max_used_connections', 'Aborted_connects');

-- MongoDB
db.serverStatus().connections
Version notes

What changed recently

Your turn

A service runs 40 pods, each with a pool of 30, against a PostgreSQL primary with max_connections 500. At peak it does 4,000 queries a second averaging 6 ms. A deploy starts 40 new pods before stopping the old ones. What happens, and what would you change?

Write your answer down first. Then open mine.

Show my answer

What happens: 40 × 30 = 1,200 possible connections already exceed 500. During the deploy, 80 pods can ask for 2,400. New pods fail to connect, health checks fail, the deploy stalls or rolls back.

What the work needs: 4,000 × 0.006 = 24 busy connections on average. Even with headroom for bursts, under 100 in total.

What I would change: pools of 3 to 5 per pod; PgBouncer in transaction mode in front, with a server pool of about 50; and a deploy that replaces pods in batches. Then check that nothing in the code depends on session state.

Connected

Where this shows up

The same mechanism, caches and memory, replication and failover, elsewhere on the site: in real incidents, in measurements, and in designs.

Check yourself · 4 questions

Check yourself

Pick an answer. You will see whether it is right, and why.

1. Queries take 10 ms and you run 1,000 a second. On average, how many connections are busy?

2. Which feature breaks behind PgBouncer in transaction mode?

3. The pool times out but the database CPU is at 10%. What is the likely cause?

4. Why can a bigger pool make things slower?

Part 4 of 4 · Operate · 15 pagesAll pages

How do I run it in production? What to check when it is slow or broken, where it runs and what it costs, how big it must be, pooling, backups, security, upgrades and other changes made safely.