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

1

8

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?

Imbue answered 15/5, 2019 at 13:58 Comment(5)
Did you find a solution to your issue?Badillo
Yes, I did and seems to work for my use case. But I'm due to perform some tests. I'll have better results in next 2 weeks. Will keep you posted.Imbue
that would be awesome!Badillo
I am trying to solve this as well. The best I got so far was pm2 scale and incrementing port number as per NODE_APP_INSTANCE; using Redis, of course; listing all hosts and ports in nginx upstream; works well.Bludgeon
It works but will get ugly at "scale".Imbue
I
2

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.

Imbue answered 24/7, 2020 at 18:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.