Design Rate Limiter
Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2025-05-05
Problem Statement
Designing a Rate Limiter that controls how frequently a particular action or API request can be performed. The design should be thread-safe, efficient, and scalable.
✅ Functional Requirements
1.Limit API Requests
•Restrict the number of requests from a user, IP, or service within a fixed time window.
•Example: 100 requests per minute per user.
2.Support Multiple Strategies
•Fixed Window Counter: Limit requests per fixed interval (e.g., per minute).
•Sliding Window Log / Sliding Window Counter: More precise rate limiting with smoother request distribution.
•Optional: Token Bucket / Leaky Bucket: Allow burst traffic but maintain average rate.
3.API Methods
•allowRequest(userId): Returns true if request is allowed, false if rate limit exceeded.
•Optional: reset(userId): Reset counter for a user.
•Optional: setLimit(userId, limit, window): Set custom limits per user.
4.Thread Safety & Concurrency
•Multiple threads may call allowRequest concurrently.
•Ensure no race conditions or overcounting.
5.Scalability
•Handle millions of users efficiently.
•Efficient memory and computation per user.
🔐 Constraints & Assumptions
•Focus on LLD, concurrency, and rate limiting strategies, not distributed deployment.
•Single-machine implementation is acceptable, can discuss extensions for distributed environments.
•Users/clients identified by a unique userId or key.
🧱 Key Components & Classes
1.RateLimiter Class
1
2class RateLimiter {
3private:
4 int limit; // max requests
5 int windowInSeconds; // time window in seconds
6 unordered_map<string, vector<long>> userRequestLog; // userId -> timestamps
7 mutex mtx; // protect concurrent access
8
9public:
10 RateLimiter(int limit, int windowInSeconds);
11
12 bool allowRequest(string userId);
13 void reset(string userId); // optional
14};1.allowRequest Method (Sliding Window Example)
1
2bool RateLimiter::allowRequest(string userId) {
3 lock_guard<mutex> lock(mtx);
4 long currentTime = getCurrentTimestamp();
5
6 auto ×tamps = userRequestLog[userId];
7
8 // Remove expired timestamps
9 while (!timestamps.empty() && timestamps.front() <= currentTime - windowInSeconds) {
10 timestamps.erase(timestamps.begin());
11 }
12
13 if (timestamps.size() < limit) {
14 timestamps.push_back(currentTime);
15 return true;
16 } else {
17 return false;
18 }
19}1.Optional Token Bucket Implementation
•Keep track of tokens per user, refill at a fixed rate.
•Allows bursts while enforcing average rate.
🔄 Example Workflow
1.User A sends request → allowRequest(A) → allowed → log timestamp.
2.User B sends requests → checked against limit → denied if exceeded.
3.Sliding window removes old timestamps automatically → ensures accurate request count.
🧪 Expected Deliverables
•Class diagram showing RateLimiter and associated data structures.
•Implementation of allowRequest with thread-safety.
•Test cases:
•Single-threaded request flow
•Multi-threaded request flow
•Edge cases: requests at window boundary, burst traffic
•Reset or custom limit per user
💡 Discussion Points / Trade-offs
1.Fixed Window vs Sliding Window
•Fixed window → simpler but can allow burst at boundary.
•Sliding window → smoother enforcement, slightly higher memory overhead.
2.Concurrency & Locks
•Single lock per RateLimiter → simple, may reduce throughput.
•Fine-grained locks per user → higher concurrency, more complex.
3.Memory Optimization
•For large user base → keep only necessary recent timestamps or counters.
•Use circular buffer or queue for sliding window logs.
4.Extensibility
•Support distributed rate limiter using Redis / Memcached for shared state.
•Add multiple strategies: token bucket, leaky bucket, etc.