Design an API rate limiter

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2022-05-02

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:


β€’A free user can make 100 requests per minute.
β€’A premium user can make 1000 requests per minute.


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

β€’Allow only N requests in a defined time window (e.g., 100 requests/minute per user).
β€’Deny or throttle requests exceeding the limit.

Different Strategies

β€’Support multiple rate-limiting algorithms:
β€’Fixed Window Counter
β€’Sliding Window Log
β€’Token Bucket
β€’Leaky Bucket

User-Level Limiting

β€’Limit requests per user ID or API key.

Configurable Limits

β€’Different users or endpoints can have custom rate limits.

Thread-Safe and Efficient

β€’The limiter should handle concurrent access in multi-threaded environments.

Response Feedback

β€’Return whether a request is allowed or rejected, along with remaining quota.


βš™οΈ 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 LeakyBucketRateLimiter

Supporting 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


1.User A has limit: 100 requests per minute.
2.At time T0, user starts making requests.
3.The system increments the counter for user A.
4.If the counter exceeds 100 within the same minute window β€” request is rejected.
5.After the minute window resets, the counter starts from zero.


βš™οΈ 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

β€’Distributed rate limiting using Redis or Memcached.
β€’Dashboard for monitoring rate limit usage.
β€’Global throttling by endpoint or IP.
β€’Dynamic limits based on subscription tier.
β€’Alerting when users hit thresholds.


Solution

Comments