Sobes.tech
Junior — Middle

How can a system be designed to limit the number of requests to a resource within five consecutive sessions?

sobes.tech AI

Answer from AI

To limit the number of requests to a resource within five consecutive sessions, a mechanism can be implemented that tracks the number of requests in each session and sums them over the last five sessions.

Example approach:

  1. Store a request counter for each session.
  2. Keep a history of the last five sessions with their counters.
  3. When a new request comes in, check the sum of requests over the last five sessions.
  4. If the sum exceeds the limit, block the request.

In Python, a fixed-length queue (e.g., collections.deque with maxlen=5) can be used to store the number of requests per session. When a session ends, add the counter to the queue; for a new request, sum the values in the queue.

Example code:

from collections import deque

class RateLimiter:
    def __init__(self, max_requests_per_5_sessions):
        self.max_requests = max_requests_per_5_sessions
        self.session_requests = 0
        self.last_5_sessions = deque(maxlen=5)

    def new_request(self):
        # Check the sum of requests over the last 5 sessions
        total = sum(self.last_5_sessions) + self.session_requests + 1
        if total > self.max_requests:
            return False  # Limit exceeded
        self.session_requests += 1
        return True

    def end_session(self):
        self.last_5_sessions.append(self.session_requests)
        self.session_requests = 0

# Usage
limiter = RateLimiter(max_requests_per_5_sessions=100)

# During a session
if limiter.new_request():
    print("Request allowed")
else:
    print("Limit exceeded")

# At the end of a session
limiter.end_session()

This approach allows controlling the total number of requests over the last five sessions.