Gathering detailed insights and metrics for rate-limiter-flexible
Gathering detailed insights and metrics for rate-limiter-flexible
Gathering detailed insights and metrics for rate-limiter-flexible
Gathering detailed insights and metrics for rate-limiter-flexible
limiter
A generic rate limiter for the web and node.js. Useful for API clients, web crawling, or other tasks that need to be throttled
@konceiver/hapi-rate-limiter-flexible
An integration for node-rate-limiter-flexible into hapi.js
egg-rate-limiter-flexible
egg rate limiter flexible
express-rate-limit
Basic IP rate-limiting middleware for Express. Use to limit repeated requests to public APIs and/or endpoints such as password reset.
Atomic counters and rate limiting tools. Limit resource access at any scale.
npm install rate-limiter-flexible
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
Fix memory storage being not accurate with expired keys
Published on 08 Dec 2023
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
3,079 Stars
701 Commits
163 Forks
22 Watching
4 Branches
42 Contributors
Updated on 26 Nov 2024
JavaScript (100%)
Cumulative downloads
Total Downloads
Last day
-1.3%
134,738
Compared to previous day
Last week
6.3%
728,674
Compared to previous week
Last month
7%
2,953,434
Compared to previous month
Last year
73.7%
25,000,293
Compared to previous year
rate-limiter-flexible counts and limits the number of actions by key and protects from DDoS and brute force attacks at any scale.
It works with Redis, Prisma, DynamoDB, process Memory, Cluster or PM2, Memcached, MongoDB, MySQL, and PostgreSQL.
Memory limiter also works in the browser.
Atomic increments. All operations in memory or distributed environment use atomic increments against race conditions.
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 a 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.
Allow traffic bursts with BurstyRateLimiter.
Deno compatible See this example
It uses a fixed window, as it is much faster than a rolling window. See comparative benchmarks with other libraries here
npm i --save rate-limiter-flexible
yarn add rate-limiter-flexible
1// CommonJS 2const { RateLimiterMemory } = require("rate-limiter-flexible"); 3 4// or 5 6// ECMAScript 7import { RateLimiterMemory } from "rate-limiter-flexible"; 8// or 9import RateLimiterMemory from "rate-limiter-flexible/lib/RateLimiterMemory.js";
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 });
The Promise's resolve
and reject
callbacks both return an instance of the RateLimiterRes
class if there is no 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 HTTP headers for the 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}
get
, set
, block
, delete
, penalty
and reward
methodsFull documentation is on Wiki
Some copy/paste examples on Wiki:
See releases for detailed changelog.
points
Default: 4
Maximum number of points that can be consumed over duration
duration
Default: 1
Number of seconds before consumed points are reset.
Points are never reset if duration
is set to 0.
storeClient
Required for store limiters
Must be redis
, ioredis
, memcached
, mongodb
, pg
, mysql2
, mysql
or any other related pool or connection.
knex
, if you use it.Smooth out traffic peaks:
Specific:
Read detailed description on Wiki.
RateLimiterRes
or null
.secDuration
seconds.Average latency during test of 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.
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 must be extended from RateLimiterStoreAbstract
.
It has to implement 4 methods:
_getRateLimiterRes
parses raw data from store to RateLimiterRes
object.
_upsert
may be atomic or non-atomic upsert (increment). It inserts or updates the value by key and returns raw data.
If it doesn't make an atomic upsert (increment), the class should be suffixed with NonAtomic
, e.g. RateLimiterRedisNonAtomic
.
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 the store. See RateLimiterRedis
or RateLimiterPostgres
for examples.
Note: all changes should be covered by tests.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
6 commit(s) and 9 issue activity found in the last 90 days -- score normalized to 10
Reason
GitHub workflow tokens follow principle of least privilege
Details
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
Reason
Found 5/13 approved changesets -- score normalized to 3
Reason
SAST tool is not run on all commits -- score normalized to 1
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Score
Last Scanned on 2024-11-25
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