indutny / sticky-session

Sticky session balancer based on a `cluster` module
964 stars 99 forks source link

Added Reverse Proxy Support #45

Closed awolden closed 3 years ago

awolden commented 8 years ago

This pull request is a proposed solution for reverse proxy support. It leaves all existing functionality in place with no effect whatsoever if you are not using the new proposed option: proxyHeader.

This fixes issue #6 and #15 and it is heavily based on PR #20.

Logic

The basic logic is to parse the first packet on an incoming connection, read the IP header information, and load balance based on the header IP. The read packet is included in the load-balancing IPC message and is unshift'ed back onto the socket.

I included a basic proxy test and testing with websocket bench seems to indicate no major issues.

There were also some minor changes regarding the options object and I added some basic logic to support different types of balancing functions.

Example Usage

var cluster = require('cluster'); // Only required if you want the worker id
var sticky = require('sticky-session');

var server = require('http').createServer(function(req, res) {
  res.end('worker: ' + cluster.worker.id);
});

let isChild = sticky.listen(server, 3000, {
  workers: 8,
  proxyHeader: 'x-forwarded-for'//header to read for IP
});

if (!isChild) {
  // Master code
  server.once('listening', function() {
    console.log('server started on 3000 port');
  });
} else {
  // Worker code
}
paul-em commented 8 years ago

I am trying to solve the same issue and I am not successful so far. Your solution is interesting, but i wonder how it performs since you have to parse the headers in the master process...

awolden commented 8 years ago

I didn't do much performance comparison, I just did a load test to watch for dropped connections and issues like that.

Honestly, I made this change for a project I was working on, but I eventually walked away from clustering all together and ran each websocket process on a different port and used nginx to load balance between them. Anything performance dependent probably shouldn't be going through cluster.

gunblues commented 8 years ago

I have tried your solution but it will fail back to XHR. You can see it at chrome console. All requests happened at XHR in tab network.

indutny commented 8 years ago

Sorry, I have totally missed this PR.

I totally agree that this is required, however I have a question/feedback. Do you think it may be easier to just use PROXY protocol?