Design a rate-limiter

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2023-11-27

Problem Statement

Design and implement a Rate Limiter system that controls the number of requests a user (or client) can make to an API/service within a specified time window. The system should support multiple algorithms for rate limiting, ensure fairness across clients, and provide high performance.


Functional Requirements (FR)


Core Rate Limiting


•Allow at most N requests per user/client within a given time window.
•If the limit is exceeded, reject the request with an appropriate response (429 Too Many Requests).


Algorithms to Support


•Fixed Window Counter: Requests are counted in discrete time windows.
•Sliding Window: More accurate windowing with rolling intervals.
•Token Bucket / Leaky Bucket: Smooth request handling by replenishing tokens at a fixed rate.


Client-specific Limits


•Different clients may have different rate limits.
•System should support per-API, per-user, or global rate limits.


Concurrency Handling


•Must handle concurrent requests safely without race conditions.


Non-Functional Requirements (NFR)


•Performance: checkRequest() should be O(1).
•Thread Safety: Must handle concurrent API requests.
•Scalability: Should be extensible to handle thousands of users in a distributed system (optional for base LLD).
•Extensibility: Easy to add new rate limiting strategies.


Core Classes / Entities


RateLimiter (Interface/Abstract Class)


•boolean allowRequest(String clientId)


FixedWindowRateLimiter (extends RateLimiter)


•Attributes: windowSize, maxRequests, Map<clientId, counter & timestamp>
•Logic: Count requests within the current window. Reset counter when window changes.


SlidingWindowRateLimiter (extends RateLimiter)


•Attributes: windowSize, maxRequests, Map<clientId, Deque<Timestamps>>
•Logic: Maintain timestamps of requests, evict expired ones.


TokenBucketRateLimiter (extends RateLimiter)


•Attributes: bucketCapacity, refillRate, Map<clientId, tokens & lastRefillTime>
•Logic: Add tokens periodically, allow request if tokens > 0.


ClientConfig


•Attributes: clientId, limit, strategyType
•Holds configuration for each client.


Key Operations


•allowRequest(clientId) → Returns true if request is allowed, else false.
•setLimit(clientId, maxRequests, strategyType) → Configures client-specific limits.
•refillTokens() (for token bucket).


Example Usage


•RateLimiter rl = new TokenBucketRateLimiter(10, 2) → 10 capacity, 2 tokens/second.
•rl.allowRequest("user1") → ✅ allowed.
•If user1 makes 12 requests in one second → last 2 are ❌ rejected.


✅ This is the LLD problem statement for a Rate Limiter.

Solution

Comments