typescriptadvanced

Sliding Window Rate Limiter

Implements sliding window rate limiting that distributes limits more evenly than fixed windows.

typescript
class SlidingWindowRateLimiter {
  private windows = new Map<string, { current: number; previous: number; timestamp: number }>();

  constructor(
    private readonly limit: number,
    private readonly windowMs: number
  ) {}

  isAllowed(key: string): boolean {
    const now = Date.now();
    const windowStart = Math.floor(now / this.windowMs) * this.windowMs;
    const entry = this.windows.get(key) || { current: 0, previous: 0, timestamp: windowStart };

    if (entry.timestamp !== windowStart) {
      entry.previous = entry.timestamp === windowStart - this.windowMs ? entry.current : 0;
      entry.current = 0;
      entry.timestamp = windowStart;
    }

    const elapsed = (now - windowStart) / this.windowMs;
    const estimated = entry.previous * (1 - elapsed) + entry.current;

    if (estimated >= this.limit) return false;

    entry.current++;
    this.windows.set(key, entry);
    return true;
  }
}

export { SlidingWindowRateLimiter };

Use Cases

  • API rate limiting
  • DDoS protection

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.