Skip to content

Instantly share code, notes, and snippets.

@gjohnson
Created October 5, 2011 07:40
Show Gist options
  • Save gjohnson/1263873 to your computer and use it in GitHub Desktop.
Save gjohnson/1263873 to your computer and use it in GitHub Desktop.
cluster throttle idea
var utils = require('cluster/lib/utils');
var redis = require('redis');
var rc = redis.createClient();
exports = module.exports = function(options) {
ratelimit.enableInWorker = true;
options = options || {};
var interval = options.interval = (options.interval || 1);
var now = function () {
return (new Date).getTime() / 1000;
};
function ratelimit(master) {
var server = master.server;
var listeners = server.listeners('request');
if (master.isWorker) {
server.removeAllListeners('request');
server.on('request', function(req, res) {
var ctx = this;
var id = req.connection.remoteAddress + req.headers['user-agent'];
rc.getset(id, now(), function(err, then) {
if (then && (now() - then) < interval) {
res.writeHead(500);
res.end();
} else {
listeners.forEach(function(fn) {
fn.call(ctx, req, res);
});
}
});
});
}
}
return ratelimit;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment