Skip to content

fix(ws): leave upgrade requests for other paths to other listeners - #18501

Merged
kamilmysliwiec merged 3 commits into
nestjs:masterfrom
mtnaskari:fix/ws-shared-upgrade
Nov 12, 2026
Merged

kamilmysliwiec merged 3 commits into
nestjs:masterfrom
mtnaskari:fix/ws-shared-upgrade

Conversation

@mtnaskari

@mtnaskari mtnaskari commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

PR Checklist

Please check if your PR fulfills the following requirements:

PR Type

What kind of change does this PR introduce?

  • Bugfix
  • Feature
  • Code style update (formatting, local variables)
  • Refactoring (no functional changes, no api changes)
  • Build related changes
  • CI related changes
  • Other... Please describe:

What is the current behavior?

When a WsAdapter gateway shares the application's HTTP server, the adapter's upgrade listener destroys the socket of every upgrade request whose path does not match one of its gateways. If another listener on the same server owns that path, the connection is gone before that listener can handle it.

A common case is GraphQL subscriptions next to a WsAdapter gateway. @nestjs/graphql routes /graphql upgrades from its own upgrade listener. When the WsAdapter listener runs first, the client gets socket hang up (ECONNRESET) and the subscription never opens. @nestjs/graphql already avoids this on its side: it closes an unclaimed socket only when it is the server's single upgrade listener.

Issue Number: N/A

What is the new behavior?

For a path that none of its gateways serves, the WsAdapter listener now:

  • closes the socket right away when it is the server's only upgrade listener, so the previous behavior is unchanged for applications without other listeners;
  • otherwise leaves the socket to the other listeners, and closes it once unclaimedUpgradeTimeout (1000 ms by default) has passed with nothing written to it since the upgrade. A listener that claims a socket answers the handshake, so a socket that nothing has been written to by then is one that nobody claimed. The count of bytes written covers the whole connection, so it is compared against its value at the upgrade, which on a keep-alive connection already includes the responses to earlier requests. engine.io handles the same case this way. Without this, such a socket would stay open until the client hangs up, since the HTTP server's timeouts no longer apply after upgrade;
  • adds an error listener that destroys the socket, because Node removes its own listeners before emitting upgrade, and a connection reset on a socket nobody claims would otherwise raise an unhandled error event.

unclaimedUpgradeTimeout is a new WsAdapterOptions setting. An application whose other listener answers the handshake late, for example after a slow authentication, can raise it, or set it to 0 to leave such sockets to the other listeners entirely:

app.useWebSocketAdapter(new WsAdapter(app, { unclaimedUpgradeTimeout: 5000 }));

Tests cover these cases:

  • an upgrade for /graphql handled by a second WebSocketServer on the same server opens;
  • an upgrade for an unknown path is still closed when the adapter is the only listener;
  • with another listener present, an unclaimed socket is closed after 1000 ms, after a custom unclaimedUpgradeTimeout, and never when it is 0, while a socket that the other listener answered is kept;
  • the same holds for a socket that arrives with bytes already written, as on a keep-alive connection.

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

As in @nestjs/graphql, a socket that another listener sees but does not claim is left to that listener until the timeout. The previous behavior is kept for a gateway on its own port, since the adapter's server has no other upgrade listeners.

Results with Node.js 22: the full build, prettier and oxlint pass, and the platform-ws and websockets test suites pass with 213 tests. The test for a socket that arrives with bytes already written fails with the previous check and passes with this one.

@kamilmysliwiec kamilmysliwiec left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, the fix is right: today the adapter destroys sockets that another upgrade listener has just claimed, so GraphQL subscriptions on the same server break whichever listener runs first.

One gap: when another listener is present, an upgrade for a path that no listener serves is now closed by nobody. @nestjs/graphql follows the same rule, so with both installed such a socket stays open until the client hangs up. The HTTP server's timeouts no longer apply after upgrade, and the gateways never see the socket.

Could you close it after a short delay when nothing has been written to it, as engine.io does for the same case? Something like:

if (!isRequestDelegated) {
  socket.on(ERROR_EVENT, () => socket.destroy());
  if (httpServer.listenerCount('upgrade') <= 1) {
    socket.destroy();
  } else {
    // A listener that claims the socket answers the handshake, so a socket
    // nothing has been written to by then is one that nobody claimed.
    setTimeout(() => {
      if (socket.writable && socket.bytesWritten <= 0) {
        socket.destroy();
      }
    }, 1000).unref();
  }
}

plus a test where a second listener ignores the path and the socket gets closed (fake timers are fine).

if (!isRequestDelegated) {
socket.destroy();
socket.on(ERROR_EVENT, () => socket.destroy());
if (httpServer.listenerCount('upgrade') <= 1) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@kamilmysliwiec about the 1s timer you suggested above: upgrade listener that authenticates before handleUpgrade (pattern from ws README, "Client authentication") writes nothing until auth is done, so when auth takes longer than delay (cold db, remote jwks) adapter would destroy socket that other listener alredy claimed

httpServer.on('upgrade', (req, socket, head) => {
  socket.on('error', onSocketError);
  authenticate(req, (err, client) => { // > 1s
    wss.handleUpgrade(req, socket, head, ws => wss.emit('connection', ws, req, client));
  });
});

engine.io has same trade-off and exposes it as destroyUpgrade / destroyUpgradeTimeout, maybe worth same knob in WsAdapterOptions so apps with slow upgrade auth can raise or turn it off

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for pointing this out. I have made the delay configurable through a new unclaimedUpgradeTimeout option in WsAdapterOptions, following the approach engine.io takes with destroyUpgradeTimeout. It defaults to 1000 ms, an application with a slow authentication step can raise it, and setting it to 0 leaves such sockets to the other listeners entirely.

When another upgrade listener is present, an upgrade for a path that no listener serves was left open until the client hung up. Close it once "unclaimedUpgradeTimeout" (1000 ms by default) has passed with nothing written to it, as engine.io does. A listener that answers the handshake late, for example after a slow authentication, can be given more time, or the timer can be turned off with 0.
@mtnaskari

Copy link
Copy Markdown
Contributor Author

Thank you for the review, @kamilmysliwiec. I have pushed the change you suggested: when another upgrade listener is present, a socket for a path that no listener serves is now closed after a delay if nothing has been written to it. I added tests with fake timers for a socket that no listener claims and for one that the other listener answered.

To address the concern raised in the review thread about listeners that authenticate before answering the handshake, the delay is configurable through a new unclaimedUpgradeTimeout option in WsAdapterOptions. It defaults to 1000 ms, and 0 turns the timer off. I would be glad to remove the option and keep a fixed delay if you prefer to keep the API unchanged.

@kamilmysliwiec kamilmysliwiec left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, the option is fine by me: it covers the slow-authentication case @thekhegay raised, the same way engine.io does.

One problem with the check I suggested, sorry: bytesWritten counts everything written on the connection, not just the handshake. A client that sends a plain request first and then an upgrade on the same keep-alive connection arrives with bytesWritten already above 0 (124 bytes after a short response in my test), so the timer never closes its socket. Comparing against the value at upgrade time covers that:

const writtenBeforeUpgrade = (socket as Socket).bytesWritten;
setTimeout(() => {
  if (socket.writable && (socket as Socket).bytesWritten <= writtenBeforeUpgrade) {
    socket.destroy();
  }
}, this.unclaimedUpgradeTimeout).unref();

A TLS handshake doesn't count towards bytesWritten (0 on a fresh HTTPS connection), so HTTPS needs nothing else. Could you add a test for a socket that arrives with bytes already written?

bytesWritten counts everything sent on the connection, so on a keep-alive connection it already includes the responses to earlier requests and the timer never closed such a socket. Compare against the count at upgrade time instead.
@mtnaskari

Copy link
Copy Markdown
Contributor Author

Thank you for catching that, @kamilmysliwiec. I have pushed the change: the timer now compares bytesWritten against its value at upgrade time, as you suggested. I added tests for a socket that arrives with bytes already written, both when no listener claims it, where it is now closed, and when the other listener answers the handshake, where it is kept. I also changed the existing test for an answered socket so that the handshake response is written after the upgrade rather than before it. The build passes, and the platform-ws and websockets test suites pass with 213 tests.

@kamilmysliwiec kamilmysliwiec left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the quick turnaround.

@kamilmysliwiec
kamilmysliwiec merged commit ef7bc16 into nestjs:master Nov 12, 2026
2 checks passed
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.

3 participants