The Rate Limiter is a per-minute request limiter. It allows up to 1000 events in a minute and does not roll over the underutilized capacity to the next minute.
It uses a Hashmap to keep track of per second requests. The idea is to extend the code for roll-over capacity to the next minute.
from random import seed
from random import randint
import sys
seed(1)
class RateLimit():
def getTime(self, minute):
if minute == 4:
sys.exit(0)
return minute, randint(0, 59)
def __init__(self):
self.status = {}
self.start_minute = 1
self.total_events = 0
def ratelimit(self, minute, second):
print(minute, self.start_minute, self.status, self.total_events)
if minute != self.start_minute:
self.start_minute = minute
self.status.clear()
self.total_events = 0
if self.total_events > 1000:
print("not accepting anymore")
return -1
hashKey = second % 60
print("hashkey={}".format(hashKey))
if hashKey in self.status:
self.status[hashKey] += 1
else:
self.status[hashKey] = 1
self.total_events += 1
r = RateLimit()
minute = 1
while 1:
m,s = r.getTime(minute)
if r.ratelimit(m, s) == -1:
minute += 1
r.getTime(minute)
Sample output
hashkey=50
(3, 3, {0: 17, 1: 20, 2: 21, 3: 20, 4: 12, 5: 19, 6: 20, 7: 12, 8: 21, 9: 21, 10: 17, 11: 10, 12: 15, 13: 21, 14: 15, 15: 15, 16: 20, 17: 12, 18: 19, 19: 9, 20: 14, 21: 12, 22: 10, 23: 21, 24: 15, 25: 14, 26: 20, 27: 16, 28: 18, 29: 8, 30: 17, 31: 11, 32: 23, 33: 16, 34: 13, 35: 23, 36: 20, 37: 14, 38: 16, 39: 16, 40: 16, 41: 20, 42: 21, 43: 13, 44: 9, 45: 15, 46: 24, 47: 20, 48: 18, 49: 17, 50: 22, 51: 16, 52: 16, 53: 16, 54: 27, 55: 14, 56: 17, 57: 9, 58: 22, 59: 16}, 1001)
not accepting anymore
Written with StackEdit.