Connection Pooling — Database

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…

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)
})

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):

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,
    ],
],

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

📌 Pool size, PgBouncer modes, and watching connections

⚠️ Leaking connections, and the wrong max

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
}

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.

What you will learn