Skip to content

REQs hang once the DB pools fill: a REQ cursor can hold its pooled connection forever #1243

Done

Description

@SkanderHelali

Version: 3.16.0 (Docker Compose, Postgres 16), knex 3.2.9, pg-query-stream 4.3.0

What happens

After a few days a growing share of REQs never get EOSE: the client gets the AUTH challenge and then nothing. The relay logs KnexTimeoutError: Knex: Timeout acquiring a connection. The pool is probably full. from worker:web-socket-adapter. A restart clears it, then it builds up again. On our relay 15 of 20 test REQs hung by then.

What Postgres shows

Backends that sit in state = 'active', wait_event = 'ClientRead' for days, all running the REQ query:

select * from "events" where ("event_pubkey" in ($1)) and "event_kind" in ($2) order by "event_created_at" DESC, "event_id" asc limit $3

We had 45 of them after four days; they arrive in bursts. That is the state of a pg cursor that was submitted and then never read or closed. Opening a pg-cursor and not reading it gives the same row. Each one holds a pooled knex connection, and once a worker's pool is full every REQ it handles hangs.

To check for it:

select count(*) from pg_stat_activity
where datname = current_database() and state = 'active'
  and wait_event = 'ClientRead' and now() - query_start > interval '5 minutes';

Cause, as far as we got

SubscribeMessageHandler.fetchAndSend pipes the DB stream straight into the socket, and sendEvent awaits waitForWritable(), so the cursor is read only as fast as the client takes events. If that pipeline stalls and is never aborted, the cursor stays open and the connection is never released. We did not pin down which client behaviour leaves it stalled without an abort. A client that resets the connection mid-stream did not reproduce it: that path is aborted and cleaned up.

The fix we run

Read the whole result into an array (through pipeline(), so error and close handling stay the same), then send from Readable.from(rows) under the same abort signal. The connection goes back as soon as the query ends, however slow the client is. Results are bounded by the filter limit. The regression test below passes with the change and times out without it; the existing handler, adapter and repository tests pass (670).

Trade-off: a stalled client's rows stay in memory until the heartbeat closes its socket.

diff --git a/src/handlers/subscribe-message-handler.ts b/src/handlers/subscribe-message-handler.ts
index 0b910e78..7cf4a349 100644
--- a/src/handlers/subscribe-message-handler.ts
+++ b/src/handlers/subscribe-message-handler.ts
@@ -1,5 +1,5 @@
 import { anyPass, equals, isNil, map, omit, propSatisfies, uniqWith } from 'ramda'
-import { addAbortSignal } from 'stream'
+import { addAbortSignal, Readable, Writable } from 'stream'
 import { pipeline } from 'stream/promises'
 import { IWebSocketAdapter } from '../@types/adapters'
 import { Factory, Pubkey } from '../@types/base'
@@ -374,8 +374,26 @@ export class SubscribeMessageHandler implements IMessageHandler, IAbortable {
     const abortableFindEvents = addAbortSignal(this.abortController.signal, findEvents)
 
     try {
+      // Read the whole result before sending anything,
+      // so the pooled DB connection goes back at once whatever the client does. Piping
+      // the DB cursor straight into the socket held the connection while sends waited on
+      // the client; abandoned cursors sat open for days ("active", ClientRead) until a
+      // worker's pool was full and every REQ on it hung. Results are bounded by the
+      // filter limit, so buffering them is cheap. pipeline() keeps the existing error and
+      // close handling for the DB stream.
+      const rows: unknown[] = []
       await pipeline(
         abortableFindEvents,
+        new Writable({
+          objectMode: true,
+          write(row, _encoding, callback) {
+            rows.push(row)
+            callback()
+          },
+        }),
+      )
+      await pipeline(
+        addAbortSignal(this.abortController.signal, Readable.from(rows)),
         streamFilter(propSatisfies(isNil, 'deleted_at')),
         streamMap(toNostrEvent),
         streamFilter(isTagUnexpired),
diff --git a/test/unit/handlers/subscribe-message-handler.spec.ts b/test/unit/handlers/subscribe-message-handler.spec.ts
index 72e320a9..f512f374 100644
--- a/test/unit/handlers/subscribe-message-handler.spec.ts
+++ b/test/unit/handlers/subscribe-message-handler.spec.ts
@@ -835,6 +835,24 @@ describe('SubscribeMessageHandler', () => {
       expect(eventRepositoryFindByFiltersStub).to.have.been.calledOnceWithExactly(filters)
     })
 
+    // The DB stream is read to its end before the
+    // first send, so a client that never drains cannot keep the pooled connection.
+    it('reads the DB stream to the end even when the client never becomes writable', async () => {
+      isClientSubscribedToEventStub.returns(always(true))
+      ;(webSocket.waitForWritable as Sinon.SinonStub).returns(new Promise(() => undefined))
+      const ended = new Promise((resolve) => stream.once('end', resolve))
+
+      void (handler as any).fetchAndSend(subscriptionId, filters)
+
+      for (let i = 0; i < 500; i++) {
+        stream.write(toDbEvent({ ...event, id: i.toString(16).padStart(64, '0') }))
+      }
+      stream.end()
+
+      await ended
+      expect(stream.readableEnded).to.equal(true)
+    })
+
     it('passes an uncapped defaultLimit to the repository for a peer', async () => {
       isClientSubscribedToEventStub.returns(always(false))
       ;(webSocket.getPeerPubkey as Sinon.SinonStub).returns('a'.repeat(64))

Happy to open a PR if this direction works for you.

Activity

  1. AgrimTawani commented on Nov 28, 2026

    @AgrimTawani
    Contributor

    Hey @cameri, I'd like to take this on next.

    My approach would be:

    • Write a failing test first: a client that never drains must not keep the pooled connection
    • Release the cursor as soon as the query finishes (buffering the result up to the filter limit), and abort it if the send stalls
    • Add a test for the stalled-client memory trade-off, and run the handler, adapter and repository tests
  2. cameri commented on Nov 28, 2026

    @cameri
    Owner

    Assigned to @AgrimTawani

  3. AgrimTawani commented on Nov 28, 2026

    @AgrimTawani
    Contributor

    Hey @cameri, the fix for this is ready on AgrimTawani:fix/1243-req-cursor-release (one commit, 9f8c166, against main):

    • Root cause: an aborted REQ destroyed knex's stream before knex held a connection (the __knexUid TypeError worker.ts swallows) or before pg had submitted the queued cursor, so the cursor ran anyway and its backend sat active/ClientRead holding the connection
    • Fix: a small abortableQueryStream wrapper ends the subscription at once but closes the cursor only once it is safe, and an already-aborted REQ no longer starts a query; peer feeds stay streamed (no extra buffering)
    • Tests: new unit cases fail on the old code; against Postgres 16 with 600 randomly aborted REQs the old path fills the pool and the new one leaves every connection free; lint, build:check and 3601 unit tests pass
  4. SkanderHelali commented on Nov 28, 2026

    @SkanderHelali
    Author

    Confirming 3.17.0 fixes this for us in production.

    On 3.16.0 we had a local workaround that read the DB stream to the end before sending. The leak came back anyway: after a restart, a new backend was stuck active / ClientRead within about 30 seconds. The workaround didn't cover the abort-before-submit window that #1271 describes.

    Since upgrading to 3.17.0 we've seen no stuck backends in the first ~20 minutes, with clients still aborting mid-REQ.

    For anyone else chasing this, the leak had a log signature for us: bursts of TypeError: Cannot read properties of null (reading 'name') from pg's Client._handleParseComplete. The stuck backend's query_start matched the last of those errors to the millisecond, and none have appeared since the upgrade.

    Thanks @AgrimTawani for the fix and the clear write-up.

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

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions