Since node.js applications are single threaded we can create multiple processes to listen to the same port, and make use of all the CPU cores that are available in our computers. To simplify this, node comes with a module called cluster. This module has a number of handy functions to create workers and monitor them. It also lets us send and receive messages from processes (similar to Window.postMessage() in the browser).

One of the limitations of this module is that a worker is not aware of any other worker and can only send messages to the master process. If one worker has to send a message to another worker, the message must first be sent to the master which then forwards it to the actual recipient.

This results in a lot of boilerplate code that’s repeated in a number of applications. Pseudo code to broadcast a message:

// Workers send the message to the master
function sendMessage(message) {
    process.send(message)
}

process.on('message', function(message) {
    if (process.isMaster) {
        // In master; forward message to all workers
        forEach (worker in workersList) {
            worker.sendMessage(message)
        }
    }
    else {
        // In worker
        switch(message.code) {
            case 'code1': function1(message); break;
            case 'code2': function2(message); break;
        }
    }
})

You’ll have to write additional code to keep track of the sender’s process id, send replies to just one worker and such stuff which are pretty easy to do, but should really be a part of the library itself. So I went ahead and made a library that acts as a wrapper around the underlying cluster module and helps reduce boilerplate. :p The library provides functions called messageSiblings, messageWorkers etc. which do exactly what their names say.

The library can be found on npm under the MIT license. Feel free to fork it and add any functions you need. :)