Fixed Window Rate Limiter With Burst Accounting

Limit requests per key with fixed windows, explicit costs, reset timestamps, retry hints and bounded state for many client keys.

TypescriptResilience

Code

typescriptsnippet
88 lines
export interface RateLimitResult {
  allowed: boolean;
  remaining: number;
  resetAt: number;
  retryAfterMs: number;
}

export interface RateLimiterOptions {
  limit: number;
  windowMs: number;
  now?: () => number;
  maxKeys?: number;
}

interface WindowState {
  count: number;
  resetAt: number;
}

export class FixedWindowRateLimiter {
  private readonly limit: number;
  private readonly windowMs: number;
  private readonly now: () => number;
  private readonly maxKeys: number;
  private readonly windows = new Map<string, WindowState>();

  constructor(options: RateLimiterOptions) {
    if (!Number.isInteger(options.limit) || options.limit < 1) {
      throw new RangeError("limit must be a positive integer");
    }
    if (!Number.isFinite(options.windowMs) || options.windowMs <= 0) {
      throw new RangeError("windowMs must be a positive finite number");
    }
    const maxKeys = options.maxKeys ?? 10_000;
    if (!Number.isInteger(maxKeys) || maxKeys < 1) {
      throw new RangeError("maxKeys must be a positive integer");
    }
    this.limit = options.limit;
    this.windowMs = options.windowMs;
    this.now = options.now ?? Date.now;
    this.maxKeys = maxKeys;
  }

  consume(key: string, cost: number = 1): RateLimitResult {
    if (typeof key !== "string" || key.length === 0) {
      throw new TypeError("key must be a non-empty string");
    }
    if (!Number.isInteger(cost) || cost < 1) {
      throw new RangeError("cost must be a positive integer");
    }
    const now = this.now();
    if (!Number.isFinite(now)) throw new RangeError("now must return a finite timestamp");

    let state = this.windows.get(key);
    if (!state || now >= state.resetAt) {
      if (!state && this.windows.size >= this.maxKeys) this.evict(now);
      state = { count: 0, resetAt: now + this.windowMs };
      this.windows.set(key, state);
    }

    const allowed = state.count + cost <= this.limit;
    if (allowed) state.count += cost;
    return {
      allowed,
      remaining: Math.max(0, this.limit - state.count),
      resetAt: state.resetAt,
      retryAfterMs: allowed ? 0 : Math.max(0, state.resetAt - now),
    };
  }

  reset(key?: string): void {
    if (key === undefined) this.windows.clear();
    else this.windows.delete(key);
  }

  get size(): number {
    return this.windows.size;
  }

  private evict(now: number): void {
    for (const [key, state] of this.windows) {
      if (now >= state.resetAt) this.windows.delete(key);
    }
    if (this.windows.size < this.maxKeys) return;
    const oldest = this.windows.keys().next();
    if (!oldest.done) this.windows.delete(oldest.value);
  }
}

How it works

Count the class FixedWindowRateLimiter as the entire surface area of Fixed Window Rate Limiter With Burst Accounting.

The one repetition in this snippet is the loop for (const [key, state] of this.windows). When the guard condition holds, RangeError and TypeError is thrown rather than a bogus value returned.

The result comes back as an object carrying allowed, resetAt.

What to watch for

  • The guard typeof key !== "string" || key.length === 0 short-circuits the flow with an early throw when its condition holds.

Using it

FixedWindowRateLimiter is what another module would consume; nothing else here is load-bearing for callers.

The call returns allowed, resetAt — destructure what you need at the call site.

Key statements

if (!Number.isFinite(now)) throw new RangeError("now must return a finite timestamp");
throw new RangeError("windowMs must be a positive finite number");
throw new RangeError("maxKeys must be a positive integer");

Interactive Tools for This Topic

FAQ

Does `FixedWindowRateLimiter` modify its input?
No — a new value is constructed for the result and the arguments are never written to.
How does the code behave when input is bad?
The code refuses to continue: `RangeError` and `TypeError` is thrown while the state is still recoverable.
Are there dependencies to manage?
No. There are no dependencies to declare or install.