Design an API rate limiter
Problem Statement
π― Objective
Design a Rate Limiter that restricts the number of API requests a user (or client) can make in a specific time window.
The system should ensure fair usage, prevent abuse, and maintain consistent API performance.
πΉ Context
APIs serving multiple clients or users must enforce limits on request rates to protect system stability.
For example:
Your task is to design the class structure and behavior for a reusable and extensible rate limiting component that can be integrated into any backend system or API gateway.
β Functional Requirements
Rate Limit Enforcement
Different Strategies
User-Level Limiting
Configurable Limits
Thread-Safe and Efficient
Response Feedback
βοΈ Non-Functional Requirements
Requirement and Description
Scalability
Should support many users making concurrent requests.
Accuracy
Must correctly enforce time-based limits.
Extensibility
Should allow plugging in different rate-limiting algorithms.
Performance
Should maintain low latency in the decision path.
Thread Safety
Must handle concurrent calls safely.
π§© Core Entities & Responsibilities
Class and Description
RateLimiter (interface)
Defines the contract for any rate limiting algorithm (allowRequest()).
FixedWindowRateLimiter
Implements a simple fixed window counter logic.
SlidingWindowRateLimiter
Implements sliding window using logs/timestamps.
TokenBucketRateLimiter
Allows burst traffic within defined limits.
LeakyBucketRateLimiter
Smooths out incoming requests over time.
RateLimitConfig
Defines the limits (maxRequests, timeWindow) for each user or endpoint.
UserRequestInfo
Maintains the state (timestamps, tokens, counters) per user.
RateLimiterFactory
Provides rate limiter instances based on strategy.
π§Ύ Sample Class Diagram (Text Representation)
1
2βββββββββββββββββββββββββββββ
3β RateLimiter β
4βββββββββββββββββββββββββββββ
5β + allowRequest(userId): bool β
6ββββββββββββββββ¬βββββββββββββ
7 β
8 ββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββ
9 β β β β
10 βΌ βΌ βΌ βΌ
11FixedWindowRateLimiter SlidingWindowRateLimiter TokenBucketRateLimiter LeakyBucketRateLimiterSupporting classes:
1
2βββββββββββββββββββββββββββββ
3β RateLimitConfig β
4βββββββββββββββββββββββββββββ
5β - userId β
6β - maxRequests β
7β - timeWindowSeconds β
8βββββββββββββββββββββββββββββ
9
10βββββββββββββββββββββββββββββ
11β UserRequestInfo β
12βββββββββββββββββββββββββββββ
13β - requestCount β
14β - lastResetTime β
15β - timestamps (for logs) β
16β - availableTokens β
17βββββββββββββββββββββββββββββπ§ Example Flow β Fixed Window Counter
βοΈ Pseudocode Example
1
2class FixedWindowRateLimiter(RateLimiter):
3 def __init__(self, max_requests, window_seconds):
4 self.max_requests = max_requests
5 self.window_sec window_seconds
6 self.user_data = {} # {userId: (count, lastResetTime)}
7
8 def allowRequest(self, user_id):
9 now = time.time()
10 if user_id not in self.user_data:
11 self.user_data[user_id] = [0, now]
12
13 count, last_reset = self.user_data[user_id]
14
15 if now - last_reset > self.window_seconds:
16 # Reset window
17 count = 0
18 last_reset = now
19
20 if count < self.max_requests:
21 count += 1
22 self.user_data[user_id] = [count, last_reset]
23 return True
24 else:
25 return FalseβοΈ Algorithm Choices
| Algorithm | Pros | Cons | Use Case |
| ------------------ | -------------------- | ---------------------- | ----------------- |
| **Fixed Window** | Simple, low overhead | Spike at boundary | Small APIs |
| **Sliding Window** | Smoother limits | Slightly more complex | Real-time systems |
| **Token Bucket** | Allows burst traffic | More state tracking | API gateways |
| **Leaky Bucket** | Smooth outflow | Bursty input discarded | Stream processing |
Design Patterns
| Pattern | Use |
| --------------------- | ----------------------------------------------------------- |
| **Strategy Pattern** | To switch between rate-limiting algorithms dynamically. |
| **Factory Pattern** | To create rate limiter instances for each strategy. |
| **Singleton Pattern** | To maintain one instance of rate limiter per configuration. |
| **Decorator Pattern** | To chain multiple limiters (e.g., user-level + IP-level). |
π Example Interview Prompt Summary
Design an API Rate Limiter.
Build a system that limits how many API calls a user can make within a time window.
The system should support multiple algorithms like token bucket and fixed window, and handle concurrent access safely.
Explain your class design, key methods, and how it ensures thread-safety and configurability.
π§© Possible Extensions