Skip to content
Coding · Medium · Rate limiting · Target O(1) amortised per call · Senior

Rate limiter with sliding window

Implement allow(key, now) that admits at most limit requests per key in any trailing window_s seconds, with bounded memory.

Statement

Implement a per-key rate limiter: allow(key, now) returns True if the request is admitted and False otherwise. A key may have at most limit admitted requests in any trailing window of window_s seconds. Rejected requests do not count.

The limiter runs inside a request path, so each call must be cheap and memory must not grow without bound for keys that go quiet.

Examples

limit = 3, window_s = 10

allow("u1", 0.0)  → True
allow("u1", 1.0)  → True
allow("u1", 2.0)  → True
allow("u1", 3.0)  → False   # 3 hits in [−7, 3]
allow("u1", 10.1) → True    # hit at 0.0 has aged out

Constraints

Up to 10⁵ distinct keys and 10⁴ calls per second. now is monotonic and non-decreasing per key. Memory per key must be O(limit). Discuss how you would evict idle keys.

Free to try · sign in to save your attemptSolve it in the editor with visible tests
Open in the app