Skip to content

Add answer_timeout for a server that stops answering - #1278

Closed
GrahamCampbell wants to merge 2 commits into
porsager:masterfrom
GrahamCampbell:answer-timeout
Closed

GrahamCampbell wants to merge 2 commits into
porsager:masterfrom
GrahamCampbell:answer-timeout

Conversation

@GrahamCampbell

@GrahamCampbell GrahamCampbell commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

When the server stops answering while its connection stays up, as when it stalls or something in between keeps the connection open and drops the traffic, a query sent on that connection never settles, and nor does any query pipelined behind it. keep_alive cannot close the connection because the other end still answers its probes, connect_timeout covers only connecting, queue_timeout covers only waiting for a connection, and the error the server's statement_timeout would send never arrives.

This adds answer_timeout, in seconds and off by default. A connection that is waiting for an answer and receives nothing for that long is closed, and its queries reject with ANSWER_TIMEOUT, so the next query gets a new connection. The wait starts when a query is written and starts again with every chunk received while an answer is still owed, so a query the server keeps answering with rows or notices runs as long as it takes and only silence is timed. A query that runs longer than that without sending anything back is cut off too, so the option belongs above statement_timeout. It does not time a reserved connection, whose holder may keep it busy as long as it likes (a session lock wait, for instance), nor a connection while the server is waiting on the client: during a cursor's callback, a copy ... from stdin being written, or a stream whose reader has paused it. The README and the types document the option and the error, and the tests cover a connection that goes silent and the cases that are not timed.

Reproduction

Against PostgreSQL 17, through a relay that keeps both sockets open and drops every byte once silence() is called. On 4.0.0, which ignores the unknown answer_timeout option:

a query, the server silent: still pending after 10 s
the next query            : still pending after 3 s

With this change:

a query, the server silent: rejected ANSWER_TIMEOUT
the next query            : resolved
import net from 'node:net'
import postgres from 'postgres'

// Server and credentials from PGHOST, PGPORT, PGUSER, PGPASSWORD and PGDATABASE.
// A relay in front of the server; silence() makes the connections open now drop every byte both ways while
// both sockets stay open, as when the server stops answering and its host and the network stay up.
const pairs = new Set()
const relay = net.createServer(client => {
  const server = net.connect(process.env.PGPORT || 5432, process.env.PGHOST || 'localhost')
      , pair = { silent: false }
  pairs.add(pair)
  client.on('data', x => pair.silent || server.write(x))
  server.on('data', x => pair.silent || client.write(x))
  client.on('error', () => server.destroy()).on('close', () => server.destroy())
  server.on('error', () => client.destroy()).on('close', () => client.destroy())
})
await new Promise(r => relay.listen(0, '127.0.0.1', r))
const silence = () => pairs.forEach(x => x.silent = true)

const settle = (p, ms) => Promise.race([
  p.then(() => 'resolved', e => 'rejected ' + e.code),
  new Promise(r => setTimeout(r, ms, `still pending after ${ ms / 1000 } s`))
])

const sql = postgres({ host: '127.0.0.1', port: relay.address().port, max: 1, keep_alive: 1, answer_timeout: 2 })
await sql`select 1`
silence()
console.log('a query, the server silent:', await settle(sql`select 1`, 10000))
console.log('the next query            :', await settle(sql`select 1`, 3000))
process.exit(0)

@GrahamCampbell
GrahamCampbell marked this pull request as draft November 1, 2026 14:19
@GrahamCampbell

Copy link
Copy Markdown
Contributor Author

I've rebased, and pushed a correction.

@GrahamCampbell
GrahamCampbell marked this pull request as ready for review November 1, 2026 14:50
@porsager

porsager commented Nov 1, 2026

Copy link
Copy Markdown
Owner

Thanks Graham!

I've been looking closer at this case and some of the pitfalls, and I've gone ahead and added query_timeout instead to have a client side limit for each query. If the timeout is reached we send a cancel for it and it rejects with QUERY_TIMEOUT. cancel_timeout (is 5s by default) covers the silen server case. If a cancel, whether from query_timeout, .cancel() or .signal(), gets no answer within that time, the connection is closed.

The queries reject with CANCEL_UNANSWERED as the cause, since whether they ran is unknown, and the pool reconnects.
This way a long query that sends nothing isn’t mistaken for a dead server, and the server is asked to stop the query instead of just having its connection dropped.

Wouldn't that also cover your case here?

@porsager

porsager commented Nov 2, 2026

Copy link
Copy Markdown
Owner

This is now in master so you can check if it covers your need too.

@GrahamCampbell

Copy link
Copy Markdown
Contributor Author

Thanks, that covers the case I opened this for. With query_timeout set, a query on a connection whose server goes silent settles at query_timeout plus cancel_timeout and the pool moves on to a new connection, with or without TLS, and asking the server to stop a query that is only slow is better than dropping its connection, as you say. I'm happy to close this in favour of it.

While checking it against master I came across four things you may want to look at before it's released.

The promise from the cancel request is dropped when query_timeout fires, and when the signal given to .signal() aborts. If the cancel's own connection fails, nothing handles the rejection, and with Node's defaults the process exits before the query has rejected with QUERY_TIMEOUT. That failure is most likely in exactly the case query_timeout is for: with ssl on, the cancel connection waits for the answer to its SSLRequest, so a server that accepts connections and then says nothing is enough, and with or without ssl so is a connect that is refused or never completes. Your test "query_timeout rejects a query whose server stops answering, and the next query gets a new connection" fails with a stray CONNECT_TIMEOUT once ssl: 'require' is added to it. Through .signal() the rejection comes out of the signal's event listener as an uncaught exception, so an unhandledRejection handler doesn't help there either.

Now that sql.begin sends BEGIN together with the first query, a cancel that lands on the BEGIN makes it fail while the queries after it still run, outside any transaction, so each of them commits on its own, and sql.begin then rejects with 57014. The caller is told the transaction failed while some or all of its writes are in. With a second connection calling pg_cancel_backend in a loop on a connection running transactions of two inserts, 4 and 29 of 3000 transactions were rejected at BEGIN with rows written, a few of them with only one of the two; on 4.0.0 there were none. Any cancel can do this, and the next point makes it reachable by query_timeout on its own.

A query that times out while it is pipelined behind a slower one gets its cancel when it reaches the head of the connection, and by then it has usually run already, so the cancel stops whatever runs next on that backend, often another caller's query, while the timed out query resolves with its rows rather than with QUERY_TIMEOUT. In a loop of a slow query, a fast one pipelined behind it that times out while it waits, and a third query, the third was stopped every time (360 of 360 over a few variations). That happens far more often than the README's "a cancel sent just as a query finishes" suggests.

The type read that runs when a query first needs a type doesn't go through query_timeout, so a server that goes silent during it is bounded by nothing. Each typed query then fails with CANCEL_UNANSWERED and takes its own healthy connection down with it, for as long as the reading connection stays open, and with eager_types the queries pipelined behind the read wait forever. The same goes for a timed query pipelined behind one that isn't timed, such as a query after a cursor inside sql.begin: its cancel waits for a turn that never comes, so cancel_timeout never starts.

I can send the tests I used for any of these if that helps.

Reproduction: the dropped cancel promise

Against a PostgreSQL with ssl = on on localhost:5432, through a relay that goes silent and then accepts new connections without answering them. On master the process exits with code 1 about 6 seconds in (1 s of query_timeout and the default 5 s of cancel_timeout), printing only the error below; neither "rejected" nor "still running" is printed.

Error: write CONNECT_TIMEOUT localhost:41121
    at Timeout.<anonymous> (file:///work/src/startup.js:237:69)
    at listOnTimeout (node:internal/timers:585:17)
    at process.processTimers (node:internal/timers:521:7) {
  code: 'CONNECT_TIMEOUT',
  errno: 'CONNECT_TIMEOUT',
  address: 'localhost',
  port: 41121
}
import net from 'net'
import postgres from 'postgres'

let silent = false
const relay = net.createServer(client => {
  client.on('error', () => {})
  if (silent)
    return

  const server = net.connect(5432, 'localhost')
  server.on('error', () => {})
  client.on('data', x => silent || server.write(x))
  server.on('data', x => silent || client.write(x))
  client.on('close', () => server.destroy())
  server.on('close', () => client.destroy())
})
await new Promise(r => relay.listen(0, 'localhost', r))

const sql = postgres({ host: 'localhost', port: relay.address().port, ssl: 'require', query_timeout: 1 })
await sql`select 1`
silent = true

const start = Date.now()
await sql`select 1`.then(
  () => console.log('resolved'),
  e => console.log('rejected', e.code, e.cause && e.cause.code, 'after', Date.now() - start, 'ms')
)
console.log('still running')
await sql.end({ timeout: 0 })
relay.close()
Reproduction: a cancel on the pipelined BEGIN

Against a local PostgreSQL. Every transaction sql.begin rejects should have written nothing. Two runs on master:

'rejected 57014 (begin ), 2 rows written': 3,  'rejected 57014 (begin ), 1 rows written': 1
'rejected 57014 (begin ), 2 rows written': 27, 'rejected 57014 (begin ), 1 rows written': 2

On 4.0.0 every rejected transaction had written nothing.

import postgres from 'postgres'

const sql = postgres({ max: 1, connection: { application_name: 'victim' } })
    , other = postgres({ max: 1 })

await other`drop table if exists begin_cancel`
await other`create table begin_cancel (i int)`

let spraying = true
const spray = (async() => {
  while (spraying)
    await other`select pg_cancel_backend(pid) from pg_stat_activity where application_name = 'victim'`
})()

const outcomes = {}
for (let i = 0; i < 3000; i++) {
  const told = await sql.begin(async sql => {
    await sql`insert into begin_cancel values (${ i })`
    await sql`insert into begin_cancel values (${ i })`
  }).then(() => 'resolved', e => 'rejected ' + e.code + ' (' + e.query + ')')
  const [{ n }] = await other`select count(*)::int as n from begin_cancel where i = ${ i }`
  const key = told + ', ' + n + ' rows written'
  outcomes[key] = (outcomes[key] || 0) + 1
}

spraying = false
await spray
console.log(outcomes)
await other`drop table begin_cancel`
await sql.end()
await other.end()

@porsager

porsager commented Nov 2, 2026

Copy link
Copy Markdown
Owner

Fantastic feedback and repros! Thank you!

@GrahamCampbell
GrahamCampbell deleted the answer-timeout branch November 2, 2026 18:27
@porsager

porsager commented Nov 2, 2026

Copy link
Copy Markdown
Owner

Thanks Graham, all four were real, and the reproductions made them quick to pin down - pushed fixes now

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants