简体   繁体   中英

Running thousands of setInterval functions in NodeJS simultaneously

this is more of a code-less question as I don't think it's that important in regards to my question.

In short, I'm building an app where users create a profile. Every user has an amount of credits which they can use to promote their profile.

How the promotion works?

Each user has a "lastUpdated" field in the DB, after which they're sorted on the homepage. When a user triggers the promotion through an API call, I run a setInterval of X miliseconds (provided by the user).

Every X miliseconds, the user's "lastUpdated" field receives a timestamp and X credits are subtracted from their account. Once the user runs out of credits, the setInterval stops.

My acutal question(s)

How is this performance-wise, considering the fact that there could be thousands of those calls, resulting in thousands of setInterval functions running at the same time?

Is there any other way to approach this?

Thank you!

It would be better to calculate everything on-demand when it's needed. Assuming the amount of credits used are dependent on how long the promotion has been showing for, you could store the start time in the database and then use the current time to calculate how many credits are remaining based on how long has elapsed. This would result in much less operations compared to running a function every few milliseconds.

If you really have to do this with an interval, it would be best to just have one running every 5 seconds or so (random number). Since this is interfacing with the DB, that may be too much load.

Just doing things on demand when the API from one user comes in should be the cleanest option.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM