All notes

node-postgres crashes Node when Postgres drops a connection: listen on the pool and on each client

Node.jsPostgreSQLnode-postgresDebugging

Add an error listener to the pool and to every client the pool opens. node-postgres reports a dead connection as an error event, and Node ends the process when an error event has no listener. The pool passes on the errors of its idle clients only. A client that a transaction has checked out emits on itself, so a listener on the pool alone still leaves the server one Postgres restart away from a crash.

The crash

With no listener, ending an idle connection’s backend gives this (pg 8.23.1, Node 24, trimmed):

node:events:505
    throw er; // Unhandled 'error' event
    ^

error: terminating connection due to administrator command
    at parseErrorMessage (…/pg-protocol/dist/parser.js:306:11)
    …
Emitted 'error' event on BoundPool instance at:
    at Client.idleListener (…/pg-pool/index.js:62:10)
    …
  severity: 'FATAL',
  code: '57P01',

57P01 is what every connection receives when Postgres restarts, or when someone runs pg_terminate_backend on it. When a transaction holds the connection, the trace is the same except for one line:

Emitted 'error' event on Client instance at:

That second case is the one a pool listener misses. While a client is checked out, the pool isn’t listening to it.

The listeners

const pool = new pg.Pool({ connectionString: url });

const heard = new WeakSet();
const hear = (client, error) => {
  if (heard.has(client)) return;
  heard.add(client);
  console.warn(`database connection dropped (${error.code ?? "no code"}): ${error.message}`);
};

pool.on("connect", (client) => client.on("error", (error) => hear(client, error)));
pool.on("error", (error, client) => hear(client, error));

The WeakSet is there because one dying client can emit twice. My test, run with the listeners on and a transaction holding the connection, printed both:

client heard: 57P01 terminating connection due to administrator command
client heard:  Connection terminated unexpectedly
the next query in the transaction failed: Client has encountered a connection error and is not queryable
still alive; next query opened a new connection: true

The listeners keep the process up and nothing more. The transaction still fails and its caller still gets the error, as it should. Released with client.release(true), the dead client leaves the pool, and the next query opens a new connection.

Keep the handler from throwing. If it calls a logger that can fail, wrap the call, because an exception inside an error listener takes the process down the same way.

Test it

End one of your own connections from a second one:

const { rows } = await client.query("select pg_backend_pid() as pid");
await admin.query("select pg_terminate_backend($1)", [rows[0].pid]);

Three cases are worth a test against a real Postgres, since each takes a different path through the library: an idle connection, a connection a transaction holds between two queries, and a connection with a query running on it. In each, check that the handler was told once and that the next query gets a new connection.

A LISTEN connection is a separate matter. It’s one long-lived client outside the pool, and it needs its own reconnect with a back-off.