Skip to content

socket-mode: Slack's disconnect (refresh_requested) leaves the app without a connection for 9–12 s #2767

Closed

Description

@matzhave

Package

@slack/socket-mode

SDK Version

@slack/socket-mode@3.1.0 (the code path is unchanged on main)

Node.js Version

v26.10.0 in production, v26.8.1 for the repro

Operating System

Ubuntu 26.04 (production), macOS (repro)

Steps to Reproduce

The script below stands in for Slack with Node built-ins only: it hands out the WebSocket URL, says hello and answers pings. Like Slack in production, after {"type":"disconnect","reason":"refresh_requested"} it answers nothing more on that connection and leaves it open. --rfc makes it complete the close handshake instead.

refresh-gap.mjs (npm i @slack/socket-mode@3.1.0 && node refresh-gap.mjs)
// Repro: the gap @slack/socket-mode leaves when Slack refreshes a connection.
//   npm i @slack/socket-mode@3.1.0 && node refresh-gap.mjs
// A local stand-in for Slack (Node built-ins only) hands out the WebSocket
// URL, says hello and answers pings. Like Slack in production, once it has
// sent {"type":"disconnect","reason":"refresh_requested"} it answers nothing
// more on that connection and leaves it open. Pass --rfc to have it complete
// the close handshake instead, as RFC 6455 describes.
import { createHash } from "node:crypto";
import { createServer } from "node:http";
import { SocketModeClient } from "@slack/socket-mode";

const rfc = process.argv.includes("--rfc");
const began = performance.now();
const at = () => `${(performance.now() - began).toFixed(0).padStart(6)}ms`;

const frame = (opcode, payload) =>
  Buffer.concat([Buffer.from([0x80 | opcode, payload.length]), payload]);
const links = [];
const server = createServer((_req, res) => {
  res.setHeader("content-type", "application/json");
  res.end(JSON.stringify({ ok: true, url: `ws://127.0.0.1:${server.address().port}/link` }));
});
server.on("upgrade", (req, socket) => {
  const accept = createHash("sha1")
    .update(req.headers["sec-websocket-key"] + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11")
    .digest("base64");
  socket.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${accept}\r\n\r\n`);
  socket.write(frame(0x1, Buffer.from('{"type":"hello","num_connections":1}')));
  const link = { socket, refreshed: false };
  links.push(link);
  console.log(at(), `slack: connection ${links.length} opened`);
  let buffered = Buffer.alloc(0);
  socket.on("data", (chunk) => {
    buffered = Buffer.concat([buffered, chunk]);
    while (buffered.length >= 6) {
      const opcode = buffered[0] & 0x0f;
      const length = buffered[1] & 0x7f; // short control frames only here
      if (buffered.length < 6 + length) return;
      const payload = Buffer.from(buffered.subarray(6, 6 + length)).map((b, i) => b ^ buffered[2 + (i % 4)]);
      buffered = buffered.subarray(6 + length);
      if (link.refreshed && !rfc) continue; // like Slack: silence after the refresh
      if (opcode === 0x9) socket.write(frame(0xa, payload)); // pong
      if (opcode === 0x8) socket.end(frame(0x8, Buffer.from([0x03, 0xe8]))); // close
    }
  });
  socket.on("error", () => {});
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));

const client = new SocketModeClient({
  appToken: "xapp-test",
  clientOptions: { slackApiUrl: `http://127.0.0.1:${server.address().port}/api/` },
});
for (const event of ["connected", "reconnecting"]) client.on(event, () => console.log(at(), `client: ${event}`));
await client.start();
await new Promise((resolve) => setTimeout(resolve, 1000));

console.log(at(), 'slack: {"type":"disconnect","reason":"refresh_requested"}');
const refreshed = performance.now();
links[0].refreshed = true;
links[0].socket.write(frame(0x1, Buffer.from('{"type":"disconnect","reason":"refresh_requested"}')));
await new Promise((resolve) => client.once("connected", resolve));
console.log(at(), `no connection for ${((performance.now() - refreshed) / 1000).toFixed(1)} s`);
process.exit(0);
$ node refresh-gap.mjs
    15ms slack: connection 1 opened
    17ms client: connected
  1020ms slack: {"type":"disconnect","reason":"refresh_requested"}
[WARN]  socket-mode:SlackWebSocket:1 A pong wasn't received from the server before the timeout of 5000ms!
 11688ms client: reconnecting
 11696ms slack: connection 2 opened
 11697ms client: connected
 11697ms no connection for 10.7 s

$ node refresh-gap.mjs --rfc
  1019ms slack: {"type":"disconnect","reason":"refresh_requested"}
  6025ms client: reconnecting
  6032ms slack: connection 2 opened
  6033ms no connection for 5.0 s

Expected Result

No gap, as in python-slack-sdk: on disconnect, open the next connection first and close the old one once the new one has said hello. Slack's Socket Mode docs recommend this ("generate an additional connection before the restart occurs"; up to 10 connections are allowed).

At the very least, a refresh Slack asked for should reconnect at once, not after clientPingTimeout.

Actual Result

In production, against Slack, every ~5 hours (approximate_connection_time ≈ 18,000 s) we see the same sequence as above: A pong wasn't received …, 5 s later reconnecting, then connected. For 9–12 s the app has no connection; interactive payloads (button clicks) in that window fail for the user.

Three parts add up:

  1. SocketModeClient.onWebSocketMessage handles disconnect with this.websocket?.disconnect(): the old connection is closed before a new one is opened.
  2. Closing waits for the peer to close TCP. undici's WebSocket never does that itself and Slack doesn't either, so the connection stays in CLOSING until the pong monitor gives up after 3.3–6.7 s (same root cause as SocketModeClient.disconnect() takes ~5 seconds to close on 3.0.1 #2752).
  3. The close handler then goes through delayReconnectAttempt, which increments numOfConsecutiveReconnectionFailures and waits clientPingTimeout (5 s) before start(), as if the refresh Slack asked for were a failure. That is the 5.0 s left with a peer that closes properly (--rfc).

Also, envelopes Slack still sends on the old connection after the close frame are dropped by undici (readyState is CLOSING).

Suggested fix

  • On disconnect, start the next SlackWebSocket (retrieveWSSURL() + connect()) while the old one stays open; once the new one has received hello, close the old one and terminate it if the peer has not closed it shortly after (cf. SocketModeClient.disconnect() takes ~5 seconds to close on 3.0.1 #2752).
  • Don't count a refresh Slack asked for as a reconnection failure: no delayReconnectAttempt for it.

Related: #2752 (disconnect() waits for the pong monitor), #2656 / #2657 (unhandled rejection when disconnect() races a pending reconnect; it also bites apps that try to work around this by managing clients themselves).

Workaround we use

Clients with autoReconnectEnabled: false; the app opens a second client 4 hours after each connection (before Slack's 5-hour refresh), switches to it after hello, then closes the old one, and reconnects at once on unexpected drops. Two more things we had to handle on the way:

  • With the default retryConfig of the internal WebClient (100 retries), a client given up on keeps retrying apps.connections.open in the background and connects much later. We pass clientOptions: { retryConfig: { retries: 0 }, timeout: 10_000 } and retry ourselves.
  • disconnect() while start() is still waiting for apps.connections.open emits disconnected, but start() goes on and connects afterwards (its disconnected listener is only registered after the URL arrives). We close such a client again on connected.

Activity

  1. added
    bugM-T: A confirmed bug report. Issues are confirmed when the reproduction steps are documented
    pkg:socket-modeapplies to `@slack/socket-mode`
    on Nov 5, 2026
  2. WilliamBergamin commented on Nov 5, 2026

    @WilliamBergamin
    Contributor

    Thanks for the self-contained repro, it made this quick to confirm 🙏

    Reproduced locally on @slack/socket-mode@3.1.1 (latest; nothing since 3.1.0 touches this path), Node v26.10.0, using your refresh-gap.mjs as-is:

    Fake peer behavior after refresh_requested Gap without a connection
    Silent, connection left open (like Slack) 10.7 s (pong timeout warning, then reconnect)
    Completes the close handshake (--rfc) 5.0 s

    Results were identical across repeated runs. Your breakdown holds up against the code on main:

    1. SocketModeClient.onWebSocketMessage handles disconnect with this.websocket?.disconnect(), so the old connection closes before a new one is requested.
    2. That close waits on the peer's handshake, and with a silent peer only the client pong watchdog ends it. This is the same root cause as SocketModeClient.disconnect() takes ~5 seconds to close on 3.0.1 #2752.
    3. The close handler then routes through delayReconnectAttempt, which increments numOfConsecutiveReconnectionFailures and sleeps clientPingTimeout * failures (5 s) before start(). That accounts for the whole 5.0 s left in the --rfc case.

    For comparison, python-slack-sdk's built-in client handles disconnect with connect_to_new_endpoint(force=True): it issues a new WSS URL and connects the new session first, then closes the old one.

    The direction you suggest makes sense to us:

    • On a server-sent disconnect, open the replacement connection first and retire the old one once the new one is up. The old one gets a short handshake timeout and is then terminated (see SocketModeClient.disconnect() takes ~5 seconds to close on 3.0.1 #2752).
    • Don't treat a refresh Slack asked for as a reconnection failure, so no delayReconnectAttempt backoff for it.

    Labeling this as a bug.

  3. WilliamBergamin commented on Nov 10, 2026

    @WilliamBergamin
    Contributor

    Fixed by #2821 (shipped as part of #2820): on a warning or refresh_requested disconnect, the client now opens the replacement connection before closing the old one, so there's no gap. This will go out in the next @slack/socket-mode release.

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

    auto-triage-skipbugM-T: A confirmed bug report. Issues are confirmed when the reproduction steps are documentedpkg:socket-modeapplies to `@slack/socket-mode`semver:patch

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions