SQL databases with Node and connection pools

Intermediate · 11 min

Using the pg driver with a Pool in Node, why a pool exists, parameterized queries, transactions on a checked-out client, and how connection leaks show up.

Before thisConfiguration and environment variablesEvents and EventEmitter

WittCode · 11 min

SQL databases with Node and connection pools

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by WittCodeReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A TCP connection plus authentication to Postgres costs tens of milliseconds, and the server can hold only a limited number of connections. A pool keeps a few open and lends them out.
  • Create one `pg.Pool` per process at startup and share it. Never create one per request.
  • `pool.query(text, values)` checks out a connection, runs one statement and returns it automatically. It is the default for single statements.
  • A transaction needs `await pool.connect()`, `BEGIN`, `COMMIT` or `ROLLBACK` on that same client, and `client.release()` in a `finally`. Running `BEGIN` through `pool.query` may spread the statements across different connections.
  • Values go in `$1, $2` placeholders with an array, so the driver sends them separately from the SQL text. Building SQL by string interpolation is how injection happens.
  • When the pool is at `max` connections, extra queries wait in a queue. A connection checked out and never released eventually makes every query time out.
  • `pool` is an `EventEmitter`. Attach an `error` handler, because an idle client that loses its connection emits one, and without a listener the process crashes.

The cost of talking to a database

A Node service that serves a request usually needs the database for a few milliseconds. Getting a connection to it takes much longer. Opening a TCP socket, negotiating TLS, authenticating and setting up the session adds up to tens of milliseconds, and on the server side every connection holds memory and a slot. Postgres defaults to 100 of them. Put that behind a service handling hundreds of requests per second and two problems appear: you spend more time connecting than querying, and you can run the database out of connections.

A connection pool fixes both. It opens a handful of connections, keeps them alive, and lends one out whenever code needs it. When the code is done, the connection goes back instead of closing. Think of a restaurant with ten tables: guests do not build a table each time they arrive, and when all ten are taken, new guests wait at the door instead of sitting on the floor. The pool’s max is the number of tables.

This lesson uses pg (node-postgres), the standard driver for Postgres. mysql2 has the same pool idea with a slightly different API. Whether to write SQL by hand or through a query builder is a separate decision, covered in ORMs, query builders and raw SQL and, for Node specifically, in ORMs for Node: Prisma and Drizzle. Everything above those tools still runs on a pool like this.

One pool per process

import pg from 'pg';

export const pool = new pg.Pool({
  connectionString: process.env.DATABASE_URL, // validated at startup, see the config lesson
  max: 10,                       // the number of tables
  idleTimeoutMillis: 10_000,     // close connections idle this long
  connectionTimeoutMillis: 2_000 // how long a query may wait for a free connection
});

pool.on('error', (err) => {
  console.error('idle client error', err.message);
});

Create it once, in a module, and import it everywhere. The video walks through exactly this: what a pool is, when to use one, the options, and the fact that the pool is an EventEmitter. That last point matters. Connections sitting idle can be dropped by a network device or a database restart, and the pool reports it with an error event. If nobody listens, Node treats it as an unhandled error event and the process dies. Events and EventEmitter explains why.

A pool does not connect until the first query. It also does not open max connections up front. It opens more only when demand needs them.

Running queries

For a single statement, call pool.query. It checks a connection out, runs the statement, and returns the connection, all in one call:

const { rows } = await pool.query(
  'SELECT id, name FROM accounts WHERE name = $1',
  [name]
);

The $1 is a placeholder. The driver sends the SQL text and the parameter array separately, so the database never parses your value as SQL. I ran this against a local Postgres 14 with the input x' OR '1'='1. The parameterized query returned 0 rows. The same input interpolated into a template string returned both rows in the table. That is the whole injection story in one result. The broader picture, including what placeholders cannot protect, is in input validation and injection attacks. In short: placeholders are for values, so a column name or ORDER BY direction taken from a user needs an allowlist.

Transactions need one client

A transaction is a sequence of statements on one connection. pool.query may hand each call a different connection, so it cannot be used for this. Check out a client instead:

async function transfer(from, to, amount) {
  const client = await pool.connect();
  try {
    await client.query('BEGIN');
    await client.query('UPDATE accounts SET balance = balance - $1 WHERE name = $2', [amount, from]);
    await client.query('UPDATE accounts SET balance = balance + $1 WHERE name = $2', [amount, to]);
    await client.query('COMMIT');
  } catch (err) {
    await client.query('ROLLBACK');
    throw err;
  } finally {
    client.release();
  }
}

With a CHECK (balance >= 0) constraint, moving 30 from ada to bob committed, and trying to move 500 from bob threw error code 23514 and rolled back. Both balances were untouched afterwards. The video shows pool.connect() and releasing the client back; the full BEGIN/COMMIT/ROLLBACK pattern above is the standard shape, and the Hussein Nasser video under “go deeper” demonstrates it too. What a transaction guarantees and how isolation levels change that is in transactions and isolation levels in application code.

The finally is not optional. It is the single most common source of pool problems.

What exhaustion looks like

To see the limits, I used a pool with max: 5 and fired twelve queries that each sleep for 200 ms. Fifty milliseconds in, the pool showed totalCount 5, idleCount 0 and waitingCount 7: five running, seven queued. The twelve queries used exactly five distinct backend connections between them. Nothing failed. The pool just made the extra work wait its turn, which is the point.

Then the failure case. I checked out all five clients and never released them, and ran one more pool.query. It waited, then failed after the 2 seconds I had set with timeout exceeded when trying to connect. The database was idle the whole time. This is what a leak looks like in production: latency climbs, then everything times out, while database CPU stays flat. If you see that, look for a connect() without a release(), often on an error path.

pool.totalCount, pool.idleCount and pool.waitingCount are cheap to export as metrics, and a rising waitingCount is an early warning.

Sizing the pool

More is not better. The database can only do so much work in parallel, and a pool of 100 mostly makes requests queue inside Postgres instead of inside your service. A modest max (ten is a common starting point) is usually right per process. Remember that each process or container has its own pool, so ten instances at max: 10 can open a hundred connections. If you run many instances or serverless functions, put a pooler such as PgBouncer in front rather than raising the limit. Tuning this properly is a measurement job, not a formula.

What the video covers

WittCode’s ten-minute video is chaptered and follows the same arc as this lesson: what a connection pool is and why and when to use it, creating one with pg, the configuration options, checking a connection out and releasing it, checking pool counts, querying through the pool, closing the pool, and the pool’s EventEmitter events. It does not cover transactions in depth or parameterized queries, so those sections are carried by the prose above. The code here was run against Postgres 14 and pg 8; I did not run the video’s own code.

Where this fits

Raw pg is the lowest layer most Node services use. Most teams add something on top, which is the next lesson. Keep this one in mind when a query hangs: the problem is often the pool, not the SQL.

Check yourself

  1. 01Why not open a new connection for every request and close it afterwards?

    Each connection pays for TCP and authentication setup, and Postgres allocates a backend process or comparable resources per connection, so a busy service would waste time connecting and could exhaust the server's connection limit. A pool pays that cost a few times, then reuses connections. Like seating guests at a restaurant with a fixed number of tables, it bounds concurrency and makes extra requests wait.

  2. 02Where does this go wrong: `await pool.query('BEGIN'); await pool.query('UPDATE ...'); await pool.query('COMMIT');`?

    Each `pool.query` call may use a different connection from the pool, so the `BEGIN`, the update and the `COMMIT` can land on three separate sessions. Nothing is actually in a transaction. Check out one client with `pool.connect()` and send all three statements on it.

  3. 03What happens if a code path calls `pool.connect()` and an exception skips `client.release()`?

    The connection never goes back to the pool. Repeat that `max` times and the pool has nothing left to lend, so every later query waits until `connectionTimeoutMillis` and fails with a timeout error, even though the database itself is idle. Always release in a `finally` block.

  4. 04Does `pool.query('SELECT * FROM users WHERE name = $1', [name])` protect against `x' OR '1'='1`?

    Yes. The text and the values travel separately, so the value is treated as data and never parsed as SQL. The same input in a string-built query matches every row. Placeholders only work for values, not for table or column names, so identifiers from users need an allowlist.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark