简体   繁体   中英

Does setTimeout function affect the performance of Node.js application?

I have a request handler for ticket booking:

route.post('/makeBooking', (req, res) => {
  // Booking code

  setTimeout(function () {
    // Checks if the payment is made, if not then cancels the booking
  }, 900000);
});

Now I've a route which makes a booking and if the payment is not made within 15 minutes the timeout function will cancel the booking.

Will this function cause any performance related issues or memory leaks?

Will this function cause any performance related issues ...

No it won't, at least not in and by itself. While setTimeout is waiting to invoke it's callback, it's non-blocking . The call is simply added to a queue. At some point in the future the callback fires and the call is removed from that queue.

In the meantime, you can still process stuff.

... or memory leaks?

The setTimeout callback is within a closure. As soon as setTimeout invokes the callback, it becomes eligible for garbage collection.

Unless you get many millions of bookings within the 900000ms timeframe, you have nothing to worry about; the number of course depends on the memory size you allocated to your Node.js application.

Of course if you do get that many requests-per-second, you have other, more important stuff to worry about.

It won't have performance issues or memory leak problems, but using a 15 minutes timeout function might be problematic for debugging and maintaining.

Especially something like cancelling a booking should be solved another way.

You always should write your node application in a way that:

  • You can run it in cluster mode (Even if you don't need it for performance reasons)
  • That a crash of the application and immediate restart would not cause much information loss (a 15 minute timeout could be problematic here)
  • That a crash or restart of the application will not result in an inconsistent state (eg a pending booking that would not be cancelled anymore)

So assuming that you already use a database for the booking process, then you should also do the 15 minute timing within the database.

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