DEV Community

Cover image for Node pg pool.query reconnects after every query error
Amorizz
Amorizz

Posted on

Node pg pool.query reconnects after every query error

A duplicate key error in my Node service cost more than the failed insert. pool.query() in node-postgres threw the connection away and opened a new one, every time: 100 unique violations gave me 100 new Postgres backends, and the request right after each error waited about 5 ms instead of 0.07 ms.

Versions: pg 8.23.1 (with pg-pool 3.14.0), Node 24.22.1, PostgreSQL 17.12 on localhost, three runs of 100 errors per case.

Where I noticed it

In the last post on query_timeout I wrote that pg drops the client after a query_timeout. While going through the leftover numbers from that lab, one line didn't fit. After a server side statement_timeout, pool.totalCount and pool.idleCount were also both 0. Postgres had cancelled the statement cleanly and the session was fine, yet the pool still threw the client away.

My guess was that this has nothing to do with timeouts. So today I ran a small lab to check whether any failed query through pool.query() costs a reconnect.

What I measured

Each loop runs 100 times: one query that fails, then select pg_backend_pid() through the pool. I count new connections with the pool's connect event, count distinct backend pids on the Postgres side, and time the query that runs right after the error.

Case (100 errors) New connections Distinct backend pids Next query, median Loop total
no errors, pool.query (baseline) 0 1 0.06 to 0.07 ms 8 to 10 ms
unique violation via pool.query 100 100 4.83 to 5.14 ms 555 to 610 ms
unique violation via pool.connect + client.release() 0 1 0.07 to 0.09 ms 23 to 25 ms
statement_timeout via pool.query 100 100 5.81 to 6.10 ms 5,675 to 5,723 ms
statement_timeout via pool.connect + client.release() 0 1 0.39 to 0.43 ms 5,115 to 5,128 ms

The timeout rows are slower overall because each statement waits 50 ms before Postgres cancels it. Compare the two timeout rows with each other: about 560 to 600 ms more per 100 errors, roughly the same extra cost as in the unique violation rows.

A fresh Client connect plus one select 1 took a median of 4.68 to 4.92 ms in the same setup, so the extra time after each error is a full new connection. That is the floor. My lab has no TLS, no network hop and uses plain password auth over localhost. A real app talking to a managed Postgres pays for a TCP handshake, TLS and SCRAM on top, and Postgres forks a new backend process for every one of them.

Why it happens

It is in the source, and it is on purpose. In node_modules/pg-pool/index.js (3.14.0), the callback inside Pool.query ends like this (line 474):

client.release(err)

It passes the query error, whatever it is. Then _release (line 392) checks:

if (err || this.ending || !client._queryable || client._ending || ...) return this._remove(client, ...)

Any truthy err sends the client to _remove, which calls client.end(). The pooling docs say that a truthy value passed to release destroys the client. What I never saw spelled out is that pool.query passes every query error there, including errors where Postgres answered normally and the session is fine. A maintainer said as much in issue #1942 back in 2019: pool.query evicts on error automatically, and a smarter wrapper could tell transient errors like a unique violation apart from a dead connection.

Why it matters: plenty of normal code paths fail on purpose. Using a unique key as the dedupe check for webhooks or idempotent inserts is common. So are check constraints that reject bad input, a statement_timeout you set as a guard (which I recommended in the last post), and serialization failures you retry. With pool.query, each of those is also a reconnect.

The fix I'm using

Check out the client yourself, and tell the pool to drop it only when the error did not come from Postgres. A Postgres error always carries a SQLSTATE in err.code (23505 for a unique violation, 57014 for a cancelled statement). Errors from the driver side, like Query read timeout or a dead socket, have no code.

This script shows both the problem and the helper. It needs a Postgres you can create a table in, configured through the usual PG* env vars:

// node article.js  (uses PGHOST, PGPORT, PGUSER, PGPASSWORD, PGDATABASE)
const { Pool } = require('pg');

const pool = new Pool({ max: 5, statement_timeout: 50 });
let connects = 0;
pool.on('connect', () => connects++);

// Same as pool.query, but an ordinary SQL error does not cost a reconnect.
async function query(text, values) {
  const client = await pool.connect();
  try {
    const res = await client.query(text, values);
    client.release();
    return res;
  } catch (err) {
    // err.code set (23505, 57014...): Postgres answered, the session is fine.
    // No code (query_timeout, dead socket): let the pool drop the client.
    client.release(err.code ? undefined : err);
    throw err;
  }
}

async function run(label, fn) {
  const before = connects;
  const t0 = performance.now();
  for (let i = 0; i < 100; i++) {
    await fn('insert into lab_dupe values (1)').catch(() => {}); // 23505
    await fn('select 1');
  }
  const ms = Math.round(performance.now() - t0);
  console.log(`${label}: ${connects - before} new connections, ${ms} ms`);
}

(async () => {
  await pool.query('create table if not exists lab_dupe (id int primary key)');
  await pool.query('insert into lab_dupe values (1) on conflict do nothing');
  await run('pool.query  ', (sql) => pool.query(sql));
  await run('query helper', (sql) => query(sql));
  await pool.end();
})();
Enter fullscreen mode Exit fullscreen mode

Three runs on my box:

pool.query  : 100 new connections, 575 ms
query helper: 0 new connections, 20 ms
pool.query  : 100 new connections, 573 ms
query helper: 0 new connections, 18 ms
pool.query  : 100 new connections, 528 ms
query helper: 0 new connections, 20 ms
Enter fullscreen mode Exit fullscreen mode

I also mixed 100 unique violations with 100 statement timeouts through the same helper: 200 errors, 0 new connections, totalCount 1 and idleCount 1 at the end, in all three runs.

Checking that it still drops broken clients

Keeping clients is only safe if the pool still throws out the bad ones, so I tested two cases.

  • query_timeout: 100 on a 500 ms sleep: the error is Query read timeout with no code, the helper passes it to release, the pool opened 1 new connection and the next query worked (6.1 to 6.9 ms, i.e. a reconnect, as it should be).
  • I killed the idle backend with pg_terminate_backend(). The pool's idle error listener removed that client on its own, and the next query ran on a new pid.

One gap I did not test: a fatal error that arrives with a code in the middle of a query, like 57P01 when an admin terminates the backend. When the socket closes, pg marks the client as not queryable (lib/client.js, line 420) and _release drops it on that check too, but that depends on the close arriving before your release(). If you want to be strict, treat the 08 class and 57P01 to 57P03 as fatal and pass the error.

Where this helper is wrong

Transactions. I opened a client, ran begin, hit a unique violation, then called client.release() with no rollback on a pool with max: 1. The next unrelated pool.query('select 1') got that same connection and failed with 25P02: current transaction is aborted, commands ignored until end of transaction block. Three runs out of three.

That is a good reason for pool.query to be blunt by default. Inside BEGIN ... COMMIT, run rollback in your catch block before release(), and pass the error to release if the rollback itself fails. The helper above is for single statements only.

Keeping connections also keeps session state. @sunnatulla_dev pointed out on the last post that a plain SET statement_timeout = 0 stays on a pooled connection and leaks into the next request. Reusing clients after errors doesn't make that worse, but it is the same trade: a reused connection carries whatever the last user left on it.

I run one production failure through a lab every Thursday and Sunday, and post the leftovers as short notes like this one on Tuesdays.

Which SQLSTATE codes, if any, does your own wrapper treat as "drop this connection"?

Top comments (2)

Collapse
 
hritik_chaudhary_5db0056f profile image
Hritik Chaudhary •

I would drop on class 08 (connection exception) and 57P01 to 57P03 (admin shutdown, crash shutdown, cannot connect now). Those can arrive as FATAL with a code set, so err.code ? undefined : err would keep a dying client. The _queryable check in _release probably covers a closed socket, but it is worth testing: pg_terminate_backend on an idle pooled client, then run a query. 25P02 is a different case. If the helper ever wraps BEGIN, an aborted transaction should be rolled back before release, otherwise the next caller inherits it. For the unique violation case, INSERT ... ON CONFLICT DO NOTHING avoids raising the error at all.

Collapse
 
sunnatulla_dev profile image
Sunnatulla •

Ran it on pg 8.23 and PG17. I terminated an idle pooled client, then one mid pg_sleep. The in-flight one threw 57P01 with err.code set, so the helper released it clean, but the pool dropped it anyway (totalCount 0) and the next query just reconnected. _queryable covers it.