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

Rate limiting is a technique used to control the frequency of requests from users. We need to design a data structure that tracks user requests and determines if a new request should be allowed based on an expiration time window.

The data structure should support checking whether a user's request fails based on their previous successful request. A request fails (returns True) only when the user had a successful request within the expire time window.

Problem Understanding

Given an expire time, we need to:

  • Track the last successful request timestamp for each user
  • Check if a new request is within the rate limit window
  • Return False for allowed requests, True for rate-limited requests

Algorithm Steps

To solve this problem, we follow these steps:

  • Create a constructor that takes the expire time
  • Use a dictionary to store the last successful request timestamp for each user (default value -1)
  • For each limit() call, check if enough time has passed since the last request
  • If no previous request exists or enough time has passed, allow the request and update timestamp
  • Otherwise, reject the request (rate limit exceeded)

Implementation

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  # Request allowed
        return True  # Request rate-limited

# Example usage
expire = 6
obj = RateLimit(expire)

print(obj.limit(0, 10))  # First request for user 0
print(obj.limit(0, 16))  # Second request for user 0 
print(obj.limit(0, 17))  # Third request for user 0
print(obj.limit(1, 20))  # First request for user 1
False
False
True
False

How It Works

Let's trace through the example with expire = 6:

  • limit(0, 10): User 0's first request ? No previous request ? Allow (False)
  • limit(0, 16): Time difference = 16 - 10 = 6 ? expire time ? Allow (False)
  • limit(0, 17): Time difference = 17 - 16 = 1 < expire time ? Rate limit (True)
  • limit(1, 20): User 1's first request ? No previous request ? Allow (False)

Key Points

  • Returns False when request is allowed
  • Returns True when request is rate-limited
  • Uses defaultdict to handle new users automatically
  • Time complexity: O(1) for each operation
  • Space complexity: O(n) where n is the number of unique users

Conclusion

This rate limiting data structure efficiently tracks user requests using a dictionary to store timestamps. It allows requests when sufficient time has passed since the last successful request, providing an effective way to control request frequency per user.

Updated on: 2026-03-26T16:34:45+05:30

171 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements