Program to define data structure that supports rate limiting checking for user in Python


Suppose we want to develop a data structure that can build up with an expire time, and supports a function that takes user id and a timestamp. This will check whether a user with given user_id at time given timestamp the request fails or not. It will fail only when the user had a successful request less than the given expire time ago.

So, if the input is like expire = 6 then construct an object obj, and call functions obj.limit(0,10), obj.limit(0,16), obj.limit(0,17) and obj.limit(1,20), then the output will be False, False, True and False respectively because for user 0, initially no request was there so it is false, then at time 16 it is not greater than expire time 6 than last request 10, but at 17 it is true and for the last request, it is for user 1 so initial request is false.

To solve this, we will follow these steps −

Define the constructor . This will take expire

  • lastCall := create a dictionary whose default value is -1
  • Define a function limit() . This will take uid, timestamp
  • last := lastCall[uid]
  • if last is same as -1 or (last + expire) <= timestamp, then
    • lastCall[uid] := timestamp
    • return False
  • return True

Example

Let us see the following implementation to get better understanding −

from collections import defaultdict
class RateLimit:
   def __init__(self, expire):
      self.expire = expire
      self.lastCall = defaultdict(lambda: -1)
   def limit(self, uid, timestamp):
      last = self.lastCall[uid]
      if last == -1 or last + self.expire <= timestamp:
         self.lastCall[uid] = timestamp
         return False
      return True

expire = 6
obj = RateLimit(expire)
print(obj.limit(0,10))
print(obj.limit(0,16))
print(obj.limit(0,17))
print(obj.limit(1,20))

Input

RateLimit(6)
obj.limit(0,10)
obj.limit(0,16)
obj.limit(0,17)
obj.limit(1,20)

Output

False
False
True
False

Updated on: 14-Oct-2021

45 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements