Full answer
Failure modes and defences
-
Leaked clients and pool exhaustion
- pool.connect() without release() (an early return, a thrown error, a missing finally) keeps that connection busy. After max leaks, new requests queue. With no connectionTimeoutMillis they wait forever and the service looks frozen while the database is idle.
- Set connectionTimeoutMillis so waiting fails fast. Always use try/finally. Prefer pool.query when you do not need a transaction.
- Watch pool.waitingCount. A value above zero for a long time means a leak or too small a pool.
-
Slow queries
- A single slow query holds a connection and can block everything behind it. Set statement_timeout (in the pool options or per transaction with SET LOCAL). The server cancels the query with error 57014. Add indexes and use EXPLAIN.
- Use query_timeout in pg for the client side as a second guard.
-
Open transactions
- A transaction left open (BEGIN without COMMIT) holds locks and prevents vacuum. Set idle_in_transaction_session_timeout on the server or role so Postgres ends such sessions.
-
Errors on idle clients
- A database restart, a failover or a proxy can kill idle connections. pg emits an 'error' event on the pool. If no listener exists, the process crashes with an unhandled error event. Add pool.on('error', log). The pool removes the broken client and creates a new one when needed.
-
Types and data
- bigint (int8) and numeric are returned as strings. Cast in SQL or use pg.types.setTypeParser carefully, because large values lose precision.
- timestamp without time zone is parsed in the local time zone. Prefer timestamptz.
-
Shutdown and capacity
- Call pool.end() after the HTTP server stops accepting work.
- Total connections = instances times max. Compare with max_connections, or use PgBouncer in transaction mode.
- Retry only idempotent operations, and handle serialization failures (40001) and deadlocks (40P01) by retrying the whole transaction.
const { Pool, types } = require('pg');
async function main() {
// 1. A leaked client exhausts a small pool, and the timeout turns a hang into an error.
const small = new Pool({ max: 2, connectionTimeoutMillis: 200 });
const leaked = [await small.connect(), await small.connect()]; // never released
try {
await small.query('SELECT 1');
} catch (err) {
console.log('1. leaked clients ->', err.message);
}
console.log(' waiting after timeout:', small.waitingCount, '| total:', small.totalCount);
leaked.forEach((client) => client.release());
console.log(' after release, query works:', (await small.query('SELECT 1 AS one')).rows[0].one === 1);
await small.end();
// 2. statement_timeout cancels slow queries on the server.
const timed = new Pool({ max: 1, statement_timeout: 100 });
try {
await timed.query('SELECT pg_sleep(2)');
} catch (err) {
console.log('2. slow query ->', err.code, err.message);
}
await timed.end();
// 3. Types
const typed = new Pool({ max: 1 });
const row = (await typed.query("SELECT 9007199254740993::bigint AS big, 1.10::numeric AS price, now()::timestamptz AS at")).rows[0];
console.log('3. bigint:', typeof row.big, row.big, '| numeric:', typeof row.price, row.price, '| timestamptz:', row.at instanceof Date);
const asNumber = Number(row.big);
console.log(' converting the bigint to a number loses precision:', String(asNumber) !== row.big);
// 4. The server kills an idle connection. Without a listener this would crash the process.
const watched = new Pool({ max: 1 });
watched.on('error', (err) => console.log('4. pool error handler got:', err.code));
const client = await watched.connect();
const pid = (await client.query('SELECT pg_backend_pid() AS pid')).rows[0].pid;
client.release(); // now idle
await typed.query('SELECT pg_terminate_backend($1)', [pid]);
await new Promise((resolve) => setTimeout(resolve, 100));
console.log(' next query after the broken idle client works:', (await watched.query('SELECT 1 AS one')).rows[0].one === 1);
await watched.end();
await typed.end();
}
main();Four failures are reproduced against a local PostgreSQL server: a leaked client, a slow query, string types, and a killed idle connection. Install first with npm install pg (run here with pg 8.23.1). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): 1. leaked clients -> timeout exceeded when trying to connect waiting after timeout: 0 | total: 2 after release, query works: true 2. slow query -> 57014 canceling statement due to statement timeout 3. bigint: string 9007199254740993 | numeric: string 1.10 | timestamptz: true converting the bigint to a number loses precision: true 4. pool error handler got: 57P01 next query after the broken idle client works: true
Key points
- Leaked clients exhaust the pool and make the service look frozen.
- connectionTimeoutMillis and statement_timeout make failures fast.
- Always add pool.on('error') for idle client errors.
- End idle transactions with a server timeout.
- bigint and numeric are strings, and timestamps need care.
Common mistakes
- Using pool.connect() without try and finally.
- No connection timeout, so requests wait forever.
- No pool 'error' listener, so a restart of the database crashes the app.
- Converting a bigint column to Number.
- Opening a transaction and returning early without rollback.
Follow-ups
- How does PgBouncer transaction pooling change what you can do with a connection?
- How do you retry a transaction after a deadlock?
- How would you alert on pool exhaustion?
Tips
- Use the 'looks frozen' symptom to open.
- List timeouts and the error listener as the defences.
- Mention the string types.