Loading...
Loading...
You are building a high-throughput payment API that needs to protect against abuse and ensure fair usage. Your task is to implement a Sliding Window Rate Limiter that tracks API requests per user and determines whether each incoming request should be allowed or rejected.
Implement a RateLimiter class using the sliding window algorithm. The rate limiter should allow a maximum of maxRequests requests per windowSizeInSeconds for each unique user.
The sliding window ensures that at any point in time, no user has made more than maxRequests requests in the last windowSizeInSeconds seconds.
class RateLimiter:
def __init__(self, maxRequests: int, windowSizeInSeconds: int):
# Initialize the rate limiter
pass
def allowRequest(self, userId: str, timestamp: int) -> bool:
# Returns True if the request is allowed, False otherwise
pass
Constructor:
maxRequests — maximum number of requests allowed per windowwindowSizeInSeconds — the duration (in seconds) of the sliding windowallowRequest(userId, timestamp):
userId — string identifier for the requesting usertimestamp — integer representing the current time in seconds (non-decreasing per user)True if the request is allowed, False if the user has exceeded their limitallowRequest, evict timestamps that fall outside the sliding window (i.e., timestamp - windowSizeInSeconds).maxRequests, allow the request and record the timestamp.1 <= maxRequests <= 1000 1 <= windowSizeInSeconds <= 3600 1 <= timestamp <= 10^9 1 <= userId.length <= 50 userIds contain only lowercase letters and digits Timestamps per userId are non-decreasing Total number of allowRequest calls: 1 <= calls <= 10^4
Example 1: maxRequests=3, windowSizeInSeconds=5
| Call | userId | timestamp | Result |
|---|---|---|---|
| 1 | "alice" | 1 | True |
| 2 | "alice" | 2 | True |
| 3 | "alice" | 3 | True |
| 4 | "alice" | 4 | False |
| 5 | "alice" | 6 | True |
At timestamp 6, the request at timestamp 1 falls outside the window [2, 6], so alice only has 2 requests in the window and a new one is allowed.
Example 2: maxRequests=2, windowSizeInSeconds=10
Two different users ("bob" and "carol") have independent limits.