All Projects → animir → Node Rate Limiter Flexible

animir / Node Rate Limiter Flexible

Licence: isc
Node.js rate limit requests by key with atomic increments in single process or distributed environment.

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Node Rate Limiter Flexible

Grant
OAuth Proxy
Stars: ✭ 3,509 (+79.95%)
Mutual labels:  express, koa, hapi, authorization
Apollo Server
🌍  Spec-compliant and production ready JavaScript GraphQL server that lets you develop in a schema-first way. Built for Express, Connect, Hapi, Koa, and more.
Stars: ✭ 12,145 (+522.82%)
Mutual labels:  express, koa, hapi
Permit
An unopinionated authentication library for building Node.js APIs.
Stars: ✭ 1,654 (-15.18%)
Mutual labels:  express, koa, hapi
Cool Admin Api
cool-admin-api 是基于egg.js、typeorm、jwt等封装的api开发脚手架、快速开发api接口
Stars: ✭ 188 (-90.36%)
Mutual labels:  express, koa, nestjs
Electrode Csrf Jwt
Stateless Cross-Site Request Forgery (CSRF) protection with JWT
Stars: ✭ 127 (-93.49%)
Mutual labels:  express, koa, hapi
Cls Rtracer
Request Tracer - CLS-based request id generation for Express, Fastify, Koa and Hapi, batteries included
Stars: ✭ 175 (-91.03%)
Mutual labels:  express, koa, hapi
Blog Service
blog service @nestjs
Stars: ✭ 188 (-90.36%)
Mutual labels:  express, koa, nestjs
Annon.api
Configurable API gateway that acts as a reverse proxy with a plugin system.
Stars: ✭ 306 (-84.31%)
Mutual labels:  authorization, auth, rate-limiting
adaptive throttler
manages multiple throttlers with ability to ramp up and down
Stars: ✭ 31 (-98.41%)
Mutual labels:  rate-limiting, throttle, rate
hapi-doorkeeper
User authentication for web servers
Stars: ✭ 14 (-99.28%)
Mutual labels:  hapi, auth, authorization
Openapi Backend
Build, Validate, Route, Authenticate and Mock using OpenAPI
Stars: ✭ 216 (-88.92%)
Mutual labels:  express, koa, hapi
Node Frameworks Benchmark
Simple HTTP benchmark for different nodejs frameworks using wrk
Stars: ✭ 117 (-94%)
Mutual labels:  express, koa, hapi
Got Auth Service
A professional role-based-authorization(also supports resource and group) service with restful and graphql api for enterprise applications.
Stars: ✭ 12 (-99.38%)
Mutual labels:  koa, authorization, auth
Analys Middlewares
redux, koa, express 中间件对比实现分析
Stars: ✭ 83 (-95.74%)
Mutual labels:  express, koa
Casbin
An authorization library that supports access control models like ACL, RBAC, ABAC in Golang
Stars: ✭ 10,872 (+457.54%)
Mutual labels:  authorization, auth
Service Tools
Prepare your Node.js application for production
Stars: ✭ 89 (-95.44%)
Mutual labels:  express, koa
Jcasbin
An authorization library that supports access control models like ACL, RBAC, ABAC in Java
Stars: ✭ 1,335 (-31.54%)
Mutual labels:  authorization, auth
Simple Todos
A simple web application powered by Nuxt.js 💚 & Nest Framework 😻
Stars: ✭ 81 (-95.85%)
Mutual labels:  express, nestjs
Adidas Multi Session
(Python) Program to simulate multiple sessions on adidas queue pages.
Stars: ✭ 90 (-95.38%)
Mutual labels:  queue, bruteforce
Appy Backend
A user system to bootstrap your app.
Stars: ✭ 96 (-95.08%)
Mutual labels:  hapi, authorization

Coverage Status npm version npm node version deno version

Logo

node-rate-limiter-flexible

rate-limiter-flexible counts and limits number of actions by key and protects from DDoS and brute force attacks at any scale.

It works with Redis, process Memory, Cluster or PM2, Memcached, MongoDB, MySQL, PostgreSQL and allows to control requests rate in single process or distributed environment.

Atomic increments. All operations in memory or distributed environment use atomic increments against race conditions.

Traffic bursts. Replace Token Bucket with BurstyRateLimiter

Fast. Average request takes 0.7ms in Cluster and 2.5ms in Distributed application. See benchmarks.

Flexible. Combine limiters, block key for some duration, delay actions, manage failover with insurance options, configure smart key blocking in memory and many others.

Ready for growth. It provides unified API for all limiters. Whenever your application grows, it is ready. Prepare your limiters in minutes.

Friendly. No matter which node package you prefer: redis or ioredis, sequelize/typeorm or knex, memcached, native driver or mongoose. It works with all of them.

In memory blocks. Avoid extra requests to store with inmemoryBlockOnConsumed.

Deno compatible See this example

It uses fixed window as it is much faster than rolling window. See comparative benchmarks with other libraries here

Installation

npm i --save rate-limiter-flexible

yarn add rate-limiter-flexible

Basic Example

const opts = {
  points: 6, // 6 points
  duration: 1, // Per second
};

const rateLimiter = new RateLimiterMemory(opts);

rateLimiter.consume(remoteAddress, 2) // consume 2 points
    .then((rateLimiterRes) => {
      // 2 points consumed
    })
    .catch((rateLimiterRes) => {
      // Not enough points to consume
    });

RateLimiterRes object

Both Promise resolve and reject return object of RateLimiterRes class if there is no any error. Object attributes:

RateLimiterRes = {
    msBeforeNext: 250, // Number of milliseconds before next action can be done
    remainingPoints: 0, // Number of remaining points in current duration 
    consumedPoints: 5, // Number of consumed points in current duration 
    isFirstInDuration: false, // action is first in current duration 
}

You may want to set next HTTP headers to response:

const headers = {
  "Retry-After": rateLimiterRes.msBeforeNext / 1000,
  "X-RateLimit-Limit": opts.points,
  "X-RateLimit-Remaining": rateLimiterRes.remainingPoints,
  "X-RateLimit-Reset": new Date(Date.now() + rateLimiterRes.msBeforeNext)
}

Advantages:

Middlewares, plugins and other packages

Some copy/paste examples on Wiki:

Migration from other packages

  • express-brute Bonus: race conditions fixed, prod deps removed
  • limiter Bonus: multi-server support, respects queue order, native promises

Docs and Examples

Changelog

See releases for detailed changelog.

Basic Options

  • points

    Default: 4

    Maximum number of points can be consumed over duration

  • duration

    Default: 1

    Number of seconds before consumed points are reset.

    Never reset points, if duration is set to 0.

  • storeClient

    Required for store limiters

    Have to be redis, ioredis, memcached, mongodb, pg, mysql2, mysql or any other related pool or connection.

Other options on Wiki:

Smooth out traffic picks:

Specific:

API

Read detailed description on Wiki.

Benchmark

Average latency during test pure NodeJS endpoint in cluster of 4 workers with everything set up on one server.

1000 concurrent clients with maximum 2000 requests per sec during 30 seconds.

1. Memory     0.34 ms
2. Cluster    0.69 ms
3. Redis      2.45 ms
4. Memcached  3.89 ms
5. Mongo      4.75 ms

500 concurrent clients with maximum 1000 req per sec during 30 seconds

6. PostgreSQL 7.48 ms (with connection pool max 100)
7. MySQL     14.59 ms (with connection pool 100)

Note, you can speed up limiters with inmemoryBlockOnConsumed option.

Contribution

Appreciated, feel free!

Make sure you've launched npm run eslint before creating PR, all errors have to be fixed.

You can try to run npm run eslint-fix to fix some issues.

Any new limiter with storage have to be extended from RateLimiterStoreAbstract. It has to implement 4 methods:

  • _getRateLimiterRes parses raw data from store to RateLimiterRes object.
  • _upsert must be atomic. it inserts or updates value by key and returns raw data. it must support forceExpire mode to overwrite key expiration time.
  • _get returns raw data by key or null if there is no key.
  • _delete deletes all key related data and returns true on deleted, false if key is not found.

All other methods depends on store. See RateLimiterRedis or RateLimiterPostgres for example.

Note: all changes should be covered by tests.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].