How to sync all nodejs cluster workers

I have an application which uses the cluster package and would like to be able to setup a route that forces a settings update without restarting the whole node application.

The problem is that with cluster, calling this route will only reach a single one of the worker processes and I want to have this code run on all workers. What would the strategy be for this?

Edit: I know I could call worker.exit() and have each worker restart that way, but I dont want to interrupt a worker if its in the middle of processing a request.


I'd suggest you use the child_process/parent messaging to notify all the clusters of the change in settings.

There are a couple ways you could do that. You could send a specific settings change http request and whichever child process gets that can update itself, then notify the parent by sending a message to its parent. When the parent receives that message, it can then turn around and send a message to each child so they all get notified of the settings change.

Since settings changes are often not open to the general public, it is sometimes implemented by creating a separate http server (running on a custom port) in the main process (that often isn't publicly available). You send the settings change to the special http server (which is not clustered, but in the same process as the clustered http server) and then when that web server receives the settings change, it just iterates through the clustered child processes and sends them each a message so they can update their config.

To iterate the clustered child processes, you just keep an array of the child process when you originally create them. If your clustered code looks like the sample:

if (cluster.isPrimary) {
  console.log(`Primary ${process.pid} is running`);

  // Fork workers.
  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }
}

Then, the clustered child processes will kept track of automatically in cluster.workers and you can iterate them like this:

for (const id in cluster.workers) {
  cluster.workers[id].send(...)
}

As shown here in the doc. This shows sending each of the clustered workers a message.

You can also send messages from the clustered worker to its parent. And, of course, you need an appropriate listener in the parent or worker for any message you're sending it.