smart-limiter
Smart rate limiter middleware for both express and koa.
Requirements
- Redis 2.8+ with thunk-redis client
Installation
npm install smart-limiter
Example
koa v2
'use strict' const Koa = const smartLimiter = const app = app app appconsole
express
'use strict' const express = const smartLimiter = const app = app app app appconsole
koa v1
'use strict' const Koa = const smartLimiter = const app = app app appconsole
API
var smartLimiter =
smartLimiter(options)
const limiter = app
return a express middleware.
-
options.prefix
: Optional, Type:String
, redis key namespace, default toLIMIT
. -
options.redis
: Optional, {Mix}, thunk-redis instance or thunk-redis options -
options.duration
: Optional, {Number}, of limit in milliseconds, default to3600000
-
options.getId
: Required, {Function}, generate a identifier for requests -
options.policy
: Required, {Object}, limit policypolicy key: It support 3 types:
METHOD /path
,/path
andMETHOD
. Limiter will try matchMETHOD /path
first, then/path
, thenMETHOD
. It means thatMETHOD /path
has highest priority, then fallback to/path
andMETHOD
.policy value: If value is a member, it means max count with
options.duration
. If value is array, it should be a pair ofmax
andduration
, support one more pairs.The first pair is default limit policy. If someone touch the maximum of default limit, then the next policy will be apply, and so on. So next policy should be stricter than previous one.
If someone touch the maximum of limit and request again after double current
duration
time, it will rollback to default policy.example policy:
optionspolicy ='HEAD': 100'GET': 60 60000 30 60000 30 120000'PUT': 40 60000 20 60000 10 120000'POST': 40 60000 10 60000'DELETE': 40 60000 10 60000'POST /api/organizations': 10 60000 2 60000'POST /api/projects': 20 60000 5 60000'/api/auth': 10 60000 5 120000
limiter.get(id, max, duration, max, duration...) => Promise
Return a promise that guarantee a limiter result. it support more max
and duration
pairs ad limit policy. The first pairs will be used as default. If some trigger limit, then the limiter will apply the next pair policy.
limiter.remove(req, callback)
limiter.remove(req) => Promise
Remove req
's rate limit data. Only available when using express middleware.
limiter
Responses
Example 200 with header fields:
HTTP/1.1 200 OK Connection:keep-aliveContent-Length:111Content-Type:application/json; charset=utf-8Date:Thu, 10 Dec 2015 13:21:55 GMTX-Powered-By:ExpressX-RateLimit-Limit:3X-RateLimit-Remaining:2X-RateLimit-Reset:1449753721
Example 429 with header fields:
HTTP/1.1 429 Too Many Requests Connection:keep-aliveContent-Length:39Content-Type:text/html; charset=utf-8Date:Thu, 10 Dec 2015 13:22:36 GMTRetry-After:3X-Powered-By:ExpressX-RateLimit-Limit:3X-RateLimit-Remaining:-1X-RateLimit-Reset:1449753759