Last active
January 3, 2016 04:09
-
-
Save josuecau/8406913 to your computer and use it in GitHub Desktop.
Rate limiter pattern implementation with Node.js and Redis
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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