Tuesday, July 14, 2015

Gracefully stopping NodeJs Application Indeed

Recently, I had a problem to stop NodeJs application gracefully. The application is a highly distributed which contains multiple node process running in parallel. It is also loosely decoupled by AMQP (Advance Message Queuing Protocol). Each node process opens many connection with MQ (Message Queue) and talks each other. 

It is interesting to work with such a complex architecture which leads to give high scalability. Interestingly, we found that SIGINT signal doesn't close some of the node process when process are forked from other parent process.

The solution is laying in two steps. 

1. Capture SIGINT signal in Node process itself.
2. Wait sometime to execute all task in event loop and call process.exit().

Then the code would be,

Initially, I have started with setTimeout to make delay. Once I done the code, everything seems working fine. However, the issue was started when we move them into testing phase where program sends multiple concurrent requests.

I have situation to give more delay in setTimeout. However, the issue is started occur intermittent. The expectation is, we have to make sure delaying time that all tasks in event-loop should be cleared and no I/O operation should not be initiated.  setTimeout is not right guy to handle this dynamic delay.

After putting more focus NodeJs document, process.nextTick is more suitable for gracefully stopping Node process.

Please see following image.

Then the final code became like as follows,

Note: Please leave your queries and suggestion as comment.