Installations
npm install @rahil-p/rate-limiter-flexible
Developer Guide
Typescript
Yes
Module System
CommonJS
Node Version
18.6.0
NPM Version
8.13.2
Releases
Prisma unref timeout and DynamoDB ttlSet flag
Published on 15 Jan 2025
Redis custom Lua script support
Published on 28 Apr 2024
Prisma support
Published on 15 Feb 2024
Fix RateLimiterMongo TypeError
Published on 26 Jan 2024
DynamoDB support
Published on 16 Dec 2023
Fix RateLimiterUnion.consume return type
Published on 08 Dec 2023
Contributors
Languages
JavaScript (100%)
Developer
animir
Download Statistics
Total Downloads
433
Last Day
1
Last Week
2
Last Month
12
Last Year
177
GitHub Statistics
3,133 Stars
705 Commits
164 Forks
22 Watching
4 Branches
43 Contributors
Bundle Size
37.60 kB
Minified
8.94 kB
Minified + Gzipped
Package Meta Information
Latest Version
2.3.9
Package Id
@rahil-p/rate-limiter-flexible@2.3.9
Unpacked Size
120.03 kB
Size
24.75 kB
File Count
30
NPM Version
8.13.2
Node Version
18.6.0
Total Downloads
Cumulative downloads
Total Downloads
433
Last day
-50%
1
Compared to previous day
Last week
-60%
2
Compared to previous week
Last month
50%
12
Compared to previous month
Last year
52.6%
177
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
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
Points can be consumed by IP address, user ID, authorisation token, API route or any other string.
1const opts = { 2 points: 6, // 6 points 3 duration: 1, // Per second 4}; 5 6const rateLimiter = new RateLimiterMemory(opts); 7 8rateLimiter.consume(remoteAddress, 2) // consume 2 points 9 .then((rateLimiterRes) => { 10 // 2 points consumed 11 }) 12 .catch((rateLimiterRes) => { 13 // Not enough points to consume 14 });
RateLimiterRes object
Both Promise resolve and reject return object of RateLimiterRes
class if there is no any error.
Object attributes:
1RateLimiterRes = { 2 msBeforeNext: 250, // Number of milliseconds before next action can be done 3 remainingPoints: 0, // Number of remaining points in current duration 4 consumedPoints: 5, // Number of consumed points in current duration 5 isFirstInDuration: false, // action is first in current duration 6}
You may want to set next HTTP headers to response:
1const headers = { 2 "Retry-After": rateLimiterRes.msBeforeNext / 1000, 3 "X-RateLimit-Limit": opts.points, 4 "X-RateLimit-Remaining": rateLimiterRes.remainingPoints, 5 "X-RateLimit-Reset": new Date(Date.now() + rateLimiterRes.msBeforeNext) 6}
Advantages:
- no race conditions
- no production dependencies
- TypeScript declaration bundled
- allow traffic burst with BurstyRateLimiter
- Block Strategy against really powerful DDoS attacks (like 100k requests per sec) Read about it and benchmarking here
- Insurance Strategy as emergency solution if database / store is down Read about Insurance Strategy here
- works in Cluster or PM2 without additional software See RateLimiterCluster benchmark and detailed description here
- useful
get
,set
,block
,delete
,penalty
andreward
methods
Middlewares, plugins and other packages
- Express middleware
- Koa middleware
- Hapi plugin
- GraphQL graphql-rate-limit-directive
- NestJS try nestjs-rate-limiter
- Fastify based NestJS app try nestjs-fastify-rate-limiter
Some copy/paste examples on Wiki:
- Minimal protection against password brute-force
- Login endpoint protection
- Websocket connection prevent flooding
- Dynamic block duration
- Authorized users specific limits
- Different limits for different parts of application
- Apply Block Strategy
- Setup Insurance Strategy
- Third-party API, crawler, bot rate limiting
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
- Options
- API methods
- BurstyRateLimiter Traffic burst support
- RateLimiterRedis
- RateLimiterMemcache
- RateLimiterMongo (with sharding support)
- RateLimiterMySQL (support Sequelize and Knex)
- RateLimiterPostgres (support Sequelize, TypeORM and Knex)
- RateLimiterCluster (PM2 cluster docs read here)
- RateLimiterMemory
- RateLimiterUnion Combine 2 or more limiters to act as single
- RLWrapperBlackAndWhite Black and White lists
- RateLimiterQueue Rate limiter with FIFO queue
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:
- keyPrefix Make keys unique among different limiters.
- blockDuration Block for N seconds, if consumed more than points.
- inmemoryBlockOnConsumed Avoid extra requests to store.
- inmemoryBlockDuration
- insuranceLimiter Make it more stable with less efforts.
- storeType Have to be set to
knex
, if you use it. - dbName Where to store points.
- tableName Table/collection.
- tableCreated Is table already created in MySQL or PostgreSQL.
- clearExpiredByTimeout For MySQL and PostgreSQL.
Smooth out traffic picks:
Specific:
- indexKeyPrefix Combined indexes of MongoDB.
- timeoutMs For Cluster.
API
Read detailed description on Wiki.
- consume(key, points = 1) Consume points by key.
- get(key) Get
RateLimiterRes
ornull
. - set(key, points, secDuration) Set points by key.
- block(key, secDuration) Block key for
secDuration
seconds. - delete(key) Reset consumed points.
- deleteInMemoryBlockedAll
- penalty(key, points = 1) Increase number of consumed points in current duration.
- reward(key, points = 1) Decrease number of consumed points in current duration.
- getKey(key) Get internal prefixed key.
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.
11. Memory 0.34 ms 22. Cluster 0.69 ms 33. Redis 2.45 ms 44. Memcached 3.89 ms 55. Mongo 4.75 ms
500 concurrent clients with maximum 1000 req per sec during 30 seconds
16. PostgreSQL 7.48 ms (with connection pool max 100) 27. 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 toRateLimiterRes
object._upsert
must be atomic. it inserts or updates value by key and returns raw data. it must supportforceExpire
mode to overwrite key expiration time._get
returns raw data by key ornull
if there is no key._delete
deletes all key related data and returnstrue
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.
No vulnerabilities found.
Reason
GitHub workflow tokens follow principle of least privilege
Details
- Info: topLevel 'contents' permission set to 'read': .github/workflows/test.yml:18
- Info: no jobLevel write permissions found
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
- Info: project has a license file: LICENSE.md:0
- Info: FSF or OSI recognized license: ISC License: LICENSE.md:0
Reason
0 existing vulnerabilities detected
Reason
4 commit(s) and 6 issue activity found in the last 90 days -- score normalized to 8
Reason
Found 5/14 approved changesets -- score normalized to 3
Reason
SAST tool is not run on all commits -- score normalized to 1
Details
- Warn: 3 commits out of 23 are checked with a SAST tool
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/test.yml:24: update your workflow using https://app.stepsecurity.io/secureworkflow/animir/node-rate-limiter-flexible/test.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/test.yml:25: update your workflow using https://app.stepsecurity.io/secureworkflow/animir/node-rate-limiter-flexible/test.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/test.yml:64: update your workflow using https://app.stepsecurity.io/secureworkflow/animir/node-rate-limiter-flexible/test.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/test.yml:67: update your workflow using https://app.stepsecurity.io/secureworkflow/animir/node-rate-limiter-flexible/test.yml/master?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/test.yml:74: update your workflow using https://app.stepsecurity.io/secureworkflow/animir/node-rate-limiter-flexible/test.yml/master?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/test.yml:79: update your workflow using https://app.stepsecurity.io/secureworkflow/animir/node-rate-limiter-flexible/test.yml/master?enable=pin
- Warn: npmCommand not pinned by hash: .github/workflows/test.yml:82
- Warn: npmCommand not pinned by hash: .github/workflows/test.yml:32
- Info: 0 out of 4 GitHub-owned GitHubAction dependencies pinned
- Info: 0 out of 2 third-party GitHubAction dependencies pinned
- Info: 0 out of 2 npmCommand dependencies pinned
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'master'
Score
5.5
/10
Last Scanned on 2025-01-27
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More