Algo-Sim › Low-Level Design
Rate Limiter: Sliding Window Log
Medium · Low-Level Design · step through it in Java, Python and C++ on your own input
At most limit requests in any window of window seconds: keep a queue of accepted times and drop the ones that slid out.
Problem
Design a rate limiter that accepts at most limit requests in any window of window seconds. A request at time t is accepted if fewer than limit accepted requests happened after time t − window; otherwise it is rejected. Return the decision for each request.
Constraints
- Request times arrive in non-decreasing order
- Memory O(limit): only accepted times inside the window are kept
- Amortised O(1) per request: each time is queued and dropped once
Edge cases to test
- Requests exactly window seconds apart
- A burst at the window boundary
- limit = 1
Follow-up questions
- How do you save memory?
- A sliding window counter: weight the previous fixed window’s count by its overlap and add the current one. O(1) memory, approximate.
- What is the cost of the log?
- O(limit) memory per client and O(1) amortized per request.
Solution
Java
class SlidingWindowLog {
private final Deque<Integer> log = new ArrayDeque<>(); // accepted request times
private final int limit, window;
public SlidingWindowLog(int limit, int window) {
this.limit = limit;
this.window = window;
}
public boolean allow(int t) {
while (!log.isEmpty() && log.peekFirst() <= t - window)
log.pollFirst();
if (log.size() < limit) {
log.addLast(t);
return true;
}
return false;
}
}Python
from collections import deque
class SlidingWindowLog:
def __init__(self, limit, window):
self.log = deque() # accepted request times
self.limit = limit
self.window = window
def allow(self, t):
while self.log and self.log[0] <= t - self.window:
self.log.popleft()
if len(self.log) < self.limit:
self.log.append(t)
return True
return FalseC++
#include <bits/stdc++.h>
using namespace std;
class SlidingWindowLog {
public:
deque<int> log = {}; // accepted request times
int limit, window;
SlidingWindowLog(int limit, int window) {
this->limit = limit;
this->window = window;
}
bool allow(int t) {
while (!log.empty() && log.front() <= t - window)
log.pop_front();
if (int(log.size()) < limit) {
log.push_back(t);
return true;
}
return false;
}
};
More Low-Level Design problems
- LRU Cache (Medium)
- LFU Cache (Hard)
- Min Stack (Medium)
- Insert Delete GetRandom O(1) (Medium)
- Design Circular Queue (Medium)
- Flatten Nested List Iterator (Medium)
- Rate Limiter: Token Bucket (Medium)
- Logger Rate Limiter (Easy)
- Design Hit Counter (Medium)
- Design Parking System (Easy)
- Design Tic-Tac-Toe (Medium)
- Design Twitter (Medium)
- Design Snake Game (Medium)
- Vending Machine (State pattern) (Medium)
- Elevator System (LOOK scheduling) (Medium)
- Splitwise (expense sharing) (Medium)
- Movie Ticket Booking (BookMyShow) (Medium)