Advertisement
nirajs

ratelimiter

Jan 28th, 2024
690
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.06 KB | None | 0 0
  1. """
  2. Imagine we are building an application that is used by many different customers. We want to avoid one customer being able to overload the system by sending too many requests, so we enforce a per-customer rate limit. The rate limit is defined as:
  3.  
  4. “Each customer can make X requests per Y seconds”
  5.  
  6. Assuming that customer ID is extracted somehow from the request, implement the following function.
  7.  
  8.  
  9. // Perform rate limiting logic for provided customer ID. Return true if the
  10. // request is allowed, and false if it is not.
  11. boolean rateLimit(int customerId)
  12.  
  13. """
  14. from typing import Dict
  15. from dataclasses import dataclass
  16. from abc import ABC, abstractmethod
  17.  
  18. class RateLimiterInterface(ABC):
  19.     def allowRequest(self, customerId: int, currentTime: float) -> bool:
  20.         pass
  21.  
  22. class RateLimiter(RateLimiterInterface):
  23.  
  24.     @dataclass
  25.     class Bucket:
  26.         def __init__(self, capacity):
  27.             self.lastTimeStamp = 0
  28.             self.remaining = capacity
  29.  
  30.     def __init__(self, capacity: int, refillTime):
  31.         self.BUCKET_SIZE = capacity
  32.         self.refillTime = refillTime
  33.         self.bucket: Dict[int: RateLimiter.Bucket] = {}
  34.  
  35.     def allowRequest(self, customerId: int, t) -> bool:
  36.  
  37.         time = t
  38.         if (customerId not in self.bucket):
  39.             self.bucket[customerId] = self.Bucket(self.BUCKET_SIZE)
  40.  
  41.         bucket = self.bucket[customerId]
  42.         bucket = self.refill(bucket, time)
  43.         print(bucket.remaining)
  44.         if (bucket.remaining > 0):
  45.             bucket.remaining -= 1
  46.             return True
  47.         else:
  48.             return False
  49.  
  50.     def refill(self, bucket, t) -> Bucket:
  51.         elapsed = t - bucket.lastTimeStamp
  52.         if (elapsed >= self.refillTime):
  53.             bucket.remaining = self.BUCKET_SIZE
  54.         bucket.lastTimeStamp = t
  55.         return bucket
  56.  
  57.  
  58.  
  59. ratelimiter = RateLimiter(3,2)
  60.  
  61. print(ratelimiter.allowRequest(123, 0))
  62. print(ratelimiter.allowRequest(123,0))
  63. print(ratelimiter.allowRequest(123,0))
  64. print(ratelimiter.allowRequest(123,0))
  65. print(ratelimiter.allowRequest(123,0))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement