Search code examples
node.jsmultithreadingchild-processheavy-computation

How to finish child_process on nodejs?


So, I have a service made in node running on Kubernetes and I need to make a very heavy operation every 30 minutes (CRON JOB). It's a bunch of database operations for each tenant on my application (currently, 5 tenants).

The thing is that if I start then all, even asynchronously, on the same process the service goes into too much load and crashes.

Because of this, I tried to use the child_process module. My idea was to create a new process for each tenant,do what it needs to do and then kill the process.

I'm using child_process.fork('heavyLoadFile') to create the child process.

The thing is that when the work is done, the CPs are not being destroyed. They stay there as a "zombie" process, doing absolutely nothing.

I tried to process.kill() on the CP but it also kills the parent process.

How can I kill only the child_process? Oh, and do you guys think of a better way to handle this heavy loads?


Solution

  • Running process.kill() will kill your main NodeJS app and any children it may have.

    You need to only kill the child process. like so:

    const cp = require("child_process");
    
    // you fork a child (your cron script)
    const child = cp.fork("<your program>");
    
    // the rest of your code
    
    // you kill only this child
    child.kill();