Rate Limiter - Atlassian Variation

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2025-05-02

Problem Statement

Design and implement a Rate Limiter that restricts the number of API requests a user can make within a given time window. The limiter should allow up to N requests per T milliseconds using the Sliding Window algorithm (not Fixed Window).

The system must be thread-safe and support multiple users, each with their own independent rate limit tracking. You must ensure correctness under concurrent access, especially when multiple threads make requests for the same or different users simultaneously.

Solution

Approach

To build a Sliding Window Rate Limiter, we maintain a time-sorted queue (or deque) of request timestamps for each user. When a new request arrives:

1.We remove all timestamps from the queue that fall outside the sliding window (older than current_time - T).
2.If the queue size is less than the allowed limit N, we allow the request and add the current timestamp.
3.Otherwise, the request is rejected.

To handle concurrency:

1.We use a ConcurrentHashMap<string, deque<long long>> (or thread-safe equivalent) to track request timestamps for each user.
2.Since operations on each user's queue involve checking and modifying shared state, we protect them using mutex per user (or synchronized block in Java).
3.This ensures thread-safe behavior even when multiple threads access the same user's data simultaneously.


Code:

1#include <iostream> 2#include <unordered_map> 3#include <deque> 4#include <mutex> 5#include <chrono> 6 7using namespace std; 8using namespace std::chrono; 9 10class RateLimiter { 11private: 12 int maxRequests; 13 int windowSizeMillis; 14 15 unordered_map<string, deque<long long>> userRequests; 16 unordered_map<string, mutex> userLocks; 17 18 long long currentTimeMillis() { 19 return duration_cast<milliseconds>(steady_clock::now().time_since_epoch()).count(); 20 } 21 22public: 23 RateLimiter(int maxReq, int windowSize) 24 : maxRequests(maxReq), windowSizeMillis(windowSize) {} 25 26 bool allowRequest(const string& userId) { 27 long long now = currentTimeMillis(); 28 29 // Lock the specific user's queue 30 unique_lock<mutex> lock(userLocks[userId]); 31 deque<long long>& timestamps = userRequests[userId]; 32 33 // Clean up timestamps outside the sliding window 34 while (!timestamps.empty() && timestamps.front() <= now - windowSizeMillis) { 35 timestamps.pop_front(); 36 } 37 38 if (timestamps.size() < maxRequests) { 39 timestamps.push_back(now); 40 return true; 41 } 42 43 return false; 44 } 45};
Comments