SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
  • Indexing
  • Partitioning
  • Replication
  • Sharding
  • Query Optimization
  • Denormalization
  • Materialized Views
  • Connection Pooling
  • Replication Models
  • Replication Lag
  • Quorum (R + W > N)
  • Shard Keys, Hot Shards and Resharding
  • Cross-Shard Joins
  • Backups, RPO, RTO and Disaster Recovery
  • Point-in-Time Recovery
  • Data Archiving and TTL
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Data and Storage/Database Scaling

Connection Pooling

Reuse a small set of database connections instead of opening a new one every time.

⏱ 11 min readIntermediateInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Connection pooling means your app keeps a small set of open database connections and lends them out to requests, instead of opening a brand new connection every time.

  • Opening a connection is slow: a network handshake, maybe encryption, a login check, and a new worker on the database side.
  • A pool opens connections once, hands one to a request, and takes it back when the request is done.
  • The pool also limits how many connections exist, so the database is not buried. Extra requests wait in line.

02Concept: What is it?

A database connection is a live line between your app and the database. Before you can send a query, the line must be built. This takes several steps: open a network link (TCP), often set up encryption (TLS), log in with a user and password, and let the database get ready for you.

On the database side a connection is also not free. PostgreSQL, for example, starts a separate process for every connection, and each one uses memory. MySQL uses a thread per connection. Many databases also have a hard limit (PostgreSQL commonly defaults to 100) on how many connections can exist at once.

A connection pool solves both problems. It opens some connections ahead of time and keeps them alive. A request borrows one, runs its queries, and returns it. The next request reuses the same connection.

Without a pool and with a pool
No pool
📨Request
→↓connect + login
🗄️Databasenew process
Time spent on set-upcan be as long as the query
With a pool
📨Request
→↓borrow
🏊Poolopen connections
→↓reuse
🗄️Database
Time spent on set-upalmost nothing
Without a pool, every request pays the full set-up cost. With a pool, the connections are already open.
🧠A pool is also a limit
The pool has a maximum size. If all connections are busy, the next request waits (up to a time limit). This waiting protects the database from too many users at once.

03Real-Life Example

🍵The Library Cards at a Reading Room
A small reading room has 10 reading desks. Imagine every visitor had to build a new desk, bring a new lamp and register at the front, just to read one page. That would take longer than the reading. Instead the room keeps 10 desks ready. A visitor takes a free desk, reads, and leaves it clean for the next one. If all 10 are taken, new visitors wait in a short line. If the wait is too long, they give up and go home.
Reading room
Connection pool
A desk that is already set up
An open, ready connection
Building a new desk for each visitor
Opening a new connection per request
10 desks only
Maximum pool size
Taking a desk and giving it back
Borrow and return a connection
The waiting line at the door
The pool's wait queue
Giving up after waiting too long
Connection timeout error
A visitor who forgets to leave the desk
A connection leak
The life of one borrowed connection
🙋Askneed a connection
→↓
🧾Borrowfree one, or wait
→↓
🔎Run queriesuse the line
→↓
↩️Returnback to the pool

04Why Do We Need It?

⚡Faster requests
No handshake, no login, no new process on each request. The line is already there.
🛡️Protect the database
A hard cap on connections stops a traffic spike from using up memory on the database.
🔁Reuse is cheap
A few connections can serve thousands of short requests per second.
🚦Smooth overload
Extra requests wait in a queue or fail fast, instead of crashing the database.
🧯Health checks
A pool can test connections and replace broken ones for you.
📏Predictable resources
You know the most connections each app instance will ever use.
Opening connections is expensive and the database can only hold so many. Open few, reuse them, and make the rest wait.

05Where Do We Use It?

🧰Inside the app
Libraries like HikariCP (Java), pgx pool (Go), SQLAlchemy and psycopg pool (Python), node-postgres Pool (Node).
🧱A pooler in the middle
A separate proxy such as PgBouncer or ProxySQL pools connections for many app servers.
☁️Managed proxies
Cloud services like Amazon RDS Proxy keep a shared pool for you.
λServerless apps
Many short-lived functions can create a connection storm, so a proxy pool helps a lot.
🌐HTTP clients too
The same idea (keep-alive and reuse) is used for HTTP connections to other services.
🧵Thread and worker pools
Same pattern for any costly resource: create few, reuse many.

06Types / Parts / How It Works

Where the pool lives

Two common places for a pool
Pool inside each app
🖥️App 1pool of 10
🖥️App 2pool of 10
↓20 connections
🗄️Database
Shared pooler (PgBouncer, RDS Proxy)
🖥️App 1
🖥️App 2
🖥️App 3
↓hundreds of client links
🧱Poolerfew real connections
↓20 real connections
🗄️Database
Many systems use both: a small pool in each app, plus a pooler in front of the database.

Pooling modes (shown with PgBouncer, general idea)

ModeA real connection is held forGood and bad
Session poolingThe whole time a client stays connectedSafest and simple. Saves the least, as idle clients hold connections.
Transaction poolingOnly while a transaction runsVery efficient. Session features (temporary tables, some prepared statements, session settings) can break.
Statement poolingOne single statementMost aggressive. Multi-statement transactions are not allowed.

Settings you will meet

SettingWhat it meansWhy it matters
Maximum sizeThe most connections the pool will openToo big hurts the database. Too small makes requests wait.
Minimum idleConnections kept open even when quietAvoids a slow first request after a quiet period.
Acquire / connection timeoutHow long a request waits for a free connectionTurns an endless wait into a clear error.
Idle timeoutClose connections that were unused for a whileFrees resources, but a pool may shrink and need to regrow.
Max lifetimeRetire a connection after some time and open a new oneAvoids stale connections and works with database or firewall limits.
Validation / keep-aliveCheck that a connection still works before useStops errors from connections that were silently cut.
VisualizerPool size vs traffic: wait queue, timeouts and a spikeCompare a pool with a new connection per request. Make the pool tiny and watch the queue grow, then make it huge and watch queries slow down. Try the traffic spike and the leaky code.
How does the app connect?

Requests borrow one of a fixed number of open connections. If all are busy they wait in a queue, and give up after 2 seconds.

Connections at second 30 (pool of 8): cyan = busy, red = leaked, dark = idle
Requests waiting for a connection (amber = waiting, the pool's queue)
Average latency so far, in ms (includes waiting in the queue)
Failed requests per second (timeouts and refused connections)
0 s15 s30 s
Busy connections
5
of 8
Waiting
0
in the queue
Avg latency
50 ms
finished requests
Failed
0
timeouts + refused
Done
2995
requests finished
Healthy: 5 connections busy on average, a short queue, no failures. Average latency is 50 ms.

A simplified model with a simulated clock (no random numbers). The database has 8 cores: when more queries run than cores, each one slows down in proportion. A rough capacity for this setup is 160 requests per second. Real numbers depend on your hardware and queries.

07How to Use It / Steps / Implementation

Using a pool well

  1. 1
    Create the pool once
    Build it when the app starts and share it. Never create a new pool per request. That brings back the cost you wanted to avoid.
  2. 2
    Borrow late, return early
    Take a connection just before the query and give it back right after. Do not hold it while calling another service or waiting for the user.
  3. 3
    Always return it
    Use try/finally or a 'with' block, so a connection is returned even if an error happens. A missing return is a connection leak.
  4. 4
    Size the pool small
    A common starting idea is a small number related to the database CPU cores (a rule from the PostgreSQL community is about 2 × cores + disks). Then measure.
  5. 5
    Count all app instances
    Total connections = pool size × number of app instances. 20 servers × 10 = 200, which can be more than the database allows.
  6. 6
    Set timeouts
    Give the wait for a connection a limit, and give queries a timeout too. Fail fast, so users and threads are not stuck forever.
  7. 7
    Watch the numbers
    Track active connections, idle connections, waiting requests and wait time. Alert when the wait queue grows.
💡A bigger pool is not a faster database
A database has a limited number of CPU cores and disks. Past a point, more connections only means more queries fighting for the same resources, so each one gets slower. A small pool plus a short queue often gives better speed than a huge pool.
⚠️Serverless and many small services
Hundreds of short-lived functions each opening a pool can reach the database limit in seconds. Use a shared pooler (PgBouncer, RDS Proxy or similar) and keep the per-function pool tiny (often 1).

08Key Terms to Know

TermMeaning in easy words
ConnectionA live link between the app and the database, used to send queries
HandshakeThe back-and-forth steps (TCP, TLS, login) needed to set up a connection
Connection poolA set of ready connections that requests borrow and return
Borrow / acquireTake a connection from the pool to use it
Release / returnGive the connection back so someone else can use it
Pool exhaustionEvery connection is busy, so new requests have to wait or fail
Connection leakA connection that is borrowed but never returned
max_connectionsA database setting for the most connections it accepts (PostgreSQL commonly defaults to 100)
Pooler / proxyA separate service (PgBouncer, ProxySQL, RDS Proxy) that pools for many apps
Idle connectionAn open connection that nobody is using right now
Keep-aliveA small ping that stops firewalls or servers from closing a quiet connection

09Pros, Cons and Trade-offs

✅ Pros
  • Much lower latency per request
  • Protects the database from too many connections
  • Fewer new processes and less memory use on the database
  • Smooths out traffic bursts with a queue
  • Built into most database libraries
⚠️ Cons
  • A wrong size causes waits or an overloaded database
  • Leaked connections slowly drain the pool
  • Pools in many app instances add up
  • Transaction-mode poolers break some session features
  • One more thing to configure and monitor

Trade-offs

ChoiceWe gainWe lose
Bigger poolMore queries can run at onceMore memory and contention on the database, slower queries past a point
Smaller poolA calm, predictable databaseRequests may wait in line during a burst
Long wait timeoutFewer errors during short spikesUsers and threads wait longer, and the backlog can grow
Short wait timeoutFail fast, quick feedbackMore errors when load is only briefly high
Pool in each appSimple, no extra serviceTotal connections grow with the number of instances
Shared poolerFew real connections for many clientsExtra hop and one more component to keep alive

10Common Problems and Mistakes

Common mistakes

  1. Connection leaks. A code path forgets to release. The pool slowly empties until everything waits.
  2. Holding a connection too long. Calling a slow API or sleeping while a connection is borrowed wastes a precious slot.
  3. A huge pool. "More is better" backfires: the database slows down for everyone.
  4. Forgetting instance count. Ten servers with a pool of 50 is 500 connections, far above a typical limit.
  5. No timeouts. Without a wait limit, a stuck database makes every thread wait forever.
  6. Creating a pool per request. This is the same cost as having no pool, plus leaks.
  7. Transaction pooling with session state. Settings or temporary tables are lost between transactions.

Things to watch

⏳Pool exhaustion
All connections busy. Latency climbs and timeouts appear. Check slow queries first.
💥Connection storm
After a restart or outage, every app reconnects at once. Ramp up the pool slowly.
🧟Stale connections
A firewall or failover cut a link. Use validation and max lifetime.
🔀Failover
After a database failover the pool must drop old connections and reconnect to the new primary.

11Real-World Examples

☕Java apps
HikariCP is a very common pool, and its default maximum size is small (10).
🐘PostgreSQL at scale
Because each connection is a process, many companies put PgBouncer in front of it.
☁️Managed databases
Amazon RDS Proxy and similar services pool connections so serverless functions do not exhaust the database.
🐬MySQL fleets
Proxies such as ProxySQL (and other proxy layers) multiplex many app connections into fewer database ones.
🛒Flash sales
A burst of buyers fills the pool. A short queue and timeout keep the shop up for those already inside.
🌐HTTP keep-alive
Browsers and HTTP clients reuse connections for the same reason.
📝Note
Defaults and limits depend on the product and version. Check your driver and database docs before setting numbers.
Mini case: 20 servers and a small database
🖥️20 app serverspool 10 each = 200 links
→↓200
🧱PgBouncertransaction mode
→↓30 real
🗄️PostgreSQLmax 100
Client side Pooler Database
The pooler keeps real connections low, even when there are many clients.

12Related Topics to Read Next

Relational Databases→

The usual place where connections are costly and limited.

Query Optimization→

Faster queries return connections to the pool sooner.

Replication→

Read replicas get their own pools to spread the load.

Rate Limiting→

Another way to protect a backend from too many requests.

Latency vs Throughput vs Bandwidth→

Pooling cuts latency and raises throughput.

Message Queues→

A queue can smooth a burst before it reaches the database.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔What: a set of ready database connections that requests borrow and return.
  • ✔Why: opening a connection is slow and the database can only hold so many.
  • ✔Size: small. Start near 2 × cores + disks, then measure. Multiply by app instances.
  • ✔Full pool: requests wait in a queue, then time out.
  • ✔Always: return connections (try/finally) and set acquire and query timeouts.
  • ✔Poolers: PgBouncer, ProxySQL, RDS Proxy. Transaction mode saves most but breaks session state.
  • ✔Watch: active, idle, waiting, wait time. A growing queue means slow queries or leaks.
  • ✔One line: “Open a few connections once, share them, and make the rest wait.”
← Previous
Materialized Views
Next →
Replication Models