Skip to content

WebSocket upgrades fail intermittently under pm2: ERR_HTTP_SOCKET_ASSIGNED (@pm2/io httpMetrics vs @fastify/websocket) #545

Open

Description

@melvincarvalho

Symptom

On a production JSS (0.0.204, node v22.21.1, Ubuntu) running under pm2, WebSocket upgrades to /.webrtc fail in intermittent bursts. Clients see either a failed connect or — worse — a half-open socket (TLS front returns 101, but the inner upgrade has already died, so the client gets silence: no messages, no error). Fresh-socket clients (curl, Node WebSocket) almost always succeed; browsers holding keep-alive connections to the same host intermittently hit it.

Logs

{"level":40,"err":{"type":"Error","message":"ServerResponse has an already assigned socket",
 "stack":"Error [ERR_HTTP_SOCKET_ASSIGNED]: ServerResponse has an already assigned socket
    at ServerResponse.assignSocket (node:_http_server:291:11)
    at Server.onUpgrade (.../node_modules/@fastify/websocket/index.js:56:19)
    at Server.emit (node:events:531:35)
    at Server.<anonymous> (.../lib/node_modules/pm2/node_modules/@pm2/io/build/main/metrics/httpMetrics.js:153:37)
    at onParserExecuteCommon (node:_http_server:977:14)",
 "code":"ERR_HTTP_SOCKET_ASSIGNED"},"msg":"websocket upgrade failed"}

Bursts of these correlate exactly with client-observed dead signaling connections.

Analysis

pm2's @pm2/io httpMetrics instrumentation wraps the HTTP server's events and sits in the upgrade path ahead of @fastify/websocket's onUpgrade. "Already assigned socket" points at upgrades arriving on reused keep-alive sockets (a connection that previously served a normal HTTP response), where the wrapper's ServerResponse handling collides with the upgrade's assignSocket. That matches the observed pattern: fresh sockets fine, browser keep-alive connections intermittent.

Possibly aggravated in this deployment by a pm2 daemon/CLI version mismatch (in-memory 6.0.14 vs local 4.5.6), so the injected @pm2/io came from a different pm2 than the one managing the process.

Suggested directions

  • register the upgrade handler so it runs ahead of (or is resilient to) external 'request'/'upgrade' instrumentation — e.g. guard onUpgrade against an already-assigned socket and destroy/retry instead of throwing through
  • document pm2 deployment guidance for websocket-bearing instances (metrics-off configuration, or systemd as the recommended supervisor when --webrtc/--tunnel/notifications are enabled)
  • a health probe: the /.webrtc route could expose a trivial HTTP GET response (instead of 404) so operators can distinguish "flag off" from "upgrade path broken"

Environment

  • jss 0.0.204 under pm2 (fork mode), node v22.21.1
  • mitigation being applied operationally: pm2 update + restart; will report recurrence here

Activity

  1. melvincarvalho commented on Oct 8, 2026

    @melvincarvalho
    ContributorAuthor

    Revisiting this with a production log in hand: the root cause is not pm2. @fastify/websocket is registered once per WebSocket feature, in separate encapsulated contexts, so the HTTP server ends up with N upgrade listeners and every upgrade logs N-1 of these warnings.

    Evidence

    Listener count on fastify.server after ready(), current gh-pages (0.0.220):

    features enabled server.listenerCount('upgrade')
    notifications 1
    notifications + nostr 2
    notifications + nostr + webrtc + tunnel 4
    + terminal 5
    import { createServer } from './src/server.js';
    const f = createServer({ root: '/tmp/jss-root', port: 0, logger: false,
      notifications: true, nostr: true, webrtc: true, tunnel: true });
    await f.ready();
    console.log(f.server.listenerCount('upgrade')); // 4

    A 9-month log from an instance with notifications + nostr + webrtc + tunnel contains ~790k websocket upgrade failed lines (28% of the whole log), i.e. ~3 per real connection. They are emitted for successful upgrades too, so bursts of them only indicate that connections were being opened; they cannot be used as a signal for the half-open-socket symptom described above (that part may be a separate issue).

    Mechanism

    @fastify/websocket does two things per registration: fastify.server.on('upgrade', onUpgrade) on the single shared Node server, and fastify.decorate('websocketServer', wss) on the context it was registered in. JSS registers it in six places:

    • src/notifications/index.js:31 — unconditional
    • src/nostr/relay.js:233, src/webrtc/index.js:78, src/terminal/index.js:39, src/tunnel/index.js:98, src/plugins.js:424 — guarded by if (!fastify.websocketServer)

    Each of those plugins is mounted with a plain fastify.register(plugin) in src/server.js, which creates an encapsulated child. The websocketServer decorator set inside the notifications context is not visible from the tunnel/webrtc/… contexts, so every guard sees "not registered" and registers again.

    On an upgrade, Node calls all listeners in order. The first one does rawResponse.assignSocket(socket) and routes; the socket now has _httpMessage set, so every later listener's assignSocket throws ERR_HTTP_SOCKET_ASSIGNED, which @fastify/websocket catches and logs as websocket upgrade failed. The connection itself succeeds via the first listener.

    Fix

    Register @fastify/websocket once at the root in src/server.js, before any of the WebSocket-bearing plugins (conditionally on notificationsEnabled || liveReloadEnabled || nostrEnabled || webrtcEnabled || terminalEnabled || tunnelEnabled || pluginEntries.length). Root decorators and the onRoute hook are inherited by all children, so the five existing guards then skip correctly and { websocket: true } routes in child plugins keep working. The only other change is src/notifications/index.js using the same guard instead of registering unconditionally. No code reads fastify.websocketServer or .clients, so sharing a single instance is safe. This is also the usage the @fastify/websocket README recommends.

  2. added a commit that references this issue on Oct 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    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