-
-
Notifications
You must be signed in to change notification settings - Fork 179
Options
You can change any option in runtime, e.g. rateLimiter.points = 50 will change number of allowed points. rateLimiter.duration = 5 won't change already created keys, but it will affect all new keys.
- points
- duration
- keyPrefix
- blockDuration
- storeClient
- inMemoryBlockOnConsumed
- inMemoryBlockDuration
- insuranceLimiter
- storeType
- dbName
- tableName
- tableCreated
- clearExpiredByTimeout
- execEvenly
- execEvenlyMinDelayMs
Specific:
Mongo
Nodejs Cluster
Redis
PostgreSQL
DynamoDB
Drizzle
-
Default: 'rlflx'It is required when you need to create two or more limiters with different options so keys don't interfere with different limiters.
Set to empty string
'', if keys should be stored without prefix.Note: for some limiters it should correspond to Storage requirements for tables or collections name, as
keyPrefixmay be used as their name. -
Default: 4Maximum number of points can be consumed over duration. Limiter compares this number with number of consumed points by key to reject or resolve an action.
pointsvalue can be updated anytime, e.g.rateLimiter.points = 3. Take a look at this test case. -
Default: 1Number of seconds before consumed points are reset, starting from the time of the first consumed point on a key. Points will be reset every second if the duration is set to 1 second.
Points never expire, if
durationis 0. -
Default: 0If blockDuration is a positive number and more points are consumed than available, the limiter prolongs points lifetime for
blockDurationseconds. It rejects further consume calls for that key during this blockDuration time.This feature can be used to stop malicious activities for an extended period.
-
Required for Redis, Memcached, MongoDB, MySQL, PostgreSQL, etcHave to be
redis,ioredis,memcached,mongodb,pg,mysql2,mysqlor any other related pool or connection. -
Default: 0For Redis, Memcached, MongoDB, MySQL, PostgreSQL, etc.
Can be used against DDoS attacks. In-memory blocking works in current process memory and for
consumemethod only.It blocks a key in memory for msBeforeNext milliseconds from the last consume result, if
inMemoryBlockDurationis not set. This helps to avoid extra requests.inMemoryBlockOnConsumedvalue is supposed to be equal or more thanpointsoption. Sometimes it is not necessary to increment counter on store, if all points are consumed already. -
Default: 0Block key for
inMemoryBlockDurationseconds, ifinMemoryBlockOnConsumedor more points are consumed. Set it the same asblockDurationoption for distributed application to have consistent result on all processes. -
Default: undefinedInstance of RateLimiterAbstract extended object to store limits, when database comes up with any error.
All data from
insuranceLimiteris NOT copied to parent limiter, when error goneNote:
insuranceLimiterautomatically setupblockDurationandexecEvenlyto same values as in parent to avoid unexpected behaviour
-
For MySQL and PostgreSQL it is required only for Knex and have to be set to 'knex'.
For SQLite limiter it should be set if you use 'better-sqlite3' or 'knex' packages, defaulting to 'sqlite3'.
-
Default for MySQL: 'rtlmtrflx'Default for MongoDB: 'node-rate-limiter-flexible'Database where limits are stored. It is created during creating a limiter. Doesn't work with Mongoose, as mongoose connection is established to exact database.
-
Default: equals to 'keyPrefix' optionFor MongoDB, MySQL, PostgreSQL, SQLite.
By default, limiter creates a table for each unique
keyPrefix.tableNameoption sets table/collection name where values should be stored. -
Default: falseFor MySQL, PostgreSQL, SQLite, and DynamoDB.Do not create a table for rate limiter, if
tableCreated=true.readycallback in construct can be safely omitted if table already created. -
Default: trueFor MySQL, SQLite, and PostgreSQL.Rate limiter deletes data expired more than 1 hour ago every 5 minutes.
Note, call
rateLimiter.clearExpired(Date.now() - 3600000)manually to remove expired rows in AWS Lambda or GCP function. -
Default: falseDelay action to be executed evenly over duration. First action in duration is executed without delay. All next allowed actions in current duration are delayed by formula
msBeforeDurationEnd / (remainingPoints + 2)with minimum delay ofduration * 1000 / points. It allows to cut off load peaks similar way to Leaky Bucket. Read about it more in this article.Note: it isn't recommended to use it for long duration and few points, as it may delay action for too long with default
execEvenlyMinDelayMs. -
Default: duration * 1000 / pointsSets minimum delay in milliseconds, when action is delayed with
execEvenly
-
Default: {}Object which is used to create combined index by
{...indexKeyPrefix, key: 1}attributes. -
Default: falseDisable indexes creation that are created by default on limiter creation. Call async
createIndexesmanually. Note, without indexes no limiter would work properly.const limiter = new RateLimiterMongo({ storeClient: mongoClient, disableIndexesCreation: true }); await limiter.createIndexes();
-
Default: 5000Timeout for communication between worker and master over IPC. If master doesn't response in time, promise is rejected with Error
-
Default: falseIf set to
trueRateLimiterRedis rejects requests immediately when Redis client status is notready. Useful for high traffic applications or / and in combination with insuranceLimiter. -
Use custom Lua script to make increments. See this rejected when consume more than maximum points and multiply delay test for example.
-
By default it identifies
redispackage correctly, but they changed so much, so you can setuseRedisPackageoption totrueexplicitly if this doesn't work out of the box. If set totruestoreClientshould be created withredispackage of version 4+. -
Default: falseDanger!It isn't fully supported. Test it carefully or just upgrade yourredispackage to version 4 or later. If set totruestoreClientshould be created withredispackage of version 3 or lower.
-
By default it connects to
publicor your default schema. UseschemaNameoption to store data in different schema.
-
By default it is set to:
{ readCapacityUnits: 25, writeCapacityUnits: 25, }
-
Default: falseBy default RateLimiterDynamo requests DynamoDB to check TTL settings. You can set
ttlSetoption totrueto skip TTL requests during limiter instantiation. This could be useful in a serverless environment.
-
Required.
Example:
const rateLimiterFlexible = pgTable('RateLimiterFlexible', {
key: text('key').primaryKey(),
points: integer('points').notNull(),
expire: timestamp('expire'),
})Get started
Middlewares and plugins
Migration from other packages
Limiters:
- Cluster
- Drizzle
- DynamoDB
- Etcd
- Memcached
- Memory
- MongoDB (with sharding support)
- MySQL
- PM2 Cluster
- PostgreSQL
- Prisma
- Redis
- SQLite
- Valkey: iovalkey and Valkey Glide
- BurstyRateLimiter
- RateLimiterUnion
- RateLimiterQueue
Wrappers:
- AWS SDK v3 Client Rate Limiter
- RLWrapperBlackAndWhite Black and White lists
- RLWrapperTimeouts Timeouts
Knowledge base:
- Block Strategy in memory
- Insurance Strategy
- Periodic sync to reduce number of requests
- Comparative benchmarks
- Smooth out traffic peaks
-
Usage example
- Minimal protection against password brute-force
- Login endpoint protection
- Websocket connection prevent flooding
- Dynamic block duration
- Different limits for authorized users
- Different limits for different parts of application
- Block Strategy in memory
- Insurance Strategy
- Third-party API, crawler, bot rate limiting