Sliding Window Rate Counter
Enforce a per-key request rate limit with a sliding window of timestamps, smoothing the bursts a fixed window allows.
Code
export class SlidingWindowLimiter {
constructor(limit, windowMs) {
if (!Number.isInteger(limit) || limit <= 0) throw new RangeError('limit must be positive');
if (!Number.isInteger(windowMs) || windowMs <= 0) throw new RangeError('windowMs must be positive');
this.limit = limit;
this.windowMs = windowMs;
this.hits = new Map();
}
allow(key, now = Date.now()) {
const cutoff = now - this.windowMs;
const times = (this.hits.get(key) ?? []).filter((t) => t > cutoff);
if (times.length >= this.limit) {
this.hits.set(key, times);
return { allowed: false, retryAfterMs: times[0] + this.windowMs - now };
}
times.push(now);
this.hits.set(key, times);
return { allowed: true, remaining: this.limit - times.length };
}
}Inside the snippet
Sliding Window Rate Counter keeps everything in the class SlidingWindowLimiter and the function times.
Invalid states are rejected up front: it throws RangeError instead of continuing with bad data.
The result comes back as an object carrying false.
Using it
The surface worth importing is SlidingWindowLimiter; the helpers around it are private to the snippet.
The call returns false.
Key statements
const times = (this.hits.get(key) ?? []).filter((t) => t > cutoff);
if (!Number.isInteger(windowMs) || windowMs <= 0) throw new RangeError('windowMs must be positive');
if (!Number.isInteger(limit) || limit <= 0) throw new RangeError('limit must be positive');
Interactive Tools for This Topic
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.Word Frequency CounterCount word occurrences in text with Unicode-aware tokenization, optional lowercasing, and a ranked frequency table.
FAQ
- Does `SlidingWindowLimiter` modify its input?
- No — a new value is constructed for the result and the arguments are never written to.
- Is there a failure path for bad input?
- `RangeError` is raised at the guard, so invalid state never reaches the main logic.
- Does the code pull in any external packages?
- No external packages are involved; every call resolves to a built-in API. The file defines `times` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.