From 436e63dbd52ea12316979e23560ea0bb96176c25 Mon Sep 17 00:00:00 2001 From: Nour Alharithi Date: Tue, 12 Dec 2023 09:11:02 -0800 Subject: [PATCH] proper memory management --- src/wsConnectionManager.ts | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/src/wsConnectionManager.ts b/src/wsConnectionManager.ts index 0f73c25..26eb4b3 100644 --- a/src/wsConnectionManager.ts +++ b/src/wsConnectionManager.ts @@ -103,7 +103,7 @@ async function main() { const subscribers = channelSubscribers.get(subscribedChannel); if (subscribers) { subscribers.forEach((ws) => { - if (ws.readyState === WebSocket.OPEN) + if (ws.readyState === WebSocket.OPEN && ws.bufferedAmount < 20) ws.send( JSON.stringify({ channel: subscribedChannel, data: message }) ); @@ -271,6 +271,19 @@ async function main() { server.on('error', (error) => { console.error('Server error:', error); }); + + // Periodic check for bad clients and disconnect them to alleviate backpressure + setInterval(() => { + let set = new Set(); + for (const [_channel, wsSet] of channelSubscribers) { + set = new Set([...set, ...wsSet]); + } + for (const ws of set) { + if (ws.bufferedAmount > 500) { + ws.close(); + } + } + }, 5000); } async function recursiveTryCatch(f: () => void) {