title: Node.js, multi-threading and Socket.io
body: <p>I'm looking to get Socket.io to work multi-threaded with <a href="http://nodejs.org/docs/latest/api/cluster.html" rel="noreferrer">native load balancing</a> ("cluster") in Node.js v.0.6.0 and later.</p>
  
  <p>From what I understand, Socket.io uses Redis to store its internal data. My understanding is this: instead of spawning a new Redis instance for every worker, we want to force the workers to use the same Redis instance as the master. Thus, connection data would be shared across all workers.</p>
  
  <p>Something like this in the master:</p>
  
  <pre><code>RedisInstance = new io.RedisStore;
  </code></pre>
  
  <p>The we must somehow pass <code>RedisInstance</code> to the workers and do the following:</p>
  
  <pre><code>io.set('store', RedisInstance);
  </code></pre>
  
  <p>Inspired by <a href="https://github.com/3rd-Eden/nodejsconfit-2011/tree/master/cluster" rel="noreferrer">this implementation</a> using the old, 3rd party cluster module, I have the following non-working implementation:</p>
  
  <pre><code>var cluster = require('cluster');
  var http = require('http');
  var numCPUs = require('os').cpus().length;
  
  if (cluster.isMaster) {
    // Fork workers.
    for (var i = 0; i &lt; numCPUs; i++) {
      cluster.fork();
    }
  
    var sio = require('socket.io')
    , RedisStore = sio.RedisStore
    , io = sio.listen(8080, options);
  
    // Somehow pass this information to the workers
    io.set('store', new RedisStore);
  
  } else {
    // Do the work here
    io.sockets.on('connection', function (socket) {
      socket.on('chat', function (data) {
        socket.broadcast.emit('chat', data);
      })
    });
  }
  </code></pre>
  
  <p>Thoughts? I might be going completely in the wrong direction, anybody can point to some ideas?</p>