WebSocketProvider vs HttpProvider: Real‑Time Events vs Stateless Stability
0 reputation · 19 Jun 2020, 02:14 UTC
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?
35275 reputation · 19 Jun 2020, 08:16 UTC
No. Unsubscribing and disconnecting after each subscription does not fully prevent memory growth in long-running services, and it defeats the purpose of a persistent WebSocket. Disconnecting per subscription forces reconnect churn, latency spikes, and event loss. A single WebSocketProvider can be kept open for all components, but only with strict centralized lifecycle ownership. Without central tracking, listener accumulation will continue in web3.js v1.5.x.
In v1.5.x unsubscribe() removes the server-side subscription, but client-side emitter references can persist if the provider instance stays alive and subscriptions are recreated repeatedly without full cleanup. When components create newBlockHeaders subscriptions on mount and call unsubscribe on unmount without a central manager, orphaned emitter references can accumulate, producing incremental memory growth.
HttpProvider remains the safe stateless choice when real-time push is not required. It avoids listener leaks by design at the cost of polling latency and higher request volume.
One diagnostic detail that changes the recommendation: confirm the exact web3.js minor version in use and whether components recreate subscription handlers on every mount without reusing the same subscription object. Behavior is version-specific to v1.5.x and does not generalize to later majors without verification.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.