Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make socket.io work properly with pm2 cluster mode?

I have been looking at various solutions around but when I put it all together, it looks very confusing.

I am trying to implement pm2 cluster mode for my application which has socket.io implementation. Now, I understand the concept that statelessness is required in order to make my app work properly in cluster mode. And socket.io is NOT stateless. The confusion is,

1) Our friend Cam says that just implementing socket.io-redis would work fine when we'll spawn on the maximum number of CPUs.
2) While socket.io says and I quote,

Note: sticky-session is still needed when using the Redis adapter."

For 1), According to my research, Internet should disagree that it would work. Maybe Mr. Cam got lucky to have transport method as websocket and might not had to deal with polling. But at the same time I think it should work, since redis-adapter is what we are using to make it stateless.

INFO: It worked for me with websocket as transport method but I couldn't test it with polling.

For 2), I think we can combine Mr. Joni's advice to run it with "pm2" IN "cluster" but on different ports. And then our beloved nginx's upstream group with ip_hash would give us kind of same effect.

Additionally, I want to make my application elastic. NOT just on cluster level but both scale up and out. What are the best practices given that my application included socket.io implementation and session token management in redis?

Am I missing something or am I totally wrong here? Which would be the best way to scale?

like image 677
Yogesh Avatar asked May 15 '19 13:05

Yogesh


1 Answers

I've got the solution!!! And it is working perfectly fine for me! Thanks to @elad and contributors. I've done some extensive amount of testing(more than 2 MONTHS!) and never had a problem. I'll not disrespect the author by explaining what the snippet does as it has already been described enough, line-by-line.
It took me long enough because there were open issues on the repo and had to be sure. And now I am sure that those issues are workable with understanding of different components. Afterall, this is not magic!

Have a look and let me know if you still have doubts/questions.

like image 121
Yogesh Avatar answered Nov 11 '22 23:11

Yogesh