Priority-Aware Fixed-Window Rate Limiter
Medium · Software Engineering Fundamentals · Staff Software Engineer · Technical Screen
Problem Statement
Build a fixed-window request gatekeeper VIPRateLimiter (along with its command-replay wrapper vip_rate_limiter) that caps downstream load per time interval while giving priority traffic preferential access without starving standard callers.
Time starts at 0 and is partitioned into contiguous, half-open intervals [k * window_size, (k + 1) * window_size) for integers k >= 0. Implement the following behavior:
- Per-Window Quota: Within any single window, at most
capacity(default5) distinct requests may be admitted. - Direct Entry vs. Waiting Line: When an unseen
request_idarrives and the active window has admitted fewer thancapacityrequests, admit it right away and return"ADMITTED". Once the active window reachescapacity, hold the request in a waiting queue and return"QUEUED". - No Eviction: Admitted requests are final; a later VIP arrival never revokes or displaces an already-admitted request.
- Window Rollover, Priority, and Anti-Starvation: Whenever
submit_requestis called at atimestampat or past the end of the active window, jump directly to the window containingtimestamp, reset that window's used count to0, and drain waiting requests up tocapacitybefore evaluating the incoming call (quiet windows with zero calls do not trigger intermediate drains):- First, admit up to
min_regular_slots(default1) waiting standard requests (is_vip=False) in first-in, first-out (FIFO) order. - Next, admit waiting VIP requests (
is_vip=True) in FIFO order using up to all remaining slots in the window (if fewer thanmin_regular_slotsstandard requests were waiting, VIPs may use the leftover slots). - Finally, if slots remain open after every waiting VIP has been admitted, fill the remaining capacity from any additional waiting standard requests in FIFO order.
- First, admit up to
- Idempotent Retries: After advancing the window for
timestampif needed, submitting arequest_idthat has already been seen must not consume another slot or create a duplicate queue entry; simply return its current status ("ADMITTED"or"QUEUED").
Class & Driver Signatures
class VIPRateLimiter:
def __init__(self, window_size: int, capacity: int = 5, min_regular_slots: int = 1):
pass
def submit_request(self, request_id: str, is_vip: bool, timestamp: int) -> str:
pass
def get_admitted(self) -> List[str]:
"""Return all admitted request IDs in exact chronological admission order."""
pass
def vip_rate_limiter(operations: List[str], arguments: List[List]) -> List:
"""Replay operations ('VIPRateLimiter', 'submit_request', 'get_admitted') and return their outputs (None for __init__)."""
pass
Examples
Example 1
Input:
operations = [
"VIPRateLimiter",
"submit_request", "submit_request", "submit_request",
"submit_request", "submit_request", "submit_request",
"submit_request", "submit_request", "get_admitted"
]
arguments = [
[5, 3, 1],
["job_a", False, 1], ["job_b", False, 1], ["job_c", True, 2],
["job_d", False, 3], ["pro_1", True, 3], ["pro_2", True, 4],
["pro_1", True, 4], ["job_e", False, 5], []
]
Output:
[
None,
"ADMITTED", "ADMITTED", "ADMITTED",
"QUEUED", "QUEUED", "QUEUED",
"QUEUED", "QUEUED",
["job_a", "job_b", "job_c", "job_d", "pro_1", "pro_2"]
]
Walk-through: Window [0, 5) has capacity = 3, so "job_a", "job_b", and "job_c" take all three slots. "job_d" (standard) and "pro_1", "pro_2" (VIP) are queued, and retrying "pro_1" at t = 4 idempotently returns "QUEUED". At t = 5, window [5, 10) opens: "job_d" takes the 1 guaranteed standard slot and "pro_1", "pro_2" take the remaining 2 slots, filling [5, 10) completely so "job_e" is queued.
Example 2
Input:
operations = [
"VIPRateLimiter",
"submit_request", "submit_request",
"submit_request", "submit_request",
"submit_request", "get_admitted"
]
arguments = [
[10, 2, 1],
["u1", False, 2], ["u2", False, 4],
["v1", True, 6], ["v2", True, 7],
["v1", True, 32], []
]
Output:
[
None,
"ADMITTED", "ADMITTED",
"QUEUED", "QUEUED",
"ADMITTED",
["u1", "u2", "v1", "v2"]
]
Walk-through: "u1" and "u2" fill [0, 10) (capacity = 2), so VIPs "v1" and "v2" wait in line. When "v1" is polled at t = 32, the limiter jumps directly to [30, 40); because no standard requests are waiting, VIPs "v1" and "v2" claim both slots, and "v1" immediately reports "ADMITTED".
Constraints
1 <= capacity <= 10001 <= window_size <= 864000 <= min_regular_slots < capacitytimestampvalues are non-negative integers and never decrease from one call to the next.
Step-by-step walkthrough
Understand the rules and window timeline
We are building a fixed-window rate limiter that protects a backend service by allowing at most
capacityrequests per window ofwindow_sizeticks.Time is divided into fixed, half-open windows aligned to multiples of
window_size:Window 0: [0, window_size) Window 1: [window_size, 2 * window_size) Window k: [k * window_size, (k + 1) * window_size)For example, when
window_size = 5, timestamps0through4belong to Window 0 ([0, 5)), and timestamp5starts Window 1 ([5, 10)), even if the very first call arrived att = 1.Every
submit_request(request_id, is_vip, timestamp)call follows five rules:- Immediate admission vs. queuing: If the active window has used fewer than
capacityslots, admit the request right away ("ADMITTED"). Otherwise put it in a waiting queue ("QUEUED"). - Non-preemption: Once admitted, a request is never kicked out by a later VIP.
- Priority + anti-starvation on a new window: When time enters a new window, waiting requests are admitted first (up to
capacity), in FIFO (first-in, first-out) order within each class. VIPs take priority over regulars, except up tomin_regular_slotsslots are guaranteed to waiting regulars first whenever any are waiting. - Idempotency: If
request_idwas seen before, do not charge another slot or add a duplicate queue entry — just return its current status ("ADMITTED"or"QUEUED"). - Idle gaps: If several full windows pass with no calls at all, we jump straight to the window containing the new
timestampand drain at mostcapacitywaiting requests for that window. Draining skipped empty windows all at once would release a multi-window burst at a single timestamp, defeating the limiter.
- Immediate admission vs. queuing: If the active window has used fewer than
Why one waiting list is too slow, and how two queues fix it
Suppose we kept all waiting requests in a single list
[("job_d", False), ("pro_1", True), ...]. Every time a window rolled over, we would have to scan that list to pick out waiting regulars and VIPs and delete them from the middle. Under heavy traffic, the backlog grows to thousands of items, making each window roll O(N) and the whole run O(N²).Instead, we split waiting requests by class as soon as they arrive:
regular_queue (FIFO deque): front -> ["job_d", "job_f"] <- back vip_queue (FIFO deque): front -> ["pro_1", "pro_2"] <- back request_status (dict): {"job_a": "ADMITTED", ..., "job_d": "QUEUED", "pro_1": "QUEUED"}- Two
dequequeues: The oldest waiting regular is always at the front ofregular_queue, and the oldest waiting VIP is always at the front ofvip_queue. Removing from the front withpopleft()takes O(1) time. - One status dictionary:
request_statusmaps every seenrequest_idto"ADMITTED"or"QUEUED", answering duplicate requests in O(1) time.
Each unique request enters a queue at most once and leaves it at most once, so total queue work across the entire run is linear.
- Two
Build the state and queue-draining helpers
Let's start
VIPRateLimiterwith clear state variables and two tiny helper methods:_admit_one(request_id)is the single place that marks a request admitted, appends it toadmitted_order, and incrementsused_in_window. Centralizing this guarantees our dictionary, history list, and slot counter never fall out of sync._drain_from_queue(queue, max_to_admit)pops up tomax_to_admititems from the front ofqueue, stopping early if the queue runs dry.
from collections import deque from typing import Dict, List class VIPRateLimiter: def __init__(self, window_size: int, capacity: int = 5, min_regular_slots: int = 1): self.window_size = window_size self.capacity = capacity self.min_regular_slots = min_regular_slots # Windows are half-open intervals [k * window_size, (k + 1) * window_size). self.window_start = 0 self.used_in_window = 0 # vip_queue: FIFO deque of waiting VIP request_id strings, e.g. deque(["pro_1", "pro_2"]) self.vip_queue = deque() # regular_queue: FIFO deque of waiting regular request_id strings, e.g. deque(["job_d"]) self.regular_queue = deque() # request_status: dict {request_id: "ADMITTED" | "QUEUED"} for O(1) idempotency checks self.request_status: Dict[str, str] = {} # admitted_order: list of all admitted request_id strings in exact admission order self.admitted_order: List[str] = [] def _admit_one(self, request_id: str) -> None: """Mark one request as admitted and consume one slot in the current window.""" self.request_status[request_id] = "ADMITTED" self.admitted_order.append(request_id) self.used_in_window += 1 def _drain_from_queue(self, queue: deque, max_to_admit: int) -> None: """Pop and admit up to max_to_admit requests from the front of a FIFO queue.""" admitted_count = 0 while queue and admitted_count < max_to_admit: next_request_id = queue.popleft() self._admit_one(next_request_id) admitted_count += 1Roll into a new window with the three-phase quota split
When a new window starts, how do we satisfy VIP priority, the
min_regular_slotsguarantee, and the rule that neither class wastes slots when the other queue is short? We drain in three short phases:Example 1 rollover: capacity = 3, min_regular_slots = 1 Waiting: regular_queue = [job_d], vip_queue = [pro_1, pro_2] Phase 1 (reserved regulars, limit 1): admits job_d -> used_in_window = 1 Phase 2 (VIPs, limit 3 - 1 = 2): admits pro_1, pro_2 -> used_in_window = 3 Phase 3 (more regulars, limit 3 - 3): 0 slots left -> used_in_window = 3 (window full)Notice why all edge cases work automatically: - If no regulars are waiting (as in Example 2), Phase 1 admits
0items, leaving allcapacityslots for VIPs in Phase 2. - If fewer VIPs are waiting than remaining capacity, Phase 2 takes all waiting VIPs and Phase 3 hands the leftover slots back to waiting regulars. - Admitting the reserved regulars first producesjob_d, pro_1, pro_2, matching Example 1's expectedget_admitted()order.To check whether the window has ended, we compare
timestamp < self.window_start + self.window_size. Iftimestamphas reached or passed the end, integer divisiontimestamp // self.window_sizejumps directly to the new window's index in O(1) time.def _start_new_window(self, new_window_start: int) -> None: """Reset window usage and drain waiting queues using the three-phase quota split.""" self.window_start = new_window_start self.used_in_window = 0 # Phase 1 (anti-starvation): admit up to min_regular_slots waiting regulars first. # If fewer regulars are waiting, _drain_from_queue stops early so no slots are wasted. self._drain_from_queue(self.regular_queue, self.min_regular_slots) # Phase 2 (VIP priority): give VIPs all remaining capacity (all slots if no regulars waited). remaining_slots = self.capacity - self.used_in_window self._drain_from_queue(self.vip_queue, remaining_slots) # Phase 3 (fill leftover room): if VIPs ran out early, let more waiting regulars in. remaining_slots = self.capacity - self.used_in_window self._drain_from_queue(self.regular_queue, remaining_slots) def _advance_window_if_needed(self, timestamp: int) -> None: """Roll forward if timestamp has reached or passed the end of the active window.""" current_window_end = self.window_start + self.window_size # Use `<` because windows are [start, end): timestamp == current_window_end starts the next window. if timestamp < current_window_end: return # Jump straight to the window containing timestamp in O(1) so idle gaps do not # loop over empty windows or release phantom multi-window bursts at once. window_index = timestamp // self.window_size new_window_start = window_index * self.window_size self._start_new_window(new_window_start)Handle incoming requests and idempotency
Inside
submit_request(request_id, is_vip, timestamp), the order of checks is crucial:- Advance the window first. In Example 2,
"v1"was queued in[0, 10)and resubmitted attimestamp = 32. Advancing the window first drains"v1"into[30, 40)and updates its status to"ADMITTED", so the lookup right after returns"ADMITTED"instead of a stale"QUEUED". - Check
request_statusfor idempotency. Ifrequest_idis already known, return its stored status immediately without touchingused_in_windowor either queue. - Admit if room remains, else enqueue. Can
used_in_window < capacityever let a brand-new arrival cut in front of someone still waiting in a queue? Never: requests only enter queues when a window is full, and_start_new_windowdrains every waiting request unless doing so fills the new window completely. Therefore, wheneverused_in_window < capacity, both queues are guaranteed to be empty.
def submit_request(self, request_id: str, is_vip: bool, timestamp: int) -> str: # Advance the window BEFORE checking request_status so a queued request that was # just admitted at this new timestamp immediately reports "ADMITTED". self._advance_window_if_needed(timestamp) # Idempotency: an already-seen request_id keeps its status and uses no extra slot. if request_id in self.request_status: return self.request_status[request_id] # Whenever used_in_window < capacity, any prior roll already emptied both queues, # so admitting directly never lets a newcomer skip ahead of a waiting request. if self.used_in_window < self.capacity: self._admit_one(request_id) return "ADMITTED" # Current window is full: record status and place at the back of the matching FIFO queue. self.request_status[request_id] = "QUEUED" if is_vip: self.vip_queue.append(request_id) else: self.regular_queue.append(request_id) return "QUEUED" def get_admitted(self) -> List[str]: # Return a shallow copy so callers cannot mutate our internal admission history. return list(self.admitted_order)- Advance the window first. In Example 2,
Write the judge driver function
The automated judge passes parallel lists
operationsandargumentstovip_rate_limiter. We instantiateVIPRateLimiter(*args)whenop == "VIPRateLimiter"(recordingNoneas its output) and forwardsubmit_requestandget_admittedcalls to that instance.def vip_rate_limiter(operations: List[str], arguments: List[List]) -> List: limiter = None results = [] # Replay each method call in sequence and record its return value (None for __init__). for op, args in zip(operations, arguments): if op == "VIPRateLimiter": limiter = VIPRateLimiter(*args) results.append(None) elif op == "submit_request": results.append(limiter.submit_request(*args)) elif op == "get_admitted": results.append(limiter.get_admitted()) else: raise ValueError(f"Unknown operation: {op}") return resultsTrace Example 1 step by step
Let's trace
VIPRateLimiter(window_size=5, capacity=3, min_regular_slots=1):Call Window used regular_queue vip_queue Return -------------------------------------------------------------------------------------- job_a (False, t=1) [0, 5) 1 [] [] ADMITTED job_b (False, t=1) [0, 5) 2 [] [] ADMITTED job_c (True, t=2) [0, 5) 3 [] [] ADMITTED job_d (False, t=3) [0, 5) 3 [job_d] [] QUEUED pro_1 (True, t=3) [0, 5) 3 [job_d] [pro_1] QUEUED pro_2 (True, t=4) [0, 5) 3 [job_d] [pro_1, pro_2] QUEUED pro_1 (dup) (True, t=4) [0, 5) 3 [job_d] [pro_1, pro_2] QUEUED job_e (False, t=5) t=5 >= 5 -> roll to [5, 10), reset used = 0: Phase 1 (1 regular): pop job_d -> used = 1 Phase 2 (2 VIPs): pop pro_1, pro_2 -> used = 3 Phase 3 (regulars): 0 slots left -> used = 3 Now check job_e: used (3) == 3 -> enqueue job_e: [5, 10) 3 [job_e] [] QUEUED get_admitted() -> ['job_a', 'job_b', 'job_c', 'job_d', 'pro_1', 'pro_2']Every return value and the final
get_admitted()list match Example 1.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple from collections import deque class VIPRateLimiter: def __init__(self, window_size: int, capacity: int = 5, min_regular_slots: int = 1): self.window_size = window_size self.capacity = capacity self.min_regular_slots = min_regular_slots # Windows are half-open intervals [k * window_size, (k + 1) * window_size). self.window_start = 0 self.used_in_window = 0 # vip_queue: FIFO deque of waiting VIP request_id strings, e.g. deque(["pro_1", "pro_2"]) self.vip_queue = deque() # regular_queue: FIFO deque of waiting regular request_id strings, e.g. deque(["job_d"]) self.regular_queue = deque() # request_status: dict {request_id: "ADMITTED" | "QUEUED"} for O(1) idempotency checks self.request_status: Dict[str, str] = {} # admitted_order: list of all admitted request_id strings in exact admission order self.admitted_order: List[str] = [] def _admit_one(self, request_id: str) -> None: """Mark one request as admitted and consume one slot in the current window.""" self.request_status[request_id] = "ADMITTED" self.admitted_order.append(request_id) self.used_in_window += 1 def _drain_from_queue(self, queue: deque, max_to_admit: int) -> None: """Pop and admit up to max_to_admit requests from the front of a FIFO queue.""" admitted_count = 0 while queue and admitted_count < max_to_admit: next_request_id = queue.popleft() self._admit_one(next_request_id) admitted_count += 1 def _start_new_window(self, new_window_start: int) -> None: """Reset window usage and drain waiting queues using the three-phase quota split.""" self.window_start = new_window_start self.used_in_window = 0 # Phase 1 (anti-starvation): admit up to min_regular_slots waiting regulars first. # If fewer regulars are waiting, _drain_from_queue stops early so no slots are wasted. self._drain_from_queue(self.regular_queue, self.min_regular_slots) # Phase 2 (VIP priority): give VIPs all remaining capacity (all slots if no regulars waited). remaining_slots = self.capacity - self.used_in_window self._drain_from_queue(self.vip_queue, remaining_slots) # Phase 3 (fill leftover room): if VIPs ran out early, let more waiting regulars in. remaining_slots = self.capacity - self.used_in_window self._drain_from_queue(self.regular_queue, remaining_slots) def _advance_window_if_needed(self, timestamp: int) -> None: """Roll forward if timestamp has reached or passed the end of the active window.""" current_window_end = self.window_start + self.window_size # Use `<` because windows are [start, end): timestamp == current_window_end starts the next window. if timestamp < current_window_end: return # Jump straight to the window containing timestamp in O(1) so idle gaps do not # loop over empty windows or release phantom multi-window bursts at once. window_index = timestamp // self.window_size new_window_start = window_index * self.window_size self._start_new_window(new_window_start) def submit_request(self, request_id: str, is_vip: bool, timestamp: int) -> str: # Advance the window BEFORE checking request_status so a queued request that was # just admitted at this new timestamp immediately reports "ADMITTED". self._advance_window_if_needed(timestamp) # Idempotency: an already-seen request_id keeps its status and uses no extra slot. if request_id in self.request_status: return self.request_status[request_id] # Whenever used_in_window < capacity, any prior roll already emptied both queues, # so admitting directly never lets a newcomer skip ahead of a waiting request. if self.used_in_window < self.capacity: self._admit_one(request_id) return "ADMITTED" # Current window is full: record status and place at the back of the matching FIFO queue. self.request_status[request_id] = "QUEUED" if is_vip: self.vip_queue.append(request_id) else: self.regular_queue.append(request_id) return "QUEUED" def get_admitted(self) -> List[str]: # Return a shallow copy so callers cannot mutate our internal admission history. return list(self.admitted_order) def vip_rate_limiter(operations: List[str], arguments: List[List]) -> List: limiter: Optional[VIPRateLimiter] = None results: List[Any] = [] # Replay each method call in sequence and record its return value (None for __init__). for op, args in zip(operations, arguments): if op == "VIPRateLimiter": limiter = VIPRateLimiter(*args) results.append(None) elif op == "submit_request": results.append(limiter.submit_request(*args)) elif op == "get_admitted": results.append(limiter.get_admitted()) else: raise ValueError(f"Unknown operation: {op}") return results✅ Submit now — all tests should pass.
Intuition & how it works
Picture an airport shuttle gate where a van departs every 5 minutes (window_size) with 3 seats (capacity). Whenever seats are open on the current van, any traveler walking up boards right away (non-preemption means nobody already seated is ever asked to step off). Once the van is full, arriving travelers line up in two FIFO (first-in, first-out) queues — a VIP lane and a standard lane — where the earliest arrival stands at the front. When the next van pulls up, the gate agent prevents starvation (standard travelers waiting forever behind non-stop VIP arrivals) by boarding up to min_regular_slots waiting standard travelers first, filling remaining seats from the VIP lane, and handing any leftover seats back to the standard lane; meanwhile, a status ledger provides idempotency (submitting the same request_id twice returns its existing status without taking a second seat).
A naive implementation puts every waiting request into one combined list and scans it at each new window to pick out VIPs and regulars. When traffic spikes faster than capacity, scanning and deleting from the middle of a growing list of N requests turns the total work into slow O(N²) time. Worse, advancing time one window per loop step during a long quiet stretch either wastes thousands of iterations or admits a huge backlog of old requests all at once, defeating the rate limiter.
Let's trace Example 1 (window_size = 5, capacity = 3, min_regular_slots = 1):
1. At t = 1..2, "job_a", "job_b", and "job_c" arrive in window [0, 5) and fill all 3 seats ("ADMITTED").
2. At t = 3..4, standard "job_d" joins regular_queue ("QUEUED"), VIPs "pro_1" and "pro_2" join vip_queue ("QUEUED"), and the duplicate retry "pro_1" immediately returns "QUEUED" from request_status.
3. At t = 5, "job_e" arrives. Because 5 >= 5, window [5, 10) opens first: Phase 1 pops "job_d" for the 1 reserved standard slot, Phase 2 pops "pro_1" and "pro_2" for the remaining 2 slots, and since [5, 10) is now full (used_in_window = 3), "job_e" joins regular_queue ("QUEUED").
Complexity
Let N be the total number of submit_request calls, R be the number of distinct request_id values seen, and A be the number of requests admitted so far.
- Time:
submit_requestruns in amortized O(1) time (meaning an individual window roll may pop up tocapacityitems, but averaged across all calls each request costs constant work). Jumping to the active window uses one integer division (timestamp // window_size), dictionary lookups take O(1), and each of the R distinct requests is appended to and popped from a deque (a double-ended queue supporting O(1) appends and front pops) at most once across the entire run, so all queue operations together take O(R) time. Eachget_admitted()call takes O(A) time because it copies the list of A admitted IDs. - Space: O(R) memory, because each distinct
request_idappears once inrequest_status, at most once invip_queueorregular_queue, and at most once inadmitted_order.
Edge cases
- Exact window boundary: Windows are half-open
[start, start + window_size). Withwindow_size = 5,t = 4stays in[0, 5)whilet = 5triggers a roll to[5, 10). - First request arrives late: If the first call arrives at
t = 25withwindow_size = 10, windows remain anchored to multiples of 10, so it lands in[20, 30). - Multi-window idle gaps: As in Example 2 (
t = 7tot = 32), jumping directly to[30, 40)drains at mostcapacitywaiting requests for[30, 40)rather than releasing extra bursts for the quiet windows in between. - Fewer waiting regulars than
min_regular_slots: Phase 1 drains only the regulars actually waiting (0ifregular_queueis empty), leaving every remaining slot for VIPs. - Fewer waiting VIPs than remaining capacity: Phase 2 drains all waiting VIPs, and Phase 3 gives the leftover slots back to
regular_queue. min_regular_slots = 0: Phase 1 admits zero regulars, turning the policy into strict VIP priority where regulars only advance oncevip_queueis empty.- Resubmitting a request right as a roll admits it: Advancing the window before checking
request_statusensures a previously queued ID that was just drained in the new window (like"v1"att = 32in Example 2) immediately returns"ADMITTED". - Resubmitting with a different
is_vipflag: Because known IDs return early fromrequest_status, a duplicate call cannot sneak a regular request intovip_queueor consume a second slot.
Common mistakes
- Draining VIPs before reserved regulars: Admitting
(capacity - min_regular_slots)VIPs first andmin_regular_slotsregulars second admits the same set of items, but reverses their order (pro_1, pro_2, job_dinstead of Example 1'sjob_d, pro_1, pro_2). - Hard-reserving
min_regular_slotswhenregular_queueis empty: Subtractingmin_regular_slotsfrom VIP capacity unconditionally leaves capacity unused while VIPs wait in line. - Advancing by
window_start += window_sizeonce per call: After an idle gap of 5 windows, the limiter lags behind real time, causing the next 5 calls in the same real window to each resetused_in_windowand admit5 * capacityrequests at once. - Checking
request_statusbefore_advance_window_if_needed: A caller polling a queuedrequest_idin a new window gets back a stale"QUEUED"instead of triggering the window roll that admits it. - Using
list.pop(0)instead ofcollections.deque.popleft(): Popping index0of a Pythonlistshifts every remaining element left in O(N) time;deque.popleft()is O(1). - Returning
self.admitted_orderdirectly without copying: Callers mutating the returned list would corrupt internal limiter history.
Alternative approaches
- Single priority heap (
heapq): You could push(priority_rank, arrival_seq, request_id)into a min-heap, which orders VIPs ahead of regulars and preserves FIFO ties, but enforcingmin_regular_slotsstill requires separating regulars anyway, and each push/pop slows from O(1) to O(log R). Two deques are both simpler and faster. - Timer-driven background drainer: In a real server with an event loop, a background timer firing every
window_sizeseconds can proactively pop up tocapacityqueued requests and dispatch them downstream even when no new client calls arrive. In a pure request-driven class without background threads, jumping lazily onsubmit_requestavoids releasing bursts.
Follow-up questions
- How could you coordinate this limiter across a fleet of stateless API servers that share one global quota? Keep the shared state in an in-memory store such as Redis: two Redis lists (
RPUSH/LPOP) for the VIP and standard queues, scalar keys forwindow_startandused_in_window, and status keys with a TTL (time-to-live) expiration forrequest_statusso memory stays bounded. Execute the window-roll check, three-phase queue drain, idempotency lookup, and slot admission inside a single Redis Lua script so the entire read-modify-write runs atomically without race conditions across servers. Use Redis's own clock (TIME) rather than application host clocks so clock skew never rolls windows prematurely. - What changes in queue draining and fairness if you replace fixed time windows with a token bucket or sliding log? A token bucket (which refills tokens steadily over time up to a burst cap) or sliding log (which counts admissions within the trailing
window_sizespan) frees capacity incrementally rather than in an all-at-once batch at fixed boundaries. On each call, you first calculate how many slots have opened up since the prior timestamp and immediately drain that many queued items before judging the new request. Because slots open individually instead of in batches ofcapacity, anti-starvation shifts to a rolling fairness counter — ensuring at leastmin_regular_slotsout of everycapacityconsecutive drained slots come fromregular_queuewhenever standard requests are waiting. - How would you add priority aging so standard requests waiting longer than K windows get promoted ahead of newer traffic? Push
(request_id, queued_window_index)intoregular_queue, wherequeued_window_index = timestamp // window_size. Becauseregular_queueis strictly ordered by arrival time, every standard request that has waited at leastKwindows (current_window_index - queued_window_index >= K) sits contiguously at the front ofregular_queue. At the start of_start_new_window, before Phase 1, pop all aged-out requests from the front ofregular_queuein O(1) per promoted request and move them intovip_queue(or merge by original sequence number if promoted items should also precede newer VIPs), leaving the reserved regular slots for younger standard arrivals behind them.
Follow-up questions
- How could you coordinate this limiter across a fleet of stateless API servers that share one global quota?
- What changes in queue draining and fairness if you replace fixed time windows with a token bucket or sliding log?
- How would you add priority aging so standard requests waiting longer than K windows get promoted ahead of newer traffic?
Similar questions
- Transaction Status Totals and Normalized Reason Breakdown
- Locating the Largest Regular File with Bash
- Field-Level User Profile Sanitizer
- RAG-Based Product Recommendation API Design
- Increment Digit Array
- Day-30 Daily Cohort Retention
More Intuit interview questions
- RAG-Based Product Recommendation API Design Medium
- LLM Mechanics, AI-Native Architecture, Engineering Workflows, and Risk Controls Medium
- Prioritizing Funnel Insights Across Skewed Acquisition Entry Points Easy Pro
- Business Network Separation Degrees Hard Pro
- Diagnosing Missing, Leaked, and Unavailable Features in Filing Prediction Easy Pro
- Field-Level User Profile Sanitizer Medium Pro
- Longest Daily Uninterrupted Focus Window Medium Pro
- Catalog Service Evolution: Schema, Indexing, and Search Medium Pro
- Dictionary Word Splitting and React Palindrome Checker Medium Pro
- Staff Engineer Intro Deck, Core Motivators, and Signature Strengths Medium Pro