Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- 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:
- “Each customer can make X requests per Y seconds”
- Assuming that customer ID is extracted somehow from the request, implement the following function.
- // Perform rate limiting logic for provided customer ID. Return true if the
- // request is allowed, and false if it is not.
- boolean rateLimit(int customerId)
- """
- from typing import Dict
- from dataclasses import dataclass
- from abc import ABC, abstractmethod
- class RateLimiterInterface(ABC):
- def allowRequest(self, customerId: int, currentTime: float) -> bool:
- pass
- class RateLimiter(RateLimiterInterface):
- @dataclass
- class Bucket:
- def __init__(self, capacity):
- self.lastTimeStamp = 0
- self.remaining = capacity
- def __init__(self, capacity: int, refillTime):
- self.BUCKET_SIZE = capacity
- self.refillTime = refillTime
- self.bucket: Dict[int: RateLimiter.Bucket] = {}
- def allowRequest(self, customerId: int, t) -> bool:
- time = t
- if (customerId not in self.bucket):
- self.bucket[customerId] = self.Bucket(self.BUCKET_SIZE)
- bucket = self.bucket[customerId]
- bucket = self.refill(bucket, time)
- print(bucket.remaining)
- if (bucket.remaining > 0):
- bucket.remaining -= 1
- return True
- else:
- return False
- def refill(self, bucket, t) -> Bucket:
- elapsed = t - bucket.lastTimeStamp
- if (elapsed >= self.refillTime):
- bucket.remaining = self.BUCKET_SIZE
- bucket.lastTimeStamp = t
- return bucket
- ratelimiter = RateLimiter(3,2)
- print(ratelimiter.allowRequest(123, 0))
- print(ratelimiter.allowRequest(123,0))
- print(ratelimiter.allowRequest(123,0))
- print(ratelimiter.allowRequest(123,0))
- print(ratelimiter.allowRequest(123,0))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement