sliding-window-limiter
v1.0.1
Published
Implementation of the Sliding Window rate limiting algorithm
Maintainers
Readme
sliding-window-limiter
A JavaScript implementation of the Sliding Window rate limiting algorithm.
Features
- Sliding window rate limiting with configurable window size, unit, and slice width
- Pluggable persistence store (in-memory by default)
- Written in modern JavaScript, using lodash and luxon
- Thoroughly tested with Jest
Installation
npm install sliding-window-limiterUsage
const { RateLimiter } = require('sliding-window-limiter');
const limiter = new RateLimiter({
name: 'api-rate-limit',
max: 100, // max requests per window
window: {
unit: 'minute', // time unit for window
size: 10, // number of slices in window
width: 1, // width of each slice
},
store: customStore, // optional: provide your own store
});
// To check and update the rate limit:
const allowed = await limiter.update(1, new Date());
if (!allowed) {
// Rate limit exceeded
}API
RateLimiter
Constructor
new RateLimiter(config)config.name(string): Unique name for the limiterconfig.max(number): Maximum allowed value in the windowconfig.window(object): Window configurationunit(string): Time unit (second,minute,hour, etc.)size(number): Number of slices in the windowwidth(number): Width of each slice
config.store(object): Store for persistence (must implementgetandset)
Methods
static async RateLimiter.load(config): Loads a limiter and its state from the storeasync update(value, timestamp): Attempts to addvalueattimestamp. Returnstrueif allowed,falseif limit exceeded.set(state): Sets the internal window statevalueOf(): Returns the current sum of the window
Window
- Internal class for managing the sliding window logic
Testing
Run all tests with:
npm testLicense
ISC
Author
Dima Michaelov
