In this lesson's Lab, Sunset Coffee's order-history query takes only 20 ms. Yet every request to that page takes 70 ms. Where does the rest go? Into opening a connection to the database, and that happens again on every request.
The cure is a connection pool: a set of database connections opened once and then lent out to request after request. Borrow one, run the query, give it back. Picture calling your bank's call centre. Before you may ask anything, you listen to the menu, say your account number, then answer the security questions. If all you want to know is "what's my balance?", the checking takes far longer than the question. The call centre also has only so many agents, so when they're all busy, you're told to hold. Opening a database connection is that checking, and the number of agents is the database's connection limit.
What happens when an app connects to a database
A connection is a line of communication between the app and the database server. Before the first query can go out, the two have to get acquainted: TCP opens the network path, TLS agrees on encryption, then the database checks the username and password (authentication). PostgreSQL also starts a dedicated process for every connection, which uses a few MB of memory for as long as the connection stays open.
We call all of that getting acquainted the handshake. In the Lab, the handshake takes 50 ms and the query 20 ms. These are example model numbers, not benchmarks: a database on the same machine can connect in 1 to 2 ms, one in another region can take hundreds of ms. The pattern stays the same:
| Approach | Time per request (Lab model) |
|---|---|
| Open a new connection per request | 70 ms: 50 handshake + 20 query |
| Borrow from a pool | 20 ms: just the query, the handshake was paid when the connection was opened |
That's why production apps need a pool: opening a new connection (TCP, TLS, authentication) for every request is wasteful. A pool reuses connections that are already established.
Connection pool: borrow, use, give back
In Node.js, the pg library already has a pool:
import { Pool } from 'pg'
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
max: 2, // at most 2 connections
idleTimeoutMillis: 10000, // close a connection idle for 10 seconds
connectionTimeoutMillis: 2000, // queued longer than 2 seconds: error
})
app.get('/orders', async (req, res) => {
// borrow a connection, send the query, give it back: all automatic
const { rows } = await pool.query('SELECT * FROM orders ORDER BY id DESC LIMIT 10')
res.json(rows)
})
max: 2is the pool size: the most connections this pool may open. Thepgdefault is 10.pool.query(...)borrows a connection that's sitting idle, runs the query, then gives it back. The connection is not closed, so the next request needs no handshake.idleTimeoutMilliscloses connections that sit idle too long.connectionTimeoutMilliscaps the time spent queueing; past it,pgthrowsError: timeout exceeded when trying to connect.
A full pool: the queue
Three requests arrive almost together, 2 ms apart, at a pool holding 2 connections. Will the third request error, make the pool open a third connection, or wait? Guess first, then check the trace in the Lab's Pool mode:
| Time | Event | Active | Queued |
|---|---|---|---|
| 0 ms | R1 borrows connection #1 | 1 | 0 |
| 2 ms | R2 borrows connection #2 | 2 | 0 |
| 4 ms | R3 arrives, the pool is full: R3 queues | 2 | 1 |
| 20 ms | R1 is done, connection #1 comes back, R3 takes it straight away | 2 | 0 |
| 22 ms | R2 is done, connection #2 comes back | 1 | 0 |
| 40 ms | R3 is done | 0 | 0 |
R3 doesn't error, and the pool doesn't open a third connection: R3 waits 16 ms until a connection is given back.
The exercise models exactly this table with a class ConnectionPool(maxSize):
acquire()whileactive < maxSize: raiseactive, return"ok". When full: the request joins the queue, return"queued", andactivedoes not go up.release(): loweractive. If someone is queued, take one off the queue and raiseactiveagain. Soactivestays at 2 andqueueddrops to 0, just like the 20 ms row in the table.stats(): return{ active, queued }.
max_connections: the database's own limit
The database has a limit too. PostgreSQL accepts at most max_connections connections at once, 100 by default. The next connection is refused straight away with FATAL: sorry, too many clients already.
The Lab uses a small model with max_connections = 8 so the limit is easy to hit. Send 12 requests without a pool: R1 to R8 each open a connection, and R9 to R12 are refused with that message. With a pool of 4 connections, all 12 requests finish within 66 ms and the database only ever sees 4 connections. Requests that don't get a connection wait a moment instead of being refused.
A pool lives inside one app process. If your app runs on several servers (instances), each instance has its own pool, and the totals multiply: 10 instances with max: 20 means up to 200 connections, while the limit is 100. The rule of thumb: max per instance is about max_connections divided by the number of instances, minus a little headroom. 10 instances with a limit of 100 means max around 10, not 100.
Laravel and PHP-FPM
Laravel usually runs on PHP-FPM: a set of PHP processes (workers) whose number is set by pm.max_children, each serving one request until it's done. Laravel opens the database connection at a request's first query and closes it when the request ends. So Laravel on PHP-FPM has no pool: every request pays the handshake, and the number of connections equals the number of busy workers. 3 servers with pm.max_children = 50 can open 150 connections.
// config/database.php
'pgsql' => [
// ...
'options' => [
PDO::ATTR_PERSISTENT => true,
],
],
PDO::ATTR_PERSISTENT => truemakes each worker keep its connection after a request ends and reuse it for the next one. The handshake goes away, but this is not a shared pool: every worker holds one connection all the time, idle or not. 150 workers are still 150 connections.- Settings that stick to a connection, such as
SETor a temporary table, carry over to the next request on the same worker. - Laravel Octane keeps the app alive in memory, so each Octane worker reuses its connection too.
Serverless: connections multiply
On serverless platforms such as AWS Lambda, each function instance serves one request at a time. 300 requests at once means 300 instances, and each instance has its own pool that only ever holds 1 connection. The database still sees 300 connections. Worse, a finished instance stays alive for a while (warm) waiting for the next request, and its connection stays open with it even though nothing uses it.
The fix is an external pooler: a small server in front of the database that holds a few database connections and lends them to many clients.
300 functions ─┐
├──▶ PgBouncer :6432 ──▶ PostgreSQL :5432
Laravel, Node ─┘ 300 clients 20 connections
- PgBouncer is an open source pooler for PostgreSQL: the app connects to PgBouncer (usually port 6432) instead of straight to the database. RDS Proxy is AWS's managed version, and Supabase and Neon also offer a dedicated pooler connection string.
- In transaction mode, PgBouncer lends a database connection for one transaction only, then hands it straight to another client.
- The handshake from the function to PgBouncer is still there. What it saves is the number of connections on the database.
📌 Pool size, PgBouncer modes, and watching connections
- A bigger pool isn't automatically faster. A database with 4 cores can only really work on a handful of queries at once. A starting point from the PostgreSQL wiki:
(core count × 2) + disk count, for example4 × 2 + 1 = 9. Measure, then adjust. - PgBouncer modes:
session(a client keeps one connection for as long as it's connected, barely saves anything),transaction(the usual one for the web),statement(per query, so a transaction with several queries won't work). In transaction mode, features tied to a connection such asSETandLISTENcan't be relied on. PgBouncer before 1.21 also didn't support prepared statements in this mode; in Laravel, addPDO::ATTR_EMULATE_PREPARES => truetooptions. - Reserved slots: PostgreSQL keeps 3 slots for superusers (
superuser_reserved_connections), so an ordinary app user is already refused before the 100th connection, withremaining connection slots are reserved for .... The Lab's model doesn't use these reserved slots. - Watch it:
SELECT state, count(*) FROM pg_stat_activity GROUP BY state;counts connections per state. Lots ofidle in transactionmeans some code opened a transaction without aCOMMIT. The settingidle_in_transaction_session_timeout = '60s'cuts such connections off automatically.
⚠️ Leaking connections, and the wrong max
- Forgetting
client.release().pool.connect()borrows a connection by hand, and you must give it back. Withoutrelease(), that connection never returns (a connection leak). Once every connection has leaked, the next requests queue until they time out. Putclient.release()in afinallyblock so it always runs:
const client = await pool.connect()
try {
await client.query('BEGIN')
await client.query('UPDATE orders SET total = 1000 WHERE id = 20')
await client.query('COMMIT')
} catch (err) {
await client.query('ROLLBACK')
throw err
} finally {
client.release() // runs on success and on failure
}
- The wrong
max. This is the pool setting that most often causes production trouble. Too small: requests queue. Too big: the number of instances timesmaxgoes pastmax_connections. - In the exercise, a queued request isn't active yet. An
acquire()that returns"queued"doesn't raiseactive. Afterrelease(), the queue gets promoted:activestays at 2,queuedbecomes 0.
TL;DR: Opening a database connection needs a handshake (TCP, TLS, authentication), which takes 50 ms in the Lab while the query takes only 20 ms. A connection pool opens connections once and lends them out in turn: borrow, query, give back. When every connection is in use, the next request queues until one is released, it doesn't error. The database has max_connections (100 by default in PostgreSQL); past it, connections are refused with FATAL: sorry, too many clients already. A pool lives per process, so total connections = number of instances × max. Laravel on PHP-FPM has no pool, and serverless makes one connection per instance, so for many servers or serverless put PgBouncer or RDS Proxy in front. Always client.release() in finally.
⚡ An expensive handshake
Guess first: the query takes only 20 ms, but every request takes 70 ms. Where does the rest go?
Into opening the connection: TCP, TLS, then authentication. In the Lab this handshake takes 50 ms, and it happens again on every request.
Meaning: A connection pool opens connections once, then lends them out in turn: borrow, query, give back. The handshake is paid only once.
⚡ Borrow from the pool
Write:
const { rows } = await pool.query('SELECT * FROM orders ORDER BY id DESC LIMIT 10')
Meaning: pool.query() borrows an idle connection, runs the query, then gives it back without closing it. When every connection is in use, the next request queues until one is given back, it doesn't error.
In the exercise, a queued request isn't active yet: an acquire() that returns "queued" doesn't raise active.
⚡ The database's own limit
Meaning: PostgreSQL accepts at most max_connections connections (100 by default). A pool lives per process, so total connections = number of instances × max. For many servers or serverless, put PgBouncer or RDS Proxy in front.