Problem
Build a per-key sliding-window rate limiter. The constructor takes a limit and a windowMs. allow(key, now) returns true if the request at logical time now (in ms) is within the limit for that key, counting only the allowed requests in the trailing window of length windowMs; otherwise it returns false. Denied requests must not consume a slot. Time is always supplied by the caller — no Thread.sleep, no system clock.
Restate the problem in one sentence and list the edge cases — before writing any code.
Then keep talking — restate the problem + the edge cases in your own words.
“Let me make sure I understand the problem, then I'll walk through my approach.”
checking microphone…
Self-check
Hints / what this doesn't test
This is an Opendoor-flavored applied problem: a stateful policy component tested
with a logical clock, so it stays deterministic. Restate it first — "So allow
is called with the current time, I count only the requests I admitted in the last
windowMs, and a rejected call shouldn't count against the next one?"
What this problem does not test (say so out loud): the cheaper fixed-window counter (and its boundary-burst flaw), a token-bucket variant, eviction of idle keys to bound memory, and concurrency are out of scope here — but a senior names that admitting before the window check, or recording denied requests, are the two classic off-by-one bugs in this shape.
Tests
- ○under_limit
- ○over_limit
- ○per_key_isolation
- ○window_slides
- + 2 hidden tests — revealed once the visible ones pass