Import
RateLimiter
Fixed-window rate limiter. Counts requests within discrete time windows and rejects calls that exceed the limit.
Constructor
Config options
| Property | Type | Default | Description |
|---|---|---|---|
maxRequests | number | — | Maximum number of allowed requests per window |
windowMs | number | — | Window duration in milliseconds |
Methods
| Method | Returns | Description |
|---|---|---|
isAllowed(key?) | boolean | Returns true if the request is within the limit |
getStats(key?) | RateLimiterStats | Returns current window counters |
waitForAllowance(key?) | Promise<void> | Resolves when the next request is allowed |
reset(key?) | void | Resets the counter for a specific key |
resetAll() | void | Resets all counters across every key |
getStats return value
| Property | Type | Description |
|---|---|---|
remaining | number | Requests still allowed in the current window |
resetAt | number | Timestamp (ms) when the window resets |
total | number | Total requests recorded in the current window |
Example
Await allowance before sending
SlidingWindowRateLimiter
Sliding-window variant that tracks individual request timestamps instead of a simple counter. This prevents the burst problem at window boundaries that fixed-window limiters can exhibit.
Constructor
Config options
| Property | Type | Default | Description |
|---|---|---|---|
maxRequests | number | — | Maximum number of allowed requests per window |
windowMs | number | — | Window duration in milliseconds |
Methods
The sliding window limiter exposes the same API asRateLimiter:
| Method | Returns | Description |
|---|---|---|
isAllowed(key?) | boolean | Returns true if the request is within the limit |
getStats(key?) | RateLimiterStats | Returns current window counters |
waitForAllowance(key?) | Promise<void> | Resolves when the next request is allowed |
reset(key?) | void | Resets the counter for a specific key |
resetAll() | void | Resets all counters across every key |
Example
Choosing a strategy
When to use RateLimiter (fixed window)
When to use RateLimiter (fixed window)
Best for simple throughput caps where occasional bursts at window edges are acceptable. Lower memory overhead.
When to use SlidingWindowRateLimiter
When to use SlidingWindowRateLimiter
Best when you need accurate, even distribution of requests over time. Prevents the “double burst” at window boundaries. Uses slightly more memory because it stores individual timestamps.
Per-key rate limiting
Both classes accept an optionalkey parameter on every method. This lets you apply separate limits per endpoint, per user, or per any other dimension.