Sliding Window Request Limiter Keyed by API Key
Last updated: November 29, 2026
Quick Overview
Implement `allow(key, now)` that accepts a request only if the given API key has had fewer than `limit` accepted requests in the rolling `window` seconds ending at `now`, recording accepted requests.
OpenAI
November 29, 20260
0
0 solved
Implement `allow(key, now)` that accepts a request only if the given API key has had fewer than `limit` accepted requests in the rolling `window` seconds ending at `now`, recording accepted requests.
Every OpenAI API organization has request and token limits, so a per-key limiter is a natural screen question with obvious follow-ups into distributed design. The interviewer checks precise window boundaries, that rejected requests are not counted, and awareness of the memory cost of a sliding log compared with counters.
What the Interviewer Expects
- Keep a per-key deque of accepted timestamps
- Evict expired timestamps before deciding
- Define the window boundary precisely (half-open)
- Do not record rejected requests
- Compare the sliding log with fixed-window and sliding-counter approaches
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Memory per key is O(limit): how does a sliding window counter approximate this in O(1)?
- Limit by tokens instead of requests, where each request has a cost.
- Run the limiter across 50 API servers: where does the state live, and what happens if that store is slow?
- How would you return a Retry-After value to the client?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
allow(key, now) -> bool; timestamps for a key are non-decreasing.- Window is
(now - window, now]: a request exactlywindowseconds old no longer counts. - Only accepted requests are recorded....
High-Level Design
Store, per key, a deque of the timestamps of accepted requests. On each call, pop timestamps from the front while they are at or before now - window, since those requests have aged out. If fewer tha...