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.
Code
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 };
};
}Report a problem with this exampleOpens a pre-filled issue on GitHub.