Rate Limiter

HardUtility Functions25 min4 tests

Implement a createRateLimiter that limits how many times a function can be called within a time window.

Requirements

  • createRateLimiter(fn, maxCalls, windowMs) — return a rate-limited version of fn
  • Allow at most maxCalls invocations per windowMs milliseconds
  • Calls exceeding the limit should be dropped (return undefined)
  • The window is sliding: old calls expire after windowMs

Example

const limited = createRateLimiter(x => x, 2, 100);
limited(1); // 1
limited(2); // 2
limited(3); // undefined (rate limited)
// After 100ms...
limited(4); // 4
Hints (4)
  1. Track the timestamps of each call in an array.
  2. Before each call, remove timestamps older than windowMs.
  3. If the remaining count exceeds maxCalls, drop the call.
  4. Otherwise, record the timestamp and invoke the function.

Topics

  • Utility Functions

Asked at

Stripe · Cloudflare · Amazon · Google

Join Us
blur