API Rate Limiter
Start Timer
0:00:00
Given a stream of API requests, each identified by an API key, write a class RateLimiter that throttles each key with its own token bucket. Its method allow(api_key, timestamp) returns True if the request is permitted and False if it is throttled.
Rules
- Each key’s bucket holds at most rate tokens and refills continuously at rate / per_seconds tokens per second. Each key is tracked independently.
- A request is allowed only if the key’s bucket has at least one whole token, which is then consumed.
- Timestamps are given in seconds and arrive in non-decreasing order.
Example:
Input:
limiter = RateLimiter(rate=100, per_seconds=60)
results = [limiter.allow('abc', 0) for _ in range(101)]
Output:
results -> [True]*100 + [False]
The first 100 requests at t=0 drain the bucket, so the 101st at the same timestamp is throttled.
.
.
.
.
.
.
.
.
.
Comments