Hey everyone,
I’m building a Node.js service to subscribe to the Genesys Cloud Notification API via WebSocket. The goal is to get real-time updates for interaction events. The initial connection works fine using the ws library. I’m passing the OAuth token in the query string like this:
const ws = new WebSocket(`wss://{{orgId}}.mypurecloud.com/api/v2/analytics/events?access_token=${token}`);
The problem is handling the disconnect. When the token expires or the server drops the connection, my code tries to reconnect immediately. If I don’t wait, I get flooded with 429 Too Many Requests errors because the rate limiter kicks in. If I wait too long, I miss events.
Here is my current reconnect logic:
ws.on('close', (code, reason) => {
console.log(`Connection closed: ${code} - ${reason}`);
// Wait 5 seconds before reconnecting
setTimeout(() => {
connect();
}, 5000);
});
This feels brittle. Is there a recommended pattern for exponential backoff here? Also, do I need to fetch a new OAuth token before every reconnect attempt, or does the existing token hold up for the retry window? I’ve seen some docs mention a reconnect flag but I can’t find examples for Node.js.
Any code samples for a stable reconnect loop would be great.