This question evaluates a candidate's ability to implement a sliding-window rate limiter, emphasizing time-based algorithms, per-key state management, and efficient data-structure choices to achieve near-O(1) operations.
Design and implement an in-memory rate limiter using a sliding time window.
You are given a stream of requests. Each request has:
key
(e.g., user ID, API token, or IP)
timestamp
(integer seconds, non-decreasing for a given
key
)
Implement an API:
bool allow(key, timestamp)
The limiter should allow at most N requests per W seconds for each key.
(timestamp - W, timestamp]
(or clearly define inclusivity and keep it consistent).
If N = 3, W = 10 seconds:
[1, 2, 3]
are allowed.
4
is denied (already 3 in last 10 seconds).
12
may be allowed depending on the sliding window definition (e.g., requests at time
1
may have expired).
allow
call.