Connection Pooling
Keep a small set of open database connections to reuse, instead of opening a new one for every request.
What is it?
Opening a database connection isn't free. It needs a network handshake, authentication, and setup on both sides, often tens of milliseconds. If a web server opens and closes a connection for every request, it pays that cost over and over. A traffic burst can also open so many connections that the database is overwhelmed (every database has a hard limit on simultaneous connections).
Connection pooling keeps a fixed-size set of open connections, a pool, ready to go. Your code borrows a connection, uses it, and returns it to the pool, instead of opening and closing a new one each time.
Explain like I'm 10
A new connection per request is like renting a brand-new car (paperwork and all) for each errand, then scrapping it. A pool is a car-sharing fleet already fueled and ready: check one out, use it, return it for the next person.
Examples
Without pooling — a new connection per request
// Conceptual, not real code:
app.get("/user/:id", async (req, res) => {
const connection = await openNewDatabaseConnection(); // slow, every time
const user = await connection.query("SELECT * FROM users WHERE id = $1", [req.params.id]);
await connection.close();
res.json(user);
});Every request pays the full cost of opening and closing a connection, even under heavy traffic.
With a connection pool
const pool = createConnectionPool({ min: 2, max: 10 });
app.get("/user/:id", async (req, res) => {
const connection = await pool.acquire(); // reuses an existing connection
try {
const user = await connection.query("SELECT * FROM users WHERE id = $1", [req.params.id]);
res.json(user);
} finally {
pool.release(connection); // returns it for the next request to use
}
});The pool keeps 2 to 10 connections open. Each request borrows one, uses it, and gives it back, with no repeated setup cost.
How it works
The pool keeps between a configured minimum and maximum number of open connections. When code borrows one, the pool hands over an idle connection, or opens a new one if none are free and it's under the max. If it's at the max and all are busy, the request waits until one is returned. When done, code "releases" the connection back to the pool instead of closing it.
This caps how many connections the database sees at once (protecting it from overload) and avoids paying setup cost for every unit of work.
Why does it exist?
Databases limit simultaneous connections, and opening one is relatively expensive. Without pooling, an app under real traffic either pays the setup cost constantly or risks hitting the connection limit in a spike, so new requests fail outright.
When to use it
Use pooling in almost any app server that talks to a database and handles more than one request at a time. It's standard in production web apps, and most drivers and ORMs build it in or support it.
When not to use it
A short-lived script that opens one connection, does its work, and exits doesn't need a pool. Pooling pays off under repeated, concurrent access.
Common mistakes
Forgetting to release a borrowed connection. The pool eventually runs dry and every later request waits forever.
Setting the pool's max above the database's connection limit, especially with many app instances that each have their own pool.
Thinking pooling makes queries faster. It removes connection setup overhead; a slow query stays slow.
Practice exercises
- Easy:
In your own words, explain why opening a new database connection for every web request is wasteful.
- Medium:
Describe what happens to a database if 500 app server instances each open their own pool with a max of 20 connections.
- Hard:
Describe a bug where forgetting to release a connection eventually makes every request hang.
Interview questions
What problem does connection pooling solve?
It avoids opening and closing a connection for every request, and caps how many simultaneous connections the database must handle.
What happens when all connections in a pool are in use and a new request needs one?
The request waits until a connection is released, or, if the pool is under its max, a new connection is opened for it.
Why can't you just set a connection pool's maximum size arbitrarily high?
The database has a hard limit on simultaneous connections. Exceeding it, especially with many app instances each running a pool, can overwhelm it or make it reject connections.
Why is opening a database connection expensive in the first place?
It needs a network round trip, a TLS/authentication handshake, and setup on both sides: often tens of milliseconds that have nothing to do with your query.
Besides the client's cost, why does the database itself pay a real cost per open connection?
Most databases run a dedicated backend process or thread per connection, holding memory and other resources as long as it's open, busy or not.
What's the difference between a pool's `min` and `max` settings?
min is how many connections the pool keeps open even when idle. max is the ceiling it never exceeds, whatever the demand.
Why keep a nonzero `min` of idle connections rather than letting the pool shrink to zero when idle?
So the next request doesn't pay full setup cost. A warm, open connection is ready right away.
What's a common cause of pool exhaustion that isn't simply too much traffic?
Code that borrows a connection and never releases it: a bug, an unhandled exception that skips the release, or a missing finally block. It quietly shrinks the pool's usable capacity over time.
Walk through how one leaked (never-released) connection eventually stalls every request, even under otherwise normal load.
Each leak permanently removes one connection from the pool. If the bug fires repeatedly, eventually every connection is checked out forever, and every new request waits for a connection that never comes back.
What is connection pool starvation caused by a single long-running query or transaction?
One request holds its connection for a long time (a slow query, or a transaction left open waiting on something). Especially in a small pool, every other request waits behind it, even though nothing leaked.
Why can a burst of reconnects after a brief outage or app restart overwhelm a database even with pooling in place?
If many app instances start or reconnect at once and each fills its pool to its minimum right away, the database gets a sudden spike of connection attempts instead of the gradual load pooling is meant to give.
What's a commonly cited starting guideline for sizing a connection pool, and why is 'bigger is always better' wrong?
A common rule of thumb sizes the pool relative to the database's CPU cores; small pools on roughly that order tend to perform best. Past a point, more connections just compete for the same CPU and I/O, so throughput flattens or drops.
Why might increasing a pool's max size from 10 to 100 make overall throughput worse instead of better?
Beyond what the database's CPU and disks can handle at once, extra connections just compete for the same resources, adding context-switching and lock contention instead of real work.
What's the difference between a connection pool built into the application/ORM and an external pooler like PgBouncer running as its own service?
A client-side pool is per app instance, so its max multiplies by the number of instances. An external pooler is one shared layer in front of the database, letting many app-side connections share far fewer real database connections.
Why might you run an external pooler in front of a database even when your app already has its own client-side pool?
It caps the total connections the database sees across all app instances, instead of each instance's pool adding to the total. This matters once you run many instances.
What's the practical difference between 'session pooling', 'transaction pooling', and 'statement pooling' modes in a tool like PgBouncer?
Session pooling gives a client one database connection for its whole session. Transaction pooling returns the connection as soon as each transaction commits, so many more clients can share connections. Statement pooling releases it after every statement: the most sharing, but the fewest supported features.
Why can transaction-mode pooling break features like session-level prepared statements or advisory locks?
Those features rely on the same physical connection persisting across statements. In transaction mode, the client may get a different connection for its next transaction, so any state left on the previous one is gone.
Why does deploying many application server instances, each with its own pool, multiply the effective connection count the database sees?
Each instance opens up to its own max independently, so the database faces the sum of all the maximums, not one shared ceiling.
What's a connection health check or validation query, and why does a pool need one?
A trivial query (or protocol-level check) the pool runs before handing out a connection, to confirm it's alive. Without it, a connection that silently died (network blip, database restart) could be given to a request that then fails.
Why is serverless/lambda-style compute a notoriously bad fit for pooling directly against the database, and what's the usual fix?
Each short-lived function instance can create its own pool, so at scale huge numbers of instances open connections and quickly exceed the database's limit. The usual fix is a shared external pooler between the functions and the database.
What's the difference between an idle timeout on a pooled connection and the pool's overall max size?
The idle timeout sets how long an unused connection stays open before the pool closes it, letting the pool shrink toward min when quiet. max is a hard ceiling on open connections at any time.
Why doesn't pooling make a slow query run faster?
Pooling only removes connection open/close overhead. Running the query itself (the query, indexes, table size) is unchanged.
Compare a connection pool to a thread pool conceptually — where does the analogy hold, and where does it break down?
Both reuse a limited, expensive-to-create resource instead of making one per unit of work. But a thread is generic compute, while a connection is stateful: an authenticated session to one database. Handing connections around carelessly (mid-transaction, wrong session state) can cause bugs a thread never would.
Scenario: a service acquires one connection from a pool sized to 1, then tries to acquire a second connection before releasing the first. What happens?
The second acquire() waits forever, because the only connection is the one this request already holds. It's a classic pool self-deadlock: the pool is too small for code that needs two connections at once.
Why should you generally avoid holding a pooled connection open across a slow, non-database operation in the middle of a request (e.g. an external HTTP call)?
The connection sits idle but checked out for the whole slow operation, unavailable to every other request. A scarce shared resource is tied up for work unrelated to the database.
What's the effect of pointing multiple read replicas at entirely separate pools versus one shared pool?
Separate pools let you size and track each replica's load independently, but with uneven traffic one pool can run dry while another sits idle. A shared pool balances load but adds routing complexity to know which replica a connection belongs to.
Debugging: requests are timing out with pool-exhaustion errors, but overall traffic hasn't increased. What would you check first?
Whether something holds connections longer than before: a slow query, a leak from unhandled errors, or a code change that acquires earlier or releases later. Don't assume the pool is just too small.
Why might reducing a pool's max size sometimes increase throughput on an already-overloaded database?
Too many concurrent connections can spend more time on contention and context-switching than real work. Lower concurrency lets each query finish faster, raising overall throughput despite less parallelism.
What's the tradeoff of setting a very short idle timeout on pooled connections?
It frees resources quickly when quiet, but a traffic burst right after faces a wave of new connection setup, since the pool already shrank toward its minimum.
Why does pooling matter more for a long-running application server than for a short-lived script?
A script that opens one connection and exits pays setup once anyway. Pooling pays off under repeated, concurrent access, which is what a long-running server sees.