Design a Rate Limiter

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2024-07-11

Problem Statement

Design a Rate Limiter system that controls the number of requests a client can make within a specified time window. The system should support multiple clients, concurrency, and different limiting strategies while being efficient and thread-safe.


Functional Requirements (FR)


Request Limiting

•Limit requests per client (IP, user ID, API key, etc.) per time window.
•Reject requests exceeding the limit.

Rate Limiting Strategies

•Fixed Window: Allow up to N requests per time window.
•Sliding Window: Smooth limit based on sliding time interval.
•Token Bucket: Tokens generated over time; each request consumes a token.
•Leaky Bucket: Requests leak at a constant rate to control bursts.

Concurrency

•Handle multiple clients sending requests concurrently.
•Ensure accurate counting and enforcement across threads.

Configuration

•Configurable rate limits per client or API.
•Configurable time windows or refill rates.

Optional Features

•Logging of rate-limited events.
•Metrics for monitoring (requests served, throttled requests).
•Distributed support across multiple nodes.


Suggested Classes & Responsibilities


Class: RateLimiter

•Attributes:
•limit (max requests), window (time window), strategy (type of rate limiting)
•requestTimestamps or tokenCount (depends on strategy)
•Methods:
•allowRequest(clientId) → returns true if request allowed, else false
•resetWindow(clientId) → for fixed window strategy
•refillTokens(clientId) → for token bucket strategy

Class: Client

•Attributes: clientId
•Methods: sendRequest() → invokes RateLimiter.allowRequest()
1.Class: RateLimitingStrategy (Interface / Abstract)
•Methods: allowRequest(clientId)

Implementations of Strategy

•FixedWindowStrategy
•SlidingWindowStrategy
•TokenBucketStrategy
•LeakyBucketStrategy
1.Class: MetricsCollector (Optional)
•Tracks request counts, throttled requests, and success rates.


Data Flow (High-Level)


1.Client sends request → RateLimiter receives request → checks strategy.
2.RateLimiter updates internal state (count, token, or timestamp).
3.If within limit → request allowed → forwarded to service.
4.If exceeds limit → request rejected → optionally log and notify client.


Key Design Considerations


•Thread-Safety: Use synchronized methods, atomic counters, or concurrent data structures.
•Time Management: Efficiently track request timestamps or token refill times.
•Memory Efficiency: Avoid storing excessive data per client for sliding window strategies.
•Extensibility: Easily add new rate-limiting algorithms or distributed support.
•Accuracy vs Performance: Balance between strict enforcement and system efficiency.


Solution

Comments