Sliding-Window API Rate Limiter
Updated
Problem statement
An in-memory rate limiter permits at most limit accepted requests in the rolling one-second window ending at each request timestamp. Timestamps are integer milliseconds in nondecreasing order.
Before deciding a request at time t, discard accepted requests with timestamp at most t - 1000. Accept the current request when fewer than limit accepted timestamps remain. Rejected requests do not consume capacity. Return one decision per request.
Function
allowRequests(limit: int, timestamps: int[]) → boolean[]Examples
Example 1
limit = 3timestamps = [0,100,200,300,1000,1001]return = [true,true,true,false,true,false]The fourth request is rejected. At time 1000, the accepted request at time 0 expires, so the fifth request is accepted. At time 1001, three accepted requests remain in the rolling window, so the sixth is rejected.
Example 2
limit = 1timestamps = [5,5,1004,1005]return = [true,false,false,true]The rejected duplicate at time 5 does not consume capacity; the accepted request expires only when the timestamp reaches 1005.
Constraints
1 <= limit <= 10^5.1 <= timestamps.length <= 10^5.0 <= timestamps[i] <= 2^31 - 1.- Timestamps are nondecreasing.
More Patreon interview questions
Similar questions at other companies
- Rate Limiter Sliding Window With Per-Entity LimitsRoblox · PHONE SCREEN · ONSITE INTERVIEWRoblox interview questions
- Duplicate News Within 60 SecondsBloomberg LP · PHONE SCREENBloomberg LP interview questions
- Completions API Rate LimiterCursor · PHONE SCREENCursor interview questions
- Key-Value Store GET and PUT QPSDatabricks · PHONE SCREENDatabricks interview questions
- Sliding-Window Rate LimiterSnowflake · ONSITE INTERVIEWSnowflake interview questions
- Per-Client Sliding-Window Rate LimiterGeneral Motors · OA
- Metric Counter with a Fake ClockSnap Inc. · ONSITE INTERVIEWSnap Inc. interview questions
- Per-Client Sliding-Window Rate LimiterNike, Inc. · ONSITE INTERVIEWNike, Inc. interview questions
- Per-User Sliding-Window Rate LimiterPayPal · OAPayPal interview questions
- Incident MonitorStripe · OAStripe interview questions