Search code examples
node.jssocketcluster

socketcluster pass client from one worker to another


I am pretty new to socketcluster and sockets in general. So I used a terminal chat example from https://github.com/devonJS/socket-cluster-chat/

I would like to scale it to 2 workers instead of one, specifically I would like to have the second worker as backup. So if the first worker dies I want all clients to connect to the backup worker. There should be a possibility to do that right?

I have played around with it a little but I cannot get it right. I would really appreciate a pointer in the right direction. I know that there are other solutions like forever or nginx, but I want to implement it myself, because I think only then I've understood it. I did not post code, cause it is quite a bit, but I can edit that in, if needed. Again any pointers would be appreciated. Cheers


Solution

  • Passing around instances between processes isn't supported in Node.js and in most cases it would be an anti-pattern.

    In SocketCluster, each client socket is connected to a single worker at any given time and if you have multiple workers, the client socket cannot choose which specific worker it will be connected to; by default, SC automatically distributes clients using the Node.js cluster module's round robin algorithm. This is a security feature to mitigate partial DDoS attacks (you don't want to allow a malicious client to target and DoS specific workers - You need to force them to spread out evenly across workers/CPU cores).

    Generally, for backup purposes, it's best to launch a second SC instance on a different host.

    You could launch a second SC instance on the same host on a different port but you should be aware that running two SC instances on the same host doesn't protect you from host or network failure.

    Note that fatal (uncaught) errors in SC can cause a worker to crash, but assuming that the underlying host is still running and is still connected to the internet, then the worker will re-spawn almost instantly. A good way to avoid unnecessary worker crashes is to make sure that you capture and handle exceptions correctly in your code (without leaking memory).