Repository navigation
Replies: 1 comment
|
The usual pattern is:
Socket.IO is not like a stateless HTTP API: once a socket is connected, it belongs to one server process. If NGINX randomly sends the same client to a different backend, the socket may disconnect or room/broadcast state will get split. Recommended setup:
Example NGINX upstream with sticky sessions: upstream socket_nodes {
ip_hash;
server 127.0.0.1:3001;
server 127.0.0.1:3002;
server 127.0.0.1:3003;
}
server {
listen 80;
server_name example.com;
location / {
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_http_version 1.1;
proxy_pass http://socket_nodes;
proxy_read_timeout 3600s;
proxy_send_timeout 3600s;
}
}Then on each Socket.IO server: const { Server } = require("socket.io");
const { createAdapter } = require("@socket.io/redis-adapter");
const { createClient } = require("redis");
const pubClient = createClient({ url: "redis://localhost:6379" });
const subClient = pubClient.duplicate();
const io = new Server(3000, {
adapter: createAdapter(pubClient, subClient)
});Important notes:
In short: use sticky sessions for the socket connection, and Redis adapter for multi-server coordination. That is the standard Socket.IO scaling pattern. |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
I have a server running with PM2, which lets me use all the machine’s vCPUs (02) to get better Socket.IO performance. This server has 4GB of RAM.
Since I’m using PM2, I have an NginX server in front that receives HTTPS/WSS requests and forwards them to port 8080.
I use the configuration below to allow the nodes to communicate correctly, as per the instructions on the website.
However, in my current scenario, it hasn’t been a good solution, especially for scalability.
If an issue occurs on the server—such as exhausting all RAM or hitting a file limit (tuning has already been done)—the entire service goes offline, so I’m thinking of using another machine, also with 2 vCPUs, to load-balance and provide high availability.
The scenario would be:
Nginx server:
-> Socket.IO Server 01 + 2 vCPUs running
-> Socket.IO Server 02 + 2 vCPUs running
But my question is what I need to change in my code for this to work.
From what I understand, in NginX I need to add the code below.
https://socket.io/docs/v4/using-multiple-nodes/#nginx-configuration
I really didn’t understand this part. If I’m going to use multiple servers, do I have to use only one CPU? Or can I keep using all the CPUs available on the machines?
Should I remove Socket.IO’s sticky mechanism?
Is that it? Could someone give me more details?
All reactions