Rate limit made simple, easy, async. Based on ratelimiter.
NOTE: It requires Redis 2.6.12+.
$ npm install async-ratelimiter --save
A simple middleware implementation for whatever HTTP server:
'use strict'
const RateLimiter = require('async-ratelimiter')
const Redis = require('ioredis')
const limit = new RateLimiter({
db: new Redis()
})
const apiQuota = async (req, res, handler) => {
const limit = await rateLimiter.get({ id: req.clientIp })
if (!res.finished && !res.headersSent) {
res.setHeader('X-Rate-Limit-Limit', limit.total)
res.setHeader('X-Rate-Limit-Remaining', Math.max(0, limit.remaining - 1))
res.setHeader('X-Rate-Limit-Reset', limit.reset)
}
return !limit.remaining
? sendFail({req,
res,
code: HTTPStatus.TOO_MANY_REQUESTS,
message: MESSAGES.RATE_LIMIT_EXCEDEED()
})
: handler(req, res)
}
Required
Type: object
The redis connection instance.
Type: number
Default: 2500
The maximum number of requests within duration
.
Type: number
Default: 3600000
How long keep records of requests in milliseconds.
Type: string
Default: 'limit'
The prefix used for compound the key.
Type: string
The identifier to limit against (typically a user id).
You can pass this value using when you use .get
method as well.
Given an id
, returns a Promise with the status of the limit with the following structure:
total
:max
value.remaining
: number of calls left in currentduration
without decreasing currentget
.reset
: time since epoch in seconds that the rate limiting period will end (or already ended).
Type: string
The identifier to limit against (typically a user id).
Type: number
The maximum number of requests within duration
. If provided, it overrides the default max
value. This is useful for custom limits that differ between IDs.
Type: number
How long keep records of requests in milliseconds. If provided, it overrides the default duration
value.
async-ratelimiter © microlink.io, released under the MIT License.
Authored and maintained by microlink.io with help from contributors.
microlink.io · GitHub microlink.io · Twitter @microlinkhq