Repository navigation
Description
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:
SocketModeClient.onWebSocketMessagehandlesdisconnectwiththis.websocket?.disconnect(): the old connection is closed before a new one is opened.- Closing waits for the peer to close TCP. undici's
WebSocketnever does that itself and Slack doesn't either, so the connection stays inCLOSINGuntil 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). - The
closehandler then goes throughdelayReconnectAttempt, which incrementsnumOfConsecutiveReconnectionFailuresand waitsclientPingTimeout(5 s) beforestart(), 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 nextSlackWebSocket(retrieveWSSURL()+connect()) while the old one stays open; once the new one has receivedhello, 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
delayReconnectAttemptfor 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
retryConfigof the internalWebClient(100 retries), a client given up on keeps retryingapps.connections.openin the background and connects much later. We passclientOptions: { retryConfig: { retries: 0 }, timeout: 10_000 }and retry ourselves. disconnect()whilestart()is still waiting forapps.connections.openemitsdisconnected, butstart()goes on and connects afterwards (itsdisconnectedlistener is only registered after the URL arrives). We close such a client again onconnected.
Activity
WilliamBergamin commentedon Nov 5, 2026
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 yourrefresh-gap.mjsas-is:refresh_requested--rfc)Results were identical across repeated runs. Your breakdown holds up against the code on
main:SocketModeClient.onWebSocketMessagehandlesdisconnectwiththis.websocket?.disconnect(), so the old connection closes before a new one is requested.closehandler then routes throughdelayReconnectAttempt, which incrementsnumOfConsecutiveReconnectionFailuresand sleepsclientPingTimeout * failures(5 s) beforestart(). That accounts for the whole 5.0 s left in the--rfccase.For comparison, python-slack-sdk's built-in client handles
disconnectwithconnect_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:
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).delayReconnectAttemptbackoff for it.Labeling this as a bug.
WilliamBergamin commentedon Nov 10, 2026
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.