Dynamic Task Router with Least-Loaded Tie Rotation

Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen

Problem Statement

Build an in-memory task routing system composed of two classes—Executor and JobDispatcher—along with a command runner run_job_dispatcher.

Class Specifications

  1. Executor(executor_id: str) — Models a single worker identified by executor_id that buffers assigned integer task IDs in first-in, first-out (FIFO) order:

    • assign_job(job_id: int) -> None: Appends job_id to the back of this worker's pending queue.
    • execute_next_job() -> Optional[int]: Removes and returns the oldest job_id at the front of this worker's pending queue, or returns None if no tasks are waiting.
  2. JobDispatcher() — Tracks active workers and routes incoming task IDs:

    • add_executor(executor: Executor) -> None: Registers executor in the active pool. If executor.id is already active, ignore the call so the existing worker and its queue remain untouched. If tasks arrived while zero workers were active, immediately route those buffered tasks in FIFO order.
    • remove_executor(executor_id: str) -> None: Unregisters executor_id from the active pool (doing nothing if executor_id is not active). Any pending tasks still sitting in the departing worker's queue are cleared from it and re-routed from oldest to newest through dispatch, appending behind existing tasks on the chosen remaining workers (or entering the waiting buffer if no active workers remain).
    • dispatch(job_id: int) -> None: Sends job_id to the active worker with the fewest pending tasks in its queue:
      • Tie-breaking (registration-order rotation): Active workers form a circular ring ordered by when they were registered. Whenever multiple workers tie for the minimum pending count, begin scanning strictly after the worker that received the most recently assigned task (wrapping around to the earliest-registered active worker; before any task is assigned, start at the earliest-registered worker; if the previous recipient was subsequently removed, start at the first active worker registered after it) and pick the first tied worker encountered.
      • Empty pool: If zero workers are active, hold job_id in a FIFO waiting queue until a worker is added.
    • get_state() -> Dict[str, List[int]]: Returns a dictionary mapping each active executor_id to a list of its pending task IDs ordered from oldest to newest.

Command Runner

Implement run_job_dispatcher(operations: List[str], arguments: List[List]) -> List to start with an empty JobDispatcher, apply each (operations[i], arguments[i]) pair in order, and return the list of step outputs: - "add_executor", [executor_id]: Calls add_executor(Executor(executor_id)) and records None. - "remove_executor", [executor_id]: Calls remove_executor(executor_id) and records None. - "dispatch", [job_id]: Calls dispatch(job_id) and records None. - "execute_next_job", [executor_id]: Invokes execute_next_job() directly on the active worker executor_id (if active) and records its return value (or None when executor_id is unknown or idle); subsequent dispatch calls must immediately see the worker's reduced queue size. - "get_state", []: Records the dictionary returned by get_state().

def run_job_dispatcher(operations: List[str], arguments: List[List]) -> List:

Examples

Example 1

Input:
  operations = ["add_executor", "add_executor", "add_executor", "dispatch", "dispatch", "dispatch", "dispatch", "get_state"]
  arguments  = [["w1"], ["w2"], ["w3"], [101], [102], [103], [104], []]
Output:
  [None, None, None, None, None, None, None, {"w1": [101, 104], "w2": [102], "w3": [103]}]

Explanation: Workers "w1", "w2", and "w3" start empty, so tasks 101, 102, and 103 go to "w1", "w2", and "w3" in registration order. On dispatch(104), all three workers tie at load 1; scanning after "w3" wraps around to "w1", giving "w1" task 104.

Example 2

Input:
  operations = ["add_executor", "add_executor", "dispatch", "dispatch", "execute_next_job", "dispatch", "dispatch", "get_state"]
  arguments  = [["w1"], ["w2"], [50], [60], ["w2"], [70], [80], []]
Output:
  [None, None, None, None, 60, None, None, {"w1": [50, 80], "w2": [70]}]

Explanation: Tasks 50 and 60 go to "w1" and "w2". Calling execute_next_job on "w2" pops and returns 60, dropping "w2" to load 0. Next, dispatch(70) picks "w2" (0 < 1). Finally, on dispatch(80), "w1" and "w2" tie at load 1, and scanning after "w2" wraps to "w1".

Example 3

Input:
  operations = ["add_executor", "add_executor", "add_executor", "dispatch", "dispatch", "dispatch", "dispatch", "remove_executor", "get_state"]
  arguments  = [["w1"], ["w2"], ["w3"], [11], [22], [33], [44], ["w1"], []]
Output:
  [None, None, None, None, None, None, None, None, {"w2": [22, 11], "w3": [33, 44]}]

Explanation: Before removal, queues are "w1": [11, 44], "w2": [22], and "w3": [33], with "w1" having received the most recent task (44). Removing "w1" unregisters it first and re-routes [11, 44] oldest-first: 11 breaks the 1-vs-1 tie right after "w1" onto "w2", and 44 goes to the now lighter "w3".

Constraints

  • 1 <= len(operations) == len(arguments) <= 2000
  • operations[i] is one of "add_executor", "remove_executor", "dispatch", "execute_next_job", or "get_state"
  • executor_id is a non-empty string
  • job_id is an integer

Step-by-step walkthrough

  1. Understand the classes and settle every boundary behavior

    We are building two cooperating classes: - Executor: owns a FIFO (first-in, first-out: earliest enqueued item leaves first) queue of integer task IDs with assign_job(job_id) and execute_next_job(). - JobDispatcher: maintains an active pool of workers and routes each incoming task to whichever worker currently holds the fewest queued tasks, breaking ties via round-robin (rotating around a fixed circular sequence).

    Let's pin down the exact rules before writing code: 1. Round-robin among ties: Active workers stay ordered by registration time. On every dispatch, scanning begins strictly after whichever worker received the latest task (wrapping around to the start) and picks the first worker holding the minimum queue length. 2. Re-routing tasks on removal: Unregister the departing worker first, then re-dispatch its queued tasks from oldest to newest through dispatch so they append behind existing tasks on the survivors (matching Example 3: {"w2": [22, 11], "w3": [33, 44]}). 3. Empty worker pool: Tasks are never lost—when zero workers are active (or when the last worker leaves with tasks in its queue), tasks wait in a FIFO waiting_jobs buffer on the dispatcher and drain automatically once a worker joins. 4. Duplicate registrations and missing removals: Calling add_executor on an already-active ID or remove_executor on an unknown ID is a safe no-op. 5. Direct execute_next_job calls: Callers invoke executor.execute_next_job() directly on the worker without going through the dispatcher, and subsequent dispatches immediately see the smaller queue length.

  2. Why monotonic sequence numbers beat list indices for rotation

    Trace two workers w1, w2 when w2 completes a task early (Example 2):

    1. Dispatch 50, 60         ->  w1:[50], w2:[60]   (ties went w1 -> w2)
    2. w2 executes job 60      ->  w1:[50], w2:[]
    3. Dispatch 70             ->  w2 has load 0 < 1, so least-loaded wins: w2 gets 70 (last pick = w2)
    4. Dispatch 80             ->  tied at load 1; scan starts right after w2 -> wraps to w1!
    

    How should we remember "where the previous pick happened" when workers can also be removed? If we stored a list index such as last_index = 1 (pointing at w2 inside [w1, w2, w3]) and then removed w2, the list would shrink to [w1, w3] where index 1 is already w3—advancing the index by +1 would skip right past w3 and wrongly choose w1!

    Instead, stamp each worker once upon registration with an ever-increasing integer sequence number (added_seq = 0, 1, 2, ...) and store last_picked_seq:

    Added:     w1 (seq 0)    w2 (seq 1, got last job -> last_picked_seq = 1)    w3 (seq 2)
    Remove w2: w1 (seq 0)                                                       w3 (seq 2)
    
    Next dispatch searches for first worker with added_seq > 1  -->  lands cleanly on w3 (seq 2)!
    

    Even after w2 is gone, last_picked_seq = 1 still points straight to w3 (2 > 1), or wraps around to index 0 when no active worker has a higher sequence number.

  3. Build Executor with a deque and live load queries

    Because execute_next_job() runs directly on an Executor instance without notifying JobDispatcher, caching a separate load_by_id map inside JobDispatcher would leave stale counts whenever a worker finishes a job! Querying len(executor.queue) live during dispatch guarantees queue lengths are always up to date.

    Inside Executor, store task IDs in Python's collections.deque—a double-ended queue supporting O(1) right appends (append) and O(1) left pops (popleft), avoiding the O(k) shifting cost of list.pop(0):

    from collections import deque
    
    
    class Executor:
        def __init__(self, executor_id: str):
            self.id: str = executor_id
            # queue: FIFO deque of pending job IDs, e.g. deque([50, 80]) with oldest on the left
            self.queue: deque[int] = deque()
    
        def assign_job(self, job_id: int) -> None:
            self.queue.append(job_id)
    
        def execute_next_job(self) -> Optional[int]:
            if not self.queue:
                return None
            return self.queue.popleft()
    
        def load(self) -> int:
            return len(self.queue)
    
        def pending_jobs(self) -> List[int]:
            return list(self.queue)
    
  4. Pick the least-loaded worker in rotation order

    Python dicts preserve insertion order, and since next_seq strictly increases, list(self.executors) is naturally ordered by added_seq.

    Inside _pick_executor_id: 1. Locate start_index, the earliest active worker with added_seq > self.last_picked_seq (defaulting to 0 to wrap around the ring). 2. Step across all num_executors workers via (start_index + offset) % num_executors. 3. Update best_id only on strict < (candidate_load < best_load), never <=. Strict < guarantees that among tied workers, the very first one encountered in rotation order wins:

    Ring: [w1(load=1), w2(load=1), w3(load=1)], last_picked_seq = 0 (w1)
    start_index = 1 (w2)
    
    offset 0 -> w2 (load 1): first candidate -> best = w2 (1)
    offset 1 -> w3 (load 1): is 1 < 1? False -> best stays w2
    offset 2 -> w1 (load 1): is 1 < 1? False -> best stays w2   --> Winner: w2
    
        def _pick_executor_id(self) -> Optional[str]:
            """Return the least-loaded executor ID, breaking ties round-robin after last_picked_seq."""
            executor_ids = list(self.executors)
            if not executor_ids:
                return None
    
            # Step 1: Find the rotation start—the first executor added after last_picked_seq
            # (if none has a larger sequence number, wrap around to index 0).
            start_index = 0
            for index, executor_id in enumerate(executor_ids):
                if self.added_seq[executor_id] > self.last_picked_seq:
                    start_index = index
                    break
    
            # Step 2: Walk one full circle from start_index; strict `<` keeps the earliest
            # executor in rotation order whenever multiple executors tie for minimum load.
            best_id: Optional[str] = None
            best_load = 0
            num_executors = len(executor_ids)
            for offset in range(num_executors):
                candidate_id = executor_ids[(start_index + offset) % num_executors]
                candidate_load = self.executors[candidate_id].load()
                if best_id is None or candidate_load < best_load:
                    best_id = candidate_id
                    best_load = candidate_load
    
            return best_id
    
  5. Handle registration, removal, waiting buffer, and snapshots

    Pay special attention to the order of operations in remove_executor(executor_id): 1. Remove executor_id from self.executors before re-dispatching its tasks. If it stayed registered while its queue was emptied, its load would become 0 and it would immediately reclaim all of its own tasks! 2. Snapshot its queued tasks (orphaned_jobs), clear its deque, and call self.dispatch(job_id) from oldest to newest. If that worker was the last one in the pool, self.dispatch automatically buffers those tasks in self.waiting_jobs until another worker registers.

    class JobDispatcher:
        def __init__(self):
            self.executors: Dict[str, Executor] = {}
            self.added_seq: Dict[str, int] = {}
            self.next_seq: int = 0
            self.last_picked_seq: int = -1
            self.waiting_jobs: deque[int] = deque()
    
        def add_executor(self, executor: Executor) -> None:
            if executor.id in self.executors:
                return
            self.executors[executor.id] = executor
            self.added_seq[executor.id] = self.next_seq
            self.next_seq += 1
            while self.waiting_jobs:
                self.dispatch(self.waiting_jobs.popleft())
    
        def remove_executor(self, executor_id: str) -> None:
            removed_executor = self.executors.pop(executor_id, None)
            if removed_executor is None:
                return
            del self.added_seq[executor_id]
            orphaned_jobs = removed_executor.pending_jobs()
            removed_executor.queue.clear()
            for job_id in orphaned_jobs:
                self.dispatch(job_id)
    
        def dispatch(self, job_id: int) -> None:
            chosen_id = self._pick_executor_id()
            if chosen_id is None:
                self.waiting_jobs.append(job_id)
                return
            self.executors[chosen_id].assign_job(job_id)
            self.last_picked_seq = self.added_seq[chosen_id]
    
        def get_state(self) -> Dict[str, List[int]]:
            state: Dict[str, List[int]] = {}
            for executor_id, executor in self.executors.items():
                state[executor_id] = executor.pending_jobs()
            return state
    
  6. Trace Examples 1, 2, and 3 step by step

    Example 1: add w1(0), w2(1), w3(2); dispatch 101, 102, 103, 104
      - 101 -> w1 (last=0), 102 -> w2 (last=1), 103 -> w3 (last=2)
      - 104 -> all tied at load 1; scan wraps after seq 2 to w1 -> {"w1": [101, 104], "w2": [102], "w3": [103]}
    
    Example 2: add w1(0), w2(1); dispatch 50 -> w1:[50]; dispatch 60 -> w2:[60]
      - execute_next_job("w2") pops 60 -> w1:[50], w2:[]
      - dispatch(70): w2 has load 0 < 1 -> w2:[70] (last=1)
      - dispatch(80): tied at load 1; scan wraps after seq 1 to w1 -> {"w1": [50, 80], "w2": [70]}
    
    Example 3: add w1(0), w2(1), w3(2); dispatch 11, 22, 33, 44 -> w1:[11, 44], w2:[22], w3:[33] (last=0)
      - remove_executor("w1"): unregister w1 first; orphaned_jobs = [11, 44]
      - re-dispatch 11: w2(load 1) and w3(load 1) tie; scan after seq 0 picks w2 -> w2:[22, 11] (last=1)
      - re-dispatch 44: w3(load 1 < 2) wins -> w3:[33, 44] -> {"w2": [22, 11], "w3": [33, 44]}
    
  7. Complete solution

    Putting Executor, JobDispatcher, and run_job_dispatcher together:

    from typing import Any, Dict, List, Optional, Set, Tuple
    from collections import deque
    
    
    class Executor:
        def __init__(self, executor_id: str):
            self.id: str = executor_id
            # queue: FIFO deque of pending job IDs, e.g. deque([50, 80]) with oldest on the left
            self.queue: deque[int] = deque()
    
        def assign_job(self, job_id: int) -> None:
            self.queue.append(job_id)
    
        def execute_next_job(self) -> Optional[int]:
            if not self.queue:
                return None
            return self.queue.popleft()
    
        def load(self) -> int:
            return len(self.queue)
    
        def pending_jobs(self) -> List[int]:
            return list(self.queue)
    
    
    class JobDispatcher:
        def __init__(self):
            # executors: {executor_id: Executor} preserving registration order
            self.executors: Dict[str, Executor] = {}
            # added_seq: {executor_id: monotonic int} assigned once when registered
            self.added_seq: Dict[str, int] = {}
            self.next_seq: int = 0
            # last_picked_seq: sequence number of whichever executor received the latest job
            self.last_picked_seq: int = -1
            # waiting_jobs: FIFO queue of jobs dispatched while zero executors exist
            self.waiting_jobs: deque[int] = deque()
    
        def add_executor(self, executor: Executor) -> None:
            if executor.id in self.executors:
                # Executor IDs are unique; ignore duplicate registrations to preserve existing queues.
                return
    
            self.executors[executor.id] = executor
            self.added_seq[executor.id] = self.next_seq
            self.next_seq += 1
    
            # Hand out any jobs that arrived while the pool had no executors.
            while self.waiting_jobs:
                self.dispatch(self.waiting_jobs.popleft())
    
        def remove_executor(self, executor_id: str) -> None:
            # Unregister BEFORE re-dispatching so the removed executor never gets its own jobs back.
            removed_executor = self.executors.pop(executor_id, None)
            if removed_executor is None:
                return
            del self.added_seq[executor_id]
    
            # Keep self.last_picked_seq untouched: if this executor got the last job, its sequence
            # number still tells _pick_executor_id to start at the first executor added after it.
            orphaned_jobs = removed_executor.pending_jobs()
            removed_executor.queue.clear()
            for job_id in orphaned_jobs:
                self.dispatch(job_id)
    
        def _pick_executor_id(self) -> Optional[str]:
            """Return the least-loaded executor ID, breaking ties round-robin after last_picked_seq."""
            executor_ids = list(self.executors)
            if not executor_ids:
                return None
    
            # Step 1: Find the rotation start—the first executor added after last_picked_seq
            # (if none has a larger sequence number, wrap around to index 0).
            start_index = 0
            for index, executor_id in enumerate(executor_ids):
                if self.added_seq[executor_id] > self.last_picked_seq:
                    start_index = index
                    break
    
            # Step 2: Walk one full circle from start_index; strict `<` keeps the earliest
            # executor in rotation order whenever multiple executors tie for minimum load.
            best_id: Optional[str] = None
            best_load = 0
            num_executors = len(executor_ids)
            for offset in range(num_executors):
                candidate_id = executor_ids[(start_index + offset) % num_executors]
                candidate_load = self.executors[candidate_id].load()
                if best_id is None or candidate_load < best_load:
                    best_id = candidate_id
                    best_load = candidate_load
    
            return best_id
    
        def dispatch(self, job_id: int) -> None:
            chosen_id = self._pick_executor_id()
            if chosen_id is None:
                self.waiting_jobs.append(job_id)
                return
    
            self.executors[chosen_id].assign_job(job_id)
            self.last_picked_seq = self.added_seq[chosen_id]
    
        def get_state(self) -> Dict[str, List[int]]:
            state: Dict[str, List[int]] = {}
            for executor_id, executor in self.executors.items():
                state[executor_id] = executor.pending_jobs()
            return state
    
    
    def run_job_dispatcher(operations: List[str], arguments: List[List]) -> List:
        dispatcher = JobDispatcher()
        outputs: List[Any] = []
    
        for op, args in zip(operations, arguments):
            if op == "add_executor":
                dispatcher.add_executor(Executor(args[0]))
                outputs.append(None)
            elif op == "remove_executor":
                dispatcher.remove_executor(args[0])
                outputs.append(None)
            elif op == "dispatch":
                dispatcher.dispatch(args[0])
                outputs.append(None)
            elif op == "execute_next_job":
                executor = dispatcher.executors.get(args[0])
                if executor is None:
                    outputs.append(None)
                else:
                    outputs.append(executor.execute_next_job())
            elif op == "get_state":
                outputs.append(dispatcher.get_state())
            else:
                raise ValueError(f"Unknown operation: {op}")
    
        return outputs
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture a restaurant host seating incoming guests across a line of servers (w1, w2, w3). The host always checks whose section currently has the fewest waiting tables, and whenever several servers tie for the fewest, the host uses round-robin (taking turns in a circular order) starting immediately after whichever server received the previous guest. Because servers finish tables independently (execute_next_job) and can end their shift mid-service (remove_executor), we issue each arriving server a permanent, monotonically increasing ticket number (added_seq = 0, 1, 2, ...) and inspect each server's queue length live during every dispatch.

Two tempting shortcuts break under these rules. First, if the dispatcher caches load counts or maintains a static min-heap without completion callbacks from Executor, calling executor.execute_next_job() shrinks the worker's real queue while leaving the dispatcher's cached load stale. Second, storing the rotation cursor as a list index (0, 1, 2) fails whenever a worker leaves, because deleting an entry shifts all subsequent indices left by one and skips a worker on the next tie. Querying len(executor.queue) live and anchoring the rotation cursor to last_picked_seq eliminates both bugs.

Walk through w1 (seq 0), w2 (seq 1), and w3 (seq 2): - dispatch(11), dispatch(22), dispatch(33): loads start at 0, so tasks go w1 -> w2 -> w3 (last_picked_seq = 2). - dispatch(44): all three tie at load 1; no sequence exceeds 2, so scanning wraps to w1 (w1: [11, 44], last_picked_seq = 0). - remove_executor("w1"): w1 is unregistered first, and its orphaned tasks [11, 44] are re-routed oldest-first—11 breaks the tie after seq 0 onto w2 ([22, 11]), and 44 goes to the lighter w3 ([33, 44]).

Complexity

Let E be the number of currently active workers and J be the total number of queued tasks across all workers and waiting_jobs.

  • dispatch — O(E) time: Scanning the E active workers once finds the rotation start after last_picked_seq and selects the minimum live queue length, followed by an O(1) append to a deque (a double-ended queue supporting O(1) appends and pops at both ends).
  • remove_executor — O(k * E) time for k orphaned tasks: Dictionary removal is O(1) average time, and each of the k tasks on the departing worker is re-routed through an O(E) dispatch call (or buffered in O(1) time if E dropped to 0).
  • add_executor — O(1) time plus O(w) for w waiting tasks: Dictionary insertion is O(1); waiting_jobs is non-empty only when the pool previously held 0 workers, so draining w buffered tasks onto this sole worker takes O(1) per task.
  • execute_next_job — O(1) time: deque.popleft() removes the oldest task from the front without shifting remaining items.
  • get_state — O(E + J) time: Copies each active worker's deque into a fresh list.
  • Space complexity — O(E + J): Each active worker stores O(1) metadata, and each pending or buffered task ID lives in at most one deque.

Edge cases

  • Dispatching with zero active workers: Tasks wait in waiting_jobs in FIFO order and drain automatically as soon as add_executor registers a worker.
  • Removing the sole remaining worker while it holds tasks: Unregistering it first leaves 0 active workers, so re-dispatching its orphaned tasks parks them safely in waiting_jobs instead of losing them.
  • Removing the worker that received the latest task: Leaving self.last_picked_seq intact ensures the next tie-break still searches for added_seq > last_picked_seq and lands on the exact successor that followed the departed worker.
  • execute_next_job on an empty queue or unknown ID: Returns None cleanly without raising IndexError or KeyError.
  • Duplicate add_executor or unknown remove_executor: Treated as safe no-ops so an active worker never loses its pending queue.
  • Re-adding a previously removed worker ID: Registers as a fresh worker with an empty queue and a new added_seq at the back of the rotation ring.

Common mistakes

  • Caching queue lengths inside JobDispatcher without completion hooks: Direct executor.execute_next_job() calls reduce the real queue length without updating the dispatcher's cache, starving idle workers.
  • Storing a list index as the round-robin cursor: Removing a worker shifts later indices left by one and causes the next tie-break to skip a worker.
  • Advancing a blind round-robin pointer independently of least-loaded picks: When an out-of-turn least-loaded worker wins (w2 in Example 2), the next tie must rotate from that worker (w2), not from where an independent counter happened to sit.
  • Using <= instead of < when comparing loads: Overwrites best_id on ties and picks the last tied worker around the circle instead of the first one after last_picked_seq.
  • Re-dispatching orphaned tasks before popping the worker from self.executors: Once cleared, the departing worker has load 0 and immediately receives all its own tasks back!
  • Using list.pop(0) or list.pop() inside Executor: list.pop(0) takes O(k) per dequeue, while list.pop() executes newest-first (LIFO) rather than oldest-first (FIFO).

Alternative approaches

  • Least-recently-assigned tie-breaking: An alternative interpretation of fairness stamps each worker with last_assigned_turn (initially -1) and picks min(executors, key=lambda e: (e.load(), last_assigned_turn[e.id], added_seq[e.id])). That rewards whichever tied worker has waited longest since its last assignment; it differs slightly from circular registration-order rotation after an out-of-turn least-loaded pick, so clarifying tie-break semantics upfront is essential in interviews.

Follow-up questions

  • How can you scale routing to tens of thousands of workers in sub-linear time per job while preserving the exact tie-breaking order, and how must job completion notify the router? Bucket active workers by queue length in buckets[load], where each bucket is a balanced binary search tree (a sorted container supporting O(log E) insert, delete, and successor search, such as SortedList) keyed by added_seq, paired with a min-heap or sorted set of non-empty load keys. dispatch looks up the minimum load bucket, binary-searches (bisect_right) for the first added_seq > last_picked_seq (wrapping to index 0), and moves that worker from buckets[load] to buckets[load + 1] in O(log E) time. Because the router now indexes loads explicitly, Executor.execute_next_job() must invoke an on_job_completed(executor_id) callback on the router so the worker moves from buckets[load] down to buckets[load - 1] in O(log E) time.
  • How would you adapt the routing rule if workers have bounded queue limits or process jobs at different throughput rates? For per-worker queue caps max_load, skip any worker with load() >= max_load inside _pick_executor_id; when all workers are at capacity, hold incoming tasks in waiting_jobs (or apply backpressure) and drain one waiting task whenever a worker finishes a job. For heterogeneous throughput rate (tasks per second), minimize estimated completion latency (executor.load() + 1) / executor.rate rather than raw queue count, breaking ties with the same added_seq rotation.
  • Suppose multiple threads invoke dispatch, remove_executor, and execute_next_job concurrently—what locking strategy prevents races and deadlocks while ensuring departing workers never receive new work? Guard the router's membership and rotation state (executors, added_seq, last_picked_seq, waiting_jobs) with a router-level router_lock, and guard each Executor.queue with its own queue_lock so workers can dequeue tasks in parallel. Because both dispatch (select + assign_job) and remove_executor (pop from executors + drain queue + re-dispatch) acquire router_lock first, a worker cannot be selected once removal starts; enforcing a strict lock ordering (always acquiring router_lock before any queue_lock, never the reverse) guarantees deadlock freedom.
  • If a worker process dies abruptly without calling remove_executor, what architectural mechanisms prevent its pending or in-flight tasks from disappearing? Volatile in-process queues vanish when a worker crashes, so the router must log assignments in durable storage and require workers to send periodic heartbeats (lightweight liveness pings that renew a time-bounded lease) along with explicit completion acknowledgments. When a worker's lease expires without a heartbeat, the router marks it dead and re-dispatches every unacknowledged task assigned to it; because an in-flight task may execute twice after a crash, task handlers should be idempotent (safe to run more than once for the same job_id without corrupting state).

Follow-up questions

Similar questions

More Cresta interview questions

All 10 Cresta questions →