Sliding Window Rate Limiter (JavaScript)

Track request timestamps in a sliding window to count how many calls happened in the last interval, rejecting requests that exceed the allowed rate.

JavascriptResilience

Code

javascriptsnippet
15 lines
export function createRateLimiter({ limit, windowMs }) {
  if (!Number.isInteger(limit) || limit <= 0) {
    throw new RangeError("limit must be a positive integer");
  }
  const hits = [];
  return function allow(now = Date.now()) {
    const cutoff = now - windowMs;
    while (hits.length > 0 && hits[0] <= cutoff) hits.shift();
    if (hits.length >= limit) {
      return { allowed: false, retryAfterMs: hits[0] + windowMs - now };
    }
    hits.push(now);
    return { allowed: true, remaining: limit - hits.length };
  };
}

How it works

The working surface is the functions createRateLimiter and allow — everything else is wiring.

Repetition is confined to while (hits.length > 0 && hits[0] <= cutoff) hits.shift(); — the rest of the file is straight-line. Invalid states are rejected up front: it throws RangeError instead of continuing with bad data.

The result comes back as an object carrying false.

Watch out for

  • The guard hits.length >= limit short-circuits the flow with an early return when its condition holds.

Putting it to use

The main signature reads export function createRateLimiter({ limit, windowMs })

Treat createRateLimiter as the API: import it, and ignore the supporting code.

The call returns false.

Core lines

return { allowed: false, retryAfterMs: hits[0] + windowMs - now };
throw new RangeError("limit must be a positive integer");
return { allowed: true, remaining: limit - hits.length };

Interactive Tools for This Topic

FAQ

Does `createRateLimiter` modify its input?
It does not. Inputs are only read; the return value is freshly built.
How are precondition violations signaled?
The code refuses to continue: `RangeError` is thrown while the state is still recoverable.
Is anything beyond the standard library required?
Nothing beyond the standard library — the snippet is dependency-free. The file defines `createRateLimiter`, `allow` at load time.