4

I am developing an app using Node JS, Socket.io, and Async module by Caolan.

I want to ask something about emitting to lots of clients, and if it block the event loop.

For the use in my app, I need to stack sockets (connected clients informations), and I manage to who I need to emit to.

So once I know who I need to emit to, I loop through the clients using Async.each to emit the datas to clients.

Example:

    async.each(clientsIds,
      function(item,cb)
      {
        clients[item].emit('sendData', datas);
    cb();
      },
      function(err)
      {

      }
    );  

So my question is: if I have 1000000 clients connected, will it block the Event Loop till it finished to emit to all clients when I send datas?

When I am alone connected, and try to emit 1000000 times to myself, it blocks the Event Loop till the function finished running. Is it because I am sending it 1000000 to the same clients, or the result would be the same if it was 1000000 different connected clients?

Thanks in advance if anyone can help me! I can't do test with mass of connected clients to confirm it myself or not.

(And sorry if it is a noob question, I am not a pro)

babacool
  • 41
  • 1
  • 4

1 Answers1

0

Directly depends on the emit function , is it sync or async ?

async library wont block your event loop, it is handling things through callback, now all the 1000000 callback are waiting to be called in the queue , now whenever the event loop take out the function one by one to the call stack , and emit function does all the task(some heavy operation) in the same thread or the only event loop, then this keeps other 999999 callback waiting , but if .emit function offload the task to a different runner,example db calls , lets says mongodb , node js driver offload the task of doing io to the mongodb server, and keeps on running without blocking the event loop . Basically check what emit is doing. if it wont doing much , then for sure it wont block your only event loop.

Ashok Mandal
  • 278
  • 2
  • 13
  • Thanks for the reply. Well, according to this: https://stackoverflow.com/questions/33160697/why-doesnt-io-emit-work-in-process-on socket.io EMIT function is supposedly asynchronous, but whatever test I do (I have a setInterval doing a job every 500ms in my app.js so I can see if the Event Loop is blocked at some point or not), when I emit to 1000000 clients (in my test they are all a copy of the same client: my connection to the app), it blocks the event loop for like 11 seconds till it finishes emitting. I'm at a loss :(. Thanks again though. – babacool Aug 05 '18 at 13:15