-
-
Notifications
You must be signed in to change notification settings - Fork 163
BurstyRateLimiter
Allow traffic bursts with BurstyRateLimiter
implementation easier than with TokenBucket.
The idea is to rate limit traffic by two limiters: limiter and burst limiter. If there are no points in the first, try to consume from the second limiter. The second limiter usually configured with a wider duration. See the example for details.
const {RateLimiterMemory, BurstyRateLimiter} = require('rate-limiter-flexible');
const http = require('http');
const burstyLimiter = new BurstyRateLimiter(
new RateLimiterMemory({
points: 2,
duration: 1,
}),
new RateLimiterMemory({
keyPrefix: 'burst',
points: 5,
duration: 10,
})
);
const srv = http.createServer(async (req, res) => {
burstyLimiter.consume('test')
.then((rlRes) => {
res.end(JSON.stringify(rlRes));
})
.catch((rej) => {
res.writeHead(429);
res.end(JSON.stringify(rej));
});
});
srv.listen(3000);
This burstyLimiter
limits traffic to 2 requests per second with additional allowance of traffic burst up to 5 requests per 10 seconds.
consume
method of BurstyRateLimiter resolves and rejects with RateLimiterRes object from the first limiter, but msBeforeNext
may be set from the burst limiter if it is less. consume
method never exposes the burst limiter's remaining or consumed points.
Note, if the limiter for burst allowance has a lot of points, it may result in traffic spikes every time when they are refilled.
All limiters from this package can be used for BurstyRateLimiter creation.
Get started
Middlewares and plugins
Migration from other packages
Limiters:
- Redis
- Memory
- DynamoDB
- Prisma
- MongoDB (with sharding support)
- PostgreSQL
- MySQL
- BurstyRateLimiter
- Cluster
- PM2 Cluster
- Memcached
- RateLimiterUnion
- RateLimiterQueue
Wrappers:
- RLWrapperBlackAndWhite Black and White lists
Knowledge base:
- Block Strategy in memory
- Insurance Strategy
- 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