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:

  1. Per-Window Quota: Within any single window, at most capacity (default 5) distinct requests may be admitted.
  2. Direct Entry vs. Waiting Line: When an unseen request_id arrives and the active window has admitted fewer than capacity requests, admit it right away and return "ADMITTED". Once the active window reaches capacity, hold the request in a waiting queue and return "QUEUED".
  3. No Eviction: Admitted requests are final; a later VIP arrival never revokes or displaces an already-admitted request.
  4. Window Rollover, Priority, and Anti-Starvation: Whenever submit_request is called at a timestamp at or past the end of the active window, jump directly to the window containing timestamp, reset that window's used count to 0, and drain waiting requests up to capacity before evaluating the incoming call (quiet windows with zero calls do not trigger intermediate drains):
    • First, admit up to min_regular_slots (default 1) 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 than min_regular_slots standard 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.
  5. Idempotent Retries: After advancing the window for timestamp if needed, submitting a request_id that 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 <= 1000
  • 1 <= window_size <= 86400
  • 0 <= min_regular_slots < capacity
  • timestamp values are non-negative integers and never decrease from one call to the next.

Step-by-step walkthrough

  1. Understand the rules and window timeline

    We are building a fixed-window rate limiter that protects a backend service by allowing at most capacity requests per window of window_size ticks.

    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, timestamps 0 through 4 belong to Window 0 ([0, 5)), and timestamp 5 starts Window 1 ([5, 10)), even if the very first call arrived at t = 1.

    Every submit_request(request_id, is_vip, timestamp) call follows five rules:

    1. Immediate admission vs. queuing: If the active window has used fewer than capacity slots, admit the request right away ("ADMITTED"). Otherwise put it in a waiting queue ("QUEUED").
    2. Non-preemption: Once admitted, a request is never kicked out by a later VIP.
    3. 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 to min_regular_slots slots are guaranteed to waiting regulars first whenever any are waiting.
    4. Idempotency: If request_id was seen before, do not charge another slot or add a duplicate queue entry — just return its current status ("ADMITTED" or "QUEUED").
    5. Idle gaps: If several full windows pass with no calls at all, we jump straight to the window containing the new timestamp and drain at most capacity waiting requests for that window. Draining skipped empty windows all at once would release a multi-window burst at a single timestamp, defeating the limiter.
  2. 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 deque queues: The oldest waiting regular is always at the front of regular_queue, and the oldest waiting VIP is always at the front of vip_queue. Removing from the front with popleft() takes O(1) time.
    • One status dictionary: request_status maps every seen request_id to "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.

  3. Build the state and queue-draining helpers

    Let's start VIPRateLimiter with clear state variables and two tiny helper methods:

    • _admit_one(request_id) is the single place that marks a request admitted, appends it to admitted_order, and increments used_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 to max_to_admit items from the front of queue, 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 += 1
    
  4. Roll into a new window with the three-phase quota split

    When a new window starts, how do we satisfy VIP priority, the min_regular_slots guarantee, 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 0 items, leaving all capacity slots 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 produces job_d, pro_1, pro_2, matching Example 1's expected get_admitted() order.

    To check whether the window has ended, we compare timestamp < self.window_start + self.window_size. If timestamp has reached or passed the end, integer division timestamp // self.window_size jumps 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)
    
  5. Handle incoming requests and idempotency

    Inside submit_request(request_id, is_vip, timestamp), the order of checks is crucial:

    1. Advance the window first. In Example 2, "v1" was queued in [0, 10) and resubmitted at timestamp = 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".
    2. Check request_status for idempotency. If request_id is already known, return its stored status immediately without touching used_in_window or either queue.
    3. Admit if room remains, else enqueue. Can used_in_window < capacity ever 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_window drains every waiting request unless doing so fills the new window completely. Therefore, whenever used_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)
    
  6. Write the judge driver function

    The automated judge passes parallel lists operations and arguments to vip_rate_limiter. We instantiate VIPRateLimiter(*args) when op == "VIPRateLimiter" (recording None as its output) and forward submit_request and get_admitted calls 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 results
    
  7. Trace 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.

  8. 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_request runs in amortized O(1) time (meaning an individual window roll may pop up to capacity items, 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. Each get_admitted() call takes O(A) time because it copies the list of A admitted IDs.
  • Space: O(R) memory, because each distinct request_id appears once in request_status, at most once in vip_queue or regular_queue, and at most once in admitted_order.

Edge cases

  • Exact window boundary: Windows are half-open [start, start + window_size). With window_size = 5, t = 4 stays in [0, 5) while t = 5 triggers a roll to [5, 10).
  • First request arrives late: If the first call arrives at t = 25 with window_size = 10, windows remain anchored to multiples of 10, so it lands in [20, 30).
  • Multi-window idle gaps: As in Example 2 (t = 7 to t = 32), jumping directly to [30, 40) drains at most capacity waiting 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 (0 if regular_queue is 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 once vip_queue is empty.
  • Resubmitting a request right as a roll admits it: Advancing the window before checking request_status ensures a previously queued ID that was just drained in the new window (like "v1" at t = 32 in Example 2) immediately returns "ADMITTED".
  • Resubmitting with a different is_vip flag: Because known IDs return early from request_status, a duplicate call cannot sneak a regular request into vip_queue or consume a second slot.

Common mistakes

  • Draining VIPs before reserved regulars: Admitting (capacity - min_regular_slots) VIPs first and min_regular_slots regulars second admits the same set of items, but reverses their order (pro_1, pro_2, job_d instead of Example 1's job_d, pro_1, pro_2).
  • Hard-reserving min_regular_slots when regular_queue is empty: Subtracting min_regular_slots from VIP capacity unconditionally leaves capacity unused while VIPs wait in line.
  • Advancing by window_start += window_size once 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 reset used_in_window and admit 5 * capacity requests at once.
  • Checking request_status before _advance_window_if_needed: A caller polling a queued request_id in a new window gets back a stale "QUEUED" instead of triggering the window roll that admits it.
  • Using list.pop(0) instead of collections.deque.popleft(): Popping index 0 of a Python list shifts every remaining element left in O(N) time; deque.popleft() is O(1).
  • Returning self.admitted_order directly 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 enforcing min_regular_slots still 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_size seconds can proactively pop up to capacity queued requests and dispatch them downstream even when no new client calls arrive. In a pure request-driven class without background threads, jumping lazily on submit_request avoids 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 for window_start and used_in_window, and status keys with a TTL (time-to-live) expiration for request_status so 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_size span) 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 of capacity, anti-starvation shifts to a rolling fairness counter — ensuring at least min_regular_slots out of every capacity consecutive drained slots come from regular_queue whenever 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) into regular_queue, where queued_window_index = timestamp // window_size. Because regular_queue is strictly ordered by arrival time, every standard request that has waited at least K windows (current_window_index - queued_window_index >= K) sits contiguously at the front of regular_queue. At the start of _start_new_window, before Phase 1, pop all aged-out requests from the front of regular_queue in O(1) per promoted request and move them into vip_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

Similar questions

More Intuit interview questions

All 34 Intuit questions →