Skip to content

Instantly share code, notes, and snippets.

@josuecau
Last active January 3, 2016 04:09
Show Gist options
  • Select an option

  • Save josuecau/8406913 to your computer and use it in GitHub Desktop.

Select an option

Save josuecau/8406913 to your computer and use it in GitHub Desktop.
Rate limiter pattern implementation with Node.js and Redis
var redis = require('redis'),
client = redis.createClient(),
key = 'counter',
expire = 60,
max = 5
client.get(key, function (err, counter) {
if (counter !== null && counter > max) {
console.log('Too many calls')
client.quit()
return
}
client.incr(key, function (err, counter) {
console.log('Increment counter')
if (counter === 1) {
client.expire(key, expire, function (err, reply) {
console.log('Set counter expiration')
client.quit()
return
})
}
client.quit();
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment