-
-
Notifications
You must be signed in to change notification settings - Fork 185
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:
- 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