redis-rate-limiter
Rate-limit any operation, backed by Redis.
- Inspired by ratelimiter
- But uses a fixed-window algorithm
- Great performance (>10000 checks/sec on local redis)
- No race conditions
Very easy to plug into Express
or Restify
to rate limit your Node.js
API.
Usage
Step 1: create a Redis connection
var redis = ;var client = redis;
Step 2: create your rate limiter
var rateLimiter = ;var limit = rateLimiter;
And go
;
Options
redis
A pre-created Redis client. Make sure offline queueing is disabled.
var client = redis;
key
The key is how requests are grouped for rate-limiting. Typically, this would be a user ID, a type of operation.
You can also specify any custom function:
// rate-limit each user separately { return xuserid; } // rate limit per user and operation type { return xuserid + ':' + xoperation; } // rate limit everyone in the same bucket { return 'single-bucket'; }
You can also use the built-in ip
shorthand, which gets the remote address from an HTTP request.
key: 'ip'
window
This is the duration over which rate-limiting is applied, in seconds.
// rate limit per minutewindow: 60 // rate limit per hourwindow: 3600
Note that this is not a rolling window.
If you specify 10 requests / minute
, a user would be able
to execute 10 requests at 00:59
and another 10 at 01:01
.
Then they won't be able to make another request until 02:00
.
limit
This is the total number of requests a unique key
can make during the window
.
limit: 100
rate
Rate is a shorthand notation to combine limit
and window
.
rate: '10/second'rate: '100/minute'rate: '1000/hour'
Or the even shorter
rate: '10/s'rate: '100/m'rate: '100/h'
Note: the rate is parsed ahead of time, so this notation doesn't affect performance.
HTTP middleware
This package contains a pre-built middleware, which takes the same options
var rateLimiter = ; var middleware = rateLimiter; server;
It rejects any rate-limited requests with a status code of HTTP 429
,
and an empty body.
Note: if you want to rate limit several routes individually, don't forget to use the route name as part of the key
, for example using Restify:
{ return reqconnectionremoteAddress + ':' + reqroutename;} server; server;