#1226·postgres

Stale FATAL error from a terminated backend rejects the first query after reconnect (3.4.9)

Author: fikra-labs-officialCreated Sep 24, 2026Updated Sep 24, 2026

Summary

If a backend is terminated (for example pg_terminate_backend() → 57P01, or a server restart) while a query is in flight, the in-flight query is correctly rejected with CONNECTION_CLOSED. But the next query on the same Connection object, which runs on a brand-new socket after reconnect, is rejected with the old 57P01 error. That query never reaches the server.

Reproduced on 3.4.9 (latest) with PostgreSQL 18.6 and Node 24: 10 out of 10 attempts.

Reproduction

javascript
import postgres from 'postgres'

const url = process.env.DATABASE_URL
const admin = postgres(url, { max: 1 })
const sql = postgres(url, { max: 1 })

await sql`select 1`
const [{ pid }] = await sql`select pg_backend_pid() as pid`

const inflight = sql`select pg_sleep(5)`.catch(e => e.code)
await new Promise(r => setTimeout(r, 100))          // query is on the wire
await admin`select pg_terminate_backend(${ pid })`

console.log('in-flight:', await inflight)           // CONNECTION_CLOSED  (expected)
console.log('next:', await sql`select 1 as x`.then(() => 'ok', e => e.code))
                                                     // 57P01  (expected: ok)
await sql.end(); await admin.end()

The PostgreSQL log (with log_connections/log_statement=all) shows that the new backend for the "next" query connects and later disconnects cleanly without receiving a single statement.

Cause

src/connection.js:

  1. When the FATAL ErrorResponse arrives while query is set, it is parked in errorResponse until ReadyForQuery, which never comes because the backend is gone.
  2. closed() rejects the in-flight query via error(CONNECTION_CLOSED), but it does not reset errorResponse, query or results.
  3. After reconnect, the first ReadyForQuery of the new socket (the one that ends startup) takes the else if (errorResponse) errored(errorResponse) branch (or the if (query) branch with the stale query). errored() then rejects initial, the query that triggered the reconnect, with the stale 57P01, before it is ever sent.

The same state leaks in cjs/src and cf/src.

Proposed fix

Response state belongs to one socket, so reset it in closed() after the in-flight query has been rejected:

diff
   async function closed(hadError) {
     ...
     socket.removeAllListeners()
     socket = null

-    if (initial)
-      return reconnect()
-
-    !hadError && (query || sent.length) && error(Errors.connection('CONNECTION_CLOSED', options, socket))
+    const reconnecting = !!initial
+    !reconnecting && !hadError && (query || sent.length) && error(Errors.connection('CONNECTION_CLOSED', options, socket))
+
+    // Response state belongs to the socket that just closed.
+    query = results = errorResponse = null
+    result = new Result()
+
+    if (reconnecting)
+      return reconnect()
+
     closedTime = performance.now()

With this change the reproduction above prints next: ok in 10 out of 10 runs. A regression test is straightforward: terminate the backend of an in-flight pg_sleep and assert that the next query on a max: 1 pool succeeds.

Impact

After any backend loss during a query (restart, failover, admin kill, idle_in_transaction_session_timeout FATAL racing a query), the first query on the reconnected connection fails spuriously. In transactional code that runs as BEGIN failing "before the callback", which looks like an unrelated error.

Related

Possibly the same root cause as #1223 (state from the killed socket is replayed after reconnect), but triggered by an ordinary in-flight query rather than fetch_types during startup.