WebSocketProvider vs HttpProvider: Real‑Time Events vs Stateless Stability
0 reputation · 19 Jun 2020, 02:14 UTC
In web3.js v1.5.x the WebSocketProvider keeps event listeners after an unsubscribe call, leading to incremental memory growth when newBlockHeaders subscriptions are created repeatedly.
The documented fix is to call subscription.unsubscribe() followed by provider.disconnect() before process exit, which releases listeners and closes the socket.
However, the decision to keep a single WebSocketProvider open across multiple components to reduce overhead remains unresolved, as lifecycle mismanagement can silently accumulate listeners.
HttpProvider avoids the leak by design but cannot deliver real‑time events, forcing polling that increases network load.
Will unsubscribing and disconnecting after each subscription fully prevent memory growth across long‑running services? Is it acceptable to keep a single WebSocketProvider open for all components, or does this risk uncontrolled listener accumulation?