From f923243dff49187e66df44178bb2a895f1971efd Mon Sep 17 00:00:00 2001 From: Tenderdeve Date: Tue, 28 Apr 2026 11:55:08 +0530 Subject: [PATCH] fix: clean up listenersCache and cleanupCache when last observer unsubscribes When the last listener for an observerId calls unwatch(), the Map entries in listenersCache and cleanupCache were left behind as empty arrays. In long-running Node.js servers that create many clients over time, these stale entries accumulate indefinitely causing a memory leak. Now delete both Map entries when the last listener unsubscribes instead of leaving empty arrays via filter(). Fixes #4390 --- src/utils/observe.ts | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/src/utils/observe.ts b/src/utils/observe.ts index 62df7cbd92..da0c1636a3 100644 --- a/src/utils/observe.ts +++ b/src/utils/observe.ts @@ -48,12 +48,17 @@ export function observe( const unwatch = () => { const listeners = getListeners() if (!listeners.some((cb: any) => cb.id === callbackId)) return - const cleanup = cleanupCache.get(observerId) - if (listeners.length === 1 && cleanup) { - const p = cleanup() - if (p instanceof Promise) p.catch(() => {}) + if (listeners.length === 1) { + const cleanup = cleanupCache.get(observerId) + if (cleanup) { + const p = cleanup() + if (p instanceof Promise) p.catch(() => {}) + } + listenersCache.delete(observerId) + cleanupCache.delete(observerId) + } else { + unsubscribe() } - unsubscribe() } const listeners = getListeners()