Why is redis + socket.io performance better than just socket.io?

I used to have all my code in socket.io + node.js server. I recently converted all the code to redis + socket.io + socket.io + node.js, noticing slow performance when too many users are sending messages across the entire server. So why socket.io alone was slow is because it is not multithreaded, so it handles one request or emits at a time. What redis does is propagate these requests or emit pipes. Clients subscribe to different channels, and when a message is posted to a channel, all clients that subscribe to it receive the message. It does it through this piece of code:

sub.on("message", function (channel, message) {
  client.emit("message",message);
});

      

Client.on ('emit', function () {}) takes it from here to post messages to different channels.

Here is a short code explaining what I am doing with redis:

io.sockets.on('connection', function (client) {
var pub = redis.createClient();
var sub = redis.createClient();
sub.on("message", function (channel, message) {
    client.emit('message',message);
});
client.on("message", function (msg) {
if(msg.type == "chat"){
    pub.publish("channel." + msg.tousername,msg.message);
    pub.publish("channel." + msg.user,msg.message);
}
else if(msg.type == "setUsername"){
  sub.subscribe("channel." +msg.user);
}
});

});

      

Since redis stores channel information, we can publish different servers to the same channel.

So what I don't understand is if sub.on ("message") is called every time a request is sent or emitted, why should redis give better performance? I suppose even the sub.on ("message") method is not multithreaded.

+3


source to share


1 answer


As you know, Redis

allows you to scale multiple instances node

. So the performance actually comes after the fact. Using the method Pub/Sub

is not faster. It's technically slower because you have to communicate between Redis

for each signal Pub/Sign

. "Better performance" is really true when you start to scale horizontally.



For example, you have one instance node

(a simple chat room) - which can handle a maximum of 200

active users. You don't use Redis

because there is no need. Now if you want to have active users 400

? Using the example above, you can now achieve this user label 400

, which is a "performance boost". In that sense, you can now handle more users without actually increasing the speed. If that makes sense. Hope this helps!

0


source







All Articles