# Connection Pooling

> Understand why a database refuses clients when too many connect, and how a pool reuses a few connections safely, with its size and its traps.

Subject: SQL | Lesson 43 of 44 | 7 min read
Interactive lesson: https://codewithanimation.in/sql/connection-pooling
Previous: [Parameterized Queries & SQL Injection](https://codewithanimation.in/sql/parameterized-queries-and-sql-injection.md) | Next: [Schema Migrations](https://codewithanimation.in/sql/migrations.md)

## Reuse connections instead of opening new ones

Before an app can run a query it needs a **connection** to the database. PostgreSQL gives every connection its own backend process: the manual says every client process connects to exactly one backend process, and a supervisor called the postmaster starts a new one every time a connection is requested.

A **connection pool** is a small set of connections kept open by your app. A request borrows one, runs its query, and gives it back for the next request to use. If all are busy, the request waits in line.

## A limit, and a cost per connection

The database accepts only so many connections at once: `max_connections`, typically 100 by default, and it can only be changed by restarting the server. Each connection is a process with its own memory. And opening a connection takes time before the first query can run.

A busy site can easily have more simultaneous requests than the database has connections. Without a pool, the extra ones are turned away.

## Twelve requests, six connections allowed

```js
const pool = new Pool({ max: 4 });
await pool.query("SELECT ...", [id]);
```

In the lab, 12 requests arrive in a burst and the database allows 6 connections. With no pool, each request opens its own connection, and only 6 get in. The rest fail with `sorry, too many clients already`.

With a pool of 4, the same 12 requests are all served. Four connections are opened once and reused, and the other requests wait their turn, first in, first out. Nobody is refused, and the database never sees more than 4 connections.

`pool.query(...)` borrows a connection, runs the query and gives it back for you. For several statements that must belong together, such as a transaction, borrow one connection with `pool.connect()` and run every statement on it, then release it.

## Common mistake: Leaks, size and pooler modes

If you borrow with `pool.connect()` you **must** release the connection. A connection that is never released is lost for good, and after enough leaks every request waits forever. Release in a `finally` block, so it happens even when the query fails.

Pool size is a balance. Too small, and requests queue up and time out (the pool of 2 in the lab). Too big, and the pool asks for more connections than the database allows. Remember that every copy of your app has its own pool, so add them up: the total across all servers must stay below `max_connections`.

Do not run a transaction with `pool.query`: each call may use a different connection, so the statements would not be in one transaction.

A separate pooler such as PgBouncer sits between your apps and the database. In **transaction pooling** mode a connection goes back to the pool when each transaction ends, which allows far more clients, but it breaks features that live on one session: `SET`, `LISTEN`, session-level advisory locks and `PREPARE`.

## Tip: A small pool, released every time

Start with a small pool, a handful of connections per app instance, and raise it only when you can see requests waiting. Always release in `finally`, never share a connection between two requests at once, and keep the total under what the database allows.

## Try it: Burst of requests, with and without a pool

Start with No pool and read the refused requests. Then try Pool of 2, 4 and 8, and finally switch on Forget to release.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/sql/connection-pooling

## Check yourself

### Question 1

The database allows 6 connections. 12 requests arrive at once, each opening its own connection. What happens?

- A. Some are refused with 'sorry, too many clients already'
- B. All 12 are served, one after the other
- C. PostgreSQL raises max_connections automatically

Correct answer: A

The database refuses connections beyond max_connections. A pool keeps the number of connections small and makes requests wait instead.

- Why not B: Without a pool nothing queues them. A connection beyond the limit is simply refused.
- Why not C: max_connections can only be set at server start. It does not change on its own.

### Question 2

Code borrows a connection with `pool.connect()` and an error is thrown before `client.release()` is reached. What is the result?

- A. The connection is lost to the pool, and enough of these empty the pool
- B. The pool takes it back automatically
- C. Nothing, because the database closes it

Correct answer: A

Release in a finally block, so the connection always goes back, even after an error.

- Why not B: The pool cannot know you are done. You must release a client when you are finished with it.
- Why not C: The connection stays open on the database side, but your pool still thinks it is busy.

### Question 3

Why must a transaction use one borrowed connection (`pool.connect()`), not `pool.query()` for each statement?

- A. pool.query may use a different connection each time, and a transaction belongs to one connection
- B. pool.query is slower
- C. pool.query cannot run an UPDATE

Correct answer: A

A transaction is tied to one connection, so every statement in it has to run on the same one.

- Why not B: Speed is not the problem. The statements would not be in the same transaction.
- Why not C: It can run any statement. The issue is that BEGIN and the following statements might go to different connections.

## Remember this

- Each PostgreSQL connection is a backend process, and max_connections (typically 100) limits how many can exist.
- A pool keeps a few connections open and reuses them. Extra requests wait in line.
- Always release a borrowed connection, in finally. A leak drains the pool.
- Add up the pools of every app instance, and keep the total below max_connections. Use one connection for a whole transaction.
