Search code examples
javascriptnode.jssessionfacebook-messenger-bot

NodeJS - Multiple Timeouts vs one Interval for sessions in bots


I would like the messenger bot to notify the user that their session ended if they did not write/give input to the bot for some time. In order to do so, I first thought about using setTimeout() for each user which will reset upon activity. But that means if there will be 100 active users, there will be 100 Timeouts at the same time.

I wanted to know, if having one Interval instead that checks through each user`s session end timestamp every 30-60 seconds a better approach? The active users are stored in memory.


Solution

  • setTimeout is more precise in your case: each session will be ended independently and closer to the time it was supposed to end. It will also spread the activity more evenly. Since JS is single-threaded, the timeouts will not fire in parallel, even though there will be hundreds of them at the same time.

    setInterval will create spikes of activity every 30-60 seconds, and will sometimes let the sessions stay alive longer than they should.

    As per the cost of multiple timeouts running at the same time, please see this answer.