Node.js WebSocket reconnection loop for Genesys Cloud Notification API

What’s the right way to handle reconnection logic for the Notification API in Node.js without getting hammered by rate limits?

We’ve got a Node service subscribing to /api/v2/analytics/events/realtime and /api/v2/conversations/realtime. The initial handshake works fine. We get the Authorization header, set the User-Agent, and the stream opens. But when the connection drops-usually after a few hours of idle time or a network blip-the close event fires.

My current logic just waits 1 second and calls connect() again. This feels wrong. If the server is doing maintenance, I’ll just bounce repeatedly. Plus, I’m seeing 401 Unauthorized errors in the logs sometimes, which suggests my token might be expiring while the reconnect loop is churning.

Here’s the rough setup:

const WebSocket = require('ws');

function connect() {
 const token = getAccessToken(); // Simplified
 const ws = new WebSocket(url, {
 headers: {
 'Authorization': `Bearer ${token}`,
 'User-Agent': 'MyIntegration/1.0'
 }
 });

 ws.on('close', (code, reason) => {
 console.log(`Disconnected: ${code} ${reason}`);
 // Just retry immediately? Seems bad.
 setTimeout(connect, 1000); 
 });
}

I’ve tried adding a backoff strategy, but I’m not sure what the max delay should be. Also, do I need to re-authenticate every time, or can I reuse the token if it’s still valid? The docs mention retry-after headers for REST, but WebSockets don’t really send those on close.

Is there a standard pattern for this? Or should I just poll a REST endpoint to check if the service is up before attempting the WebSocket handshake? Feels like overkill, but I’m tired of these silent failures.