Websocket disconnect after a while

I use Infura as WebSocket endpoint for web3 provider. After a while, it stops working, and can not get any new event. Is it a well-known issue? I used reconnect option in web3 too, and no disconnect or close socket event fired.

1 Like

Hi @Tan_Do_Ngoc!

You may want to check your config files to make sure the connection timeout value is high enough. With the reconnect option, I would suggest taking a look at this thread for an example of implementing the reconnect. Sometimes WebSockets will refresh after a certain amount of time to keep malicious connections at bay, which is likely why you’re running into these timeouts.

I use Infura as a WebSocket provider for web3.
Since web3 1.2.7, they’ve already implemented reconnect mechanism, so I used it with the config below. It doesn’t work with timeout as 30s or not set at all (not sure which default value is).

const options = {
    timeout: 30000,
    reconnect: {
      auto: true,
      delay: 5000,
      maxAttempts: 10,
      onTimeout: false,
    clientConfig: {
      keepalive: true,
      keepaliveInterval: 60000,
      maxReceivedFrameSize: 100000000,
      maxReceivedMessageSize: 100000000,

Weird issue is sometimes the socket is closed but I can not receive any close or error event from web3 provider.

provider.on('connect', () => console.log('Connected to blockchain!'));
provider.on('error', (err) => console.log('WEB3_ERROR', err.message));
provider.on('end', (err) => console.error('WEB3_END', err));

Does the event subscribe auto reconnect or I have to subscribe them again?
Fx: contract.inst.once or contract.events.Transfer
Thanks for your help!

We try to keep nodes from getting too many idle listeners, which brings down the WebSocket connections’ capabilities. Because of that, we do suggest creating a new function that refreshes the provider vs. uses something like the reconnect you have in your const options. You can check out one option for creating that function in the link from my last reply, or another version at this link.

got it, thanks for your help.