Rate Limiter

Level: Advanced 60–90 min

Concepts: AlgorithmsMockingBoundariesStateDesign Patterns


Implement a rate limiter that restricts the number of requests a client can make within a time window.

Requirements

  1. Create a RateLimiter with a configurable max requests and time window (in seconds)
  2. allowRequest(clientId) — returns true if the request is allowed, false if rate limited
  3. Each client is tracked independently
  4. Use a sliding window — requests older than the window are no longer counted
  5. The limiter should accept an injectable clock/time source for testability

Test Cases

Given a rate limiter configured for 3 requests per 10 seconds:

Time (s)ClientActionResult
0”alice”allowRequesttrue (1/3)
1”alice”allowRequesttrue (2/3)
2”alice”allowRequesttrue (3/3)
3”alice”allowRequestfalse (limit reached)
3”bob”allowRequesttrue (bob is separate, 1/3)
11”alice”allowRequesttrue (first request expired)
11”alice”allowRequesttrue (second request expired)
11”alice”allowRequestfalse (third request still in window)

Bonus

  • Implement token bucket algorithm as an alternative strategy
  • Add remainingRequests(clientId) — returns how many requests the client has left
  • Add retryAfter(clientId) — returns seconds until the next request will be allowed
  • Add burst allowance — permit short bursts above the rate limit with a separate burst quota
  • Support tiered limits — different rate limits for different client tiers (free, pro, enterprise)