API Rate Limiter
Hard · 90 XPImplement allow(timestamps, window, limit): given sorted request timestamps (seconds), return how many requests would be rejected if only limit requests are allowed per rolling window seconds. Process requests in order; a request is rejected if the number of accepted requests in the last window seconds (inclusive) has reached limit. Print the result for the starter data.
4
Keep a list of accepted timestamps; for each request count accepted ones with t > current - window; reject if count >= limit.
def allow(timestamps, window, limit):
accepted = []
rejected = 0
for t in timestamps:
recent = [a for a in accepted if a > t - window]
if len(recent) >= limit:
rejected += 1
else:
accepted.append(t)
return rejected
requests = [1, 2, 2, 3, 4, 10, 10, 11, 12, 12]
print(allow(requests, window=5, limit=3))
Run your code to check it…
How to approach API Rate Limiter
A rolling-window limiter keeps a log of the requests it has accepted. For each new request at time t, count how many of those accepted requests are still inside the window, meaning timestamps greater than t - window. If that count has already reached the limit, reject; otherwise accept and add t to the log.
Rejected requests are not added to the log. That detail is what makes the answer 4: a client that keeps knocking does not push its own window further out, it simply gets turned away until older accepted requests expire.
Worked through on this data
- Window 5, limit 3. Requests at 1, 2 and 2 are all accepted: the log is [1, 2, 2].
- At t = 3 the window is (−2, 3] and holds 3 accepted requests: rejected. At t = 4 it is (−1, 4], still 3: rejected.
- At t = 10 nothing in the log is newer than 5, so 10, 10 and 11 are accepted. At 12 the window (7, 12] holds 10, 10 and 11: both requests at 12 are rejected. Total rejected: 4.
Common mistakes
- Adding rejected requests to the log counts them against the limit and rejects more than it should.
- Using
>=instead of>on the window edge changes which old requests still count. Pin the boundary rule down before you code. - Rebuilding a filtered list on every request is fine for ten timestamps and slow for ten million.
Time and space
Filtering the whole log per request is O(n²) overall. A collections.deque that pops expired timestamps off the front makes each request amortised O(1), with O(limit) space.
Where this shows up
This is the sliding-window log algorithm that API gateways use to stop one client flooding a service. Token buckets and fixed windows are the cheaper approximations you will meet next.
Take it further
Rewrite it with a deque: before each check, popleft() while the oldest timestamp is at or before t - window. Then keep a separate log per client ID.