Sliding Window Rate Counter

Enforce a per-key request rate limit with a sliding window of timestamps, smoothing the bursts a fixed window allows.

JavascriptResilience

Code

javascriptsnippet
21 lines
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

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.