Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Properly stopping, waiting, and reseting a node.js heroku process

Tags:

node.js

heroku

I haven't deployed yet, but I'm not sure how to do this.

I have an app that uses a lot of background processes. That is, even after a response is sent, there are still functions associated with that response executing in the background. Thus, I want to do something like this:

var server = http.createServer(app).listen(80)

process.on('SIGINT', function () {
  server.close()
  setTimeout(function () {
    process.exit()
  }, 30000) // Wait 30 seconds before exiting
})

I'm not sure if this is correct or not. More assumptions:

  • These background processes are crucial. However, they'll probably take 1-2 seconds, not 30 seconds. Still, I want to put a 30 second delay just for safety.
  • This should work for both restarting the process (say, with forever) and stopping the process
  • What signals does Heroku (or any other process) send to node.js through process? Would I have to handle them any differently?
  • Would I handle uncaughtException any differently?

Thanks

like image 676
Jonathan Ong Avatar asked Feb 11 '13 07:02

Jonathan Ong


People also ask

How do I stop a node js server from crashing?

1- What you actually want, which is preventing the process to exit, can be handled by handling uncaughtException (documentation) event: var handleRequest = function(req, res) { res. writeHead(200); res1. end('Hello, World!\

Which process event is emitted right before a node process crashes and exits?

One of these is beforeExit , and as its name implies, it is emitted right before a Node process exits. You can provide an event handler which can make asynchronous calls, and the event loop will continue to perform the work until it's all finished.

What is process exit in node?

The process. exit() method is used to end the process which is running at the same time with an exit code in NodeJS. Syntax: process.exit( code )


1 Answers

Got it. Heroku sends a SIGTERM signal when shutting down. If the process doesn't exit in 10 seconds, then it sends a SIGKILL signal. Thus, the following is sufficient:

process.on('SIGTERM', server.close.bind(server))

https://devcenter.heroku.com/articles/dynos#graceful-shutdown-with-sigterm

Assuming 10 seconds is enough for the background processes to complete.

Basically, send a "close" signal x seconds before a "exit" signal and you should be good.

like image 82
Jonathan Ong Avatar answered Oct 02 '22 17:10

Jonathan Ong