Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

API Rate Limiter

Hard · 90 XP

Implement 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.

Target output
4
Blank · autosaved
PYapi-rate-limiter.py
Run your code to check it…
Guide

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

  1. Window 5, limit 3. Requests at 1, 2 and 2 are all accepted: the log is [1, 2, 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.
  3. 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.

Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path