16/32
Part 4 of 6 · Deques and rate limitsLearn and do
A rate limiter is a window measured in seconds
Now the rate limiter, for one client first. Keep the times of its allowed requests in a deque, oldest first. At each new request, drop from the front everything that stopped counting, then count what's left.
A request allowed at t counts while now < t + window
from collections import deque
class OneKeyLimiter:
def __init__(self, limit, window):
self.limit, self.window = limit, window
# allowed requests, oldest first
self.times = deque()
def allow(self, now):
while self.times and self.times[0] + self.window <= now:
self.times.popleft()
if len(self.times) >= self.limit:
return False
self.times.append(now)
return True
limiter = OneKeyLimiter(limit=2, window=10)
for now in [0, 3, 5, 10, 12, 13, 22]:
print(now, limiter.allow(now), list(limiter.times))
0 True [0]
3 True [0, 3]
5 False [0, 3]
10 True [3, 10]
12 False [3, 10]
13 True [10, 13]
22 True [13, 22]
Each line is now, the answer, and the times kept after the call. On a timeline, each allowed request gets a bar for the time it counts. An x is a denied request, and the last column is how many requests counted when it arrived:
0: allowed 0 counting before it
3: allowed 1 counting
5: denied 2 counting
10: allowed 1 counting: the one at 0 stopped at 10
12: denied 2 counting
13: allowed 1 counting
22: allowed 1 counting
051015202530
seconds
At 10 the bar from 0 has just ended, so only the request at 3 counts, and 10 gets through. At 12 the requests at 3 and 10 both count, so 12 is denied.
Write still_counting: from the times of a client's allowed requests, how many still count at now, by the rule above.