Running into a weird issue with my Node.js notification listener. It works fine for a few hours, then the connection drops. I’ve got a basic reconnect loop in place, but instead of backing off, it starts hammering the endpoint. The CPU usage on the container spikes to 100% and the logs fill up with connection attempts every single millisecond. It feels like the socket.close event isn’t triggering the backoff logic correctly, or maybe I’m missing a specific state check.
Here’s the relevant part of the code. I’m using the standard ws library. The idea is to wait 5 seconds before retrying, but it seems to skip the delay entirely once it enters the error state.
const WebSocket = require('ws');
function connectToNotifications() {
const ws = new WebSocket('wss://api.eu.genesys.cloud/v2/analytics/events/realtime');
ws.on('open', () => {
console.log('Connected');
// Send auth here...
});
ws.on('close', (code, reason) => {
console.log(`Connection closed with code ${code}`);
// This is where it goes wrong
setTimeout(() => {
connectToNotifications();
}, 5000);
});
ws.on('error', (err) => {
console.error('Socket error:', err);
});
}
connectToNotifications();
I’ve checked the network tab and the WebSocket handshake seems fine initially. The issue starts when the server sends a close frame. Is there a specific code I should be ignoring? Or maybe the error event is firing before close and causing a double-trigger? I’ve tried adding a flag to prevent re-entry, but it just kills the connection permanently.
Also, I’m in London, so the latency isn’t huge, but the reconnection storm is annoying. Any ideas on how to stabilize this?