Redis Pub-Sub or Socket.IO’s broadcast

publish-subscribereal timeredissocket.io

I saw this snippet:

On Server

io.sockets.on('connection', function(socket) {
  const subscribe = redis.createClient();
  const publish = redis.createClient();

  socket.on('publish', function(channel, data) {
    publish.publish(channel, data);
  });

  socket.on('psubscribe', function(channel) {
    subscribe.psubscribe(channel);
  });

  subscribe.on("pmessage", function(pattern, channel, message) {
    socket.emit('message', { channel: channel, data: message });
  });
});

On Client

$(".action").click(function() {
  socket.emit('publish', 'game.#{gameid}.action.' + $(this).data('action'),
  JSON.stringify({ nick: "#{nick}", ts: Date.now() })
);

And I'm wondering why? Doesn't Socket.IO have its own broadcast mechanism? Why choose Redis' Pub-Sub over Socket.IO? Can't we just do like this:

io.sockets.on('connection', function(socket) {
  socket.on('action', function(channel, data) {
    socket.broadcast.to(channel).emit(data)
  });
});

And if there is a reason to use Redis, what would be the benefit? Persistence?

Best Answer

The reason I chose to use Redis Pub Sub with Socket.io in my Real Time Activity Stream project (http://blog.cloudfoundry.com/2012/06/05/node-activity-streams-app-2/) was because I wanted to have multiple web servers (instances on Cloud Foundry or dynos on Heroku). As far as I could see, Socket.io stores the messages in memory (of one webserver), so how it could possibly broadcast to clients which are connected to another webserver?

Check out the post and let me know if it helps