Rate Limiter

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2025-04-13

Problem Statement

Designing and implementing a Rate Limiter that controls the number of requests a client can make to a service in a given time window. The focus is on modular, object-oriented design that supports different limiting strategies and can be extended in future.


✅ Functional Requirements


1.<span></span>Basic Functionality
2.<span></span>Allow a maximum of N requests per client within a specified time window (e.g., 100 requests per minute).
3.<span></span>Block or reject requests exceeding the limit.
4.<span></span>Provide an API:
<div><div><br /></div><div>bool allowRequest(String clientId)</div></div>
1.<span></span>Returns true if allowed, false otherwise.
2.<span></span>Limiting Strategies (Optional Extensions)
3.<span></span>Fixed Window: Count requests in a fixed time interval.
4.<span></span>Sliding Window: Count requests in a rolling time interval.
5.<span></span>Token Bucket / Leaky Bucket: Smooth out bursts while enforcing rate limits.
6.<span></span>Metrics & Monitoring
7.<span></span>Track number of requests per client.
8.<span></span>Provide ability to reset counters.
9.<span></span>Optionally, track remaining quota per client.


🔐 Constraints & Assumptions


1.<span></span>Single-node in-memory implementation for LLD; distributed version is optional.
2.<span></span>Clients are identified by a unique client ID.
3.<span></span>Time granularity can be in seconds or milliseconds, depending on requirement.
4.<span></span>Thread-safety is required if multiple threads may access the rate limiter concurrently.


🧱 Key Components & Classes


1.<span></span>RateLimiter (Interface/Base Class)
2.<span></span>allowRequest(clientId)
3.<span></span>reset(clientId)
4.<span></span>FixedWindowRateLimiter (inherits RateLimiter)
5.<span></span>Maintains a map of clientId → request count + window start timestamp
6.<span></span>SlidingWindowRateLimiter (inherits RateLimiter)
7.<span></span>Maintains a map of clientId → queue of timestamps
8.<span></span>TokenBucketRateLimiter (inherits RateLimiter)
9.<span></span>Maintains a map of clientId → tokens + last refill timestamp


🔄 Example Workflow


1.<span></span>Fixed Window:
2.<span></span>Client A makes a request → check request count in current window → allow if count < limit, else reject.
3.<span></span>Window resets after predefined interval.
4.<span></span>Sliding Window:
5.<span></span>Client A makes a request → remove timestamps older than windowSize → allow if remaining timestamps < limit, else reject.


🧪 Expected Deliverables


1.<span></span>Class diagram showing RateLimiter interface and different implementations.
2.<span></span>Implement at least one strategy (e.g., Fixed Window) in code.
3.<span></span>Test cases:
4.<span></span>Requests under limit → allowed
5.<span></span>Requests exceeding limit → blocked
6.<span></span>Window reset → requests allowed again


Solution

Comments