Fix the sliding window in a client rate limiter
Your task
An AI agent added a rate limiter to your Go API gateway that "allows up to N requests per sliding minute per client". Its only test sent N requests and checked that the next one was blocked. You are pinning down what the limiter must do for one client, including what happens after the client has been blocked.
An assistant wrote sliding_window_allow(request_times, limit, window_ms). It is in the editor. It has a bug. Find it and fix it.
Input and output:
request_times: one client's request times in milliseconds, never decreasing.limit: how many requests may be allowed within one window.window_ms: the window length in milliseconds.- Return one boolean per request: true if it is allowed.
Rules the tests check:
- Keep a list of the times of allowed requests. It starts empty.
- For a request at time t, first drop every kept time that is at or before t minus
window_ms. A time exactlywindow_msold has left the window. - Then allow the request when
limitis greater than 0 and fewer thanlimittimes remain. - Add t to the list only when the request is allowed. A denied request is not recorded.
Examples
sliding_window_allow(request_times: list[int], limit: int, window_ms: int) -> list[bool]Example 1
Input
sliding_window_allow([0, 100, 200, 300], 2, 1000)Output
[True, True, False, False]Example 2
Input
sliding_window_allow([0, 100, 200, 1050], 2, 1000)Output
[True, True, False, True]