ethers-io / ethers.js

Complete Ethereum library and wallet implementation in JavaScript.
https://ethers.org/
MIT License
7.96k stars 1.85k forks source link

Event listeners are constantly sending requests #1071

Closed 0xclem closed 4 years ago

0xclem commented 4 years ago

I'm using events listeners in my dApp in order to automatically fetch new data when needed. It's working very well, however it looks like the listeners are constantly making requests in the background even though there is no new events emitted.

Here is an example:

Screen Shot 2020-09-30 at 8 52 53 am

I left my tab open for a few minutes and it already made almost 200 requests. Knowing that we've got a lot of traffic on our dApps (Synthetix), we reach our Infura node daily cap in a couple of hours only.

So I was just wondering if there was any logical explanation to this behaviour, and if there was anything I could do to avoid it.

I'm using ethers v4.0.38.

ricmoo commented 4 years ago

You should try updating to v5, but the same thing will occur for the most part. But might help by distributing requests across INFURA and Alchemy (and soon Pocket).

There is no “push”, so the way events are implemented is by querying every 6 seconds for a new block number. If the block number has changed, it scans for all the events you are listening for.

You can consider using a WebSocketProvider (you can use the InfuraProvider.getWebSocketProvider() static method), but keep in mind using web sockets also usually incur higher costs for quota limits.

Does that make sense? Let me know if you have any follow-up questions. :)

dvd-schwrtz commented 4 years ago

the WebSocketProvider doesn't push events? Or it does? Even if it is more expensive, the amount of events pushed should be way less than the number of requests from polling negating any cost increases, right?

ricmoo commented 4 years ago

The WebSocketProvider does push events. The other providers do not though, and use polling.

It depends on your use case and how the services weigh costs.

The infrastructure cost of providing a websocket connection is tremendously more than normal http requests, so it completely depends on how that is all set up, what hardware and software stacks the service provider is using and the features they offer.

0xclem commented 4 years ago

Thanks @ricmoo ! I'll have a look at WebSocketProvider.

ricmoo commented 4 years ago

I think this has been answered, so I'm going to close it. If not, please feel free to re-open.

Thanks! :)