Could someone explain the correct pattern for handling WebSocket reconnections when consuming the Genesys Cloud Notification API in a Node.js environment? We’re building an internal service that subscribes to real-time events for queue status updates. The current implementation uses the ws library, but we’re seeing inconsistent behavior when the connection drops unexpectedly.
The issue seems to be related to how we handle the close event versus the error event. When we detect a drop, we immediately attempt to reconnect. However, sometimes the server hasn’t fully closed the connection on their end, leading to a 409 Conflict or a silent failure where the new WebSocket instance never emits open.
Here’s the simplified service logic we’re using:
import WebSocket from 'ws';
private connect(): void {
const ws = new WebSocket(this.endpoint);
ws.on('open', () => {
console.log('Connected to Notification API');
this.sendSubscription();
});
ws.on('close', () => {
console.warn('Connection closed. Reconnecting in 2s...');
setTimeout(() => this.connect(), 2000);
});
ws.on('error', (err) => {
console.error('WebSocket error:', err.message);
// Should we reconnect here too?
});
}
We’ve noticed that if we trigger a reconnect from the error handler, we often end up with multiple concurrent WebSocket instances trying to subscribe to the same topic, which causes duplicate events. The Genesys Docs mention that clients should handle re-subscription, but they don’t specify the exact sequence for tearing down the old socket before establishing a new one.
Is there a recommended way to ensure the previous connection is fully terminated before initiating a new one? We’re using the Node.js runtime, not the browser SDK. Any insights on managing the subscription lifecycle during these transitions would be appreciated.