Implementing rate limiter
You're building a sentiment analysis API where users can analyze texts for sentiments. To prevent abuse, you need to implement rate limiting that allows only 5
requests per minute per API key. The RateLimiter
class is already created and you have to add the is_rate_limited
method within the RateLimiter
class that checks the number of requests that have been made within the 1 minute time window.
The datetime
and timedelta
classes from the datetime
library have been pre-imported.
This exercise is part of the course
Deploying AI into Production with FastAPI
Exercise instructions
- Get the current time and calculate the timestamp for one minute ago.
- Filter the request list to keep only timestamps within the last minute.
- Check if the number of recent requests exceeds the limit.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
def is_rate_limited(self, api_key: str) -> bool:
# Get current time and the timestamp for one minute ago
now = _____
minute_ago = now - _____(minutes=1)
# Remove requests older than 1 minute
self.requests[api_key] = [
req_time for req_time in self.requests[api_key]
if req_time > _____]
# Check if no. of requests exceeded the set limit
if len(self.requests[api_key]) ____ self.requests_per_minute:
return True
self.requests[api_key].append(now)
return False