Rate Limiter
Level: Advanced 60–90 minConcepts: AlgorithmsMockingBoundariesStateDesign Patterns
Implement a rate limiter that restricts the number of requests a client can make within a time window.
Requirements
- Create a
RateLimiterwith a configurable max requests and time window (in seconds) allowRequest(clientId)— returnstrueif the request is allowed,falseif rate limited- Each client is tracked independently
- Use a sliding window — requests older than the window are no longer counted
- 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) | Client | Action | Result |
|---|---|---|---|
| 0 | ”alice” | allowRequest | true (1/3) |
| 1 | ”alice” | allowRequest | true (2/3) |
| 2 | ”alice” | allowRequest | true (3/3) |
| 3 | ”alice” | allowRequest | false (limit reached) |
| 3 | ”bob” | allowRequest | true (bob is separate, 1/3) |
| 11 | ”alice” | allowRequest | true (first request expired) |
| 11 | ”alice” | allowRequest | true (second request expired) |
| 11 | ”alice” | allowRequest | false (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)