Shweelan Leon Sam
Shweelan Leon Sam

Reputation: 165

nodejs cluster messaging vs websockets

I am developing an app with nodeJS and cluster with multiple workers with different port on each worker, I may need to make the workers communicate each other, I know that nodeJS cluster has built in support for messaging between master and other workers.

I have 3 questions regarding this. 1 . can I send the message between workers without master to be in the middle, for faster process ?

  1. Is it good idea to open a websocket on each worker to listen from other workers to replace the built in messaging in cluster, is it faster ?

  2. if the app would scale to multiple servers I think websocket would be the answer, any alternatives please suggest ?

Upvotes: 0

Views: 260

Answers (2)

vovchisko
vovchisko

Reputation: 2239

IPC.

Each NodeJS child process (started with fork) has process.send(<data>); method. And can listen for messages from parent. Feel free to pass objects, if you want. It will be stringified and parsed on other side.

process.on('message', (data) => {});

When you fork process on parent side - it also has methods for messaging.

const child = child_process.fork('child.js');
child.on('message', (data) => { });

If you want to make workers/childs communicate between each other - You can manage it by sending specific messages to master, and master will forward it to specified worker.

Docs: Child Process Event "Message"

Upvotes: 0

freakish
freakish

Reputation: 56557

  1. No. Generally child processes are not aware of each other. They are only aware of the parent.
  2. It is not faster, it is definitely slower. It might be better though since you won't be able to scale onto multiple machines otherwise (cluster only creates subprocesses). Depending on your needs.
  3. Try zeromq for example (I'm sure there is a binding for NodeJS, google it). Or a dedicated message broker (like RabbitMQ). These were created to solve that particular problem of yours unlike websockets.

Upvotes: 1

Related Questions