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
-
Executor(executor_id: str)— Models a single worker identified byexecutor_idthat buffers assigned integer task IDs in first-in, first-out (FIFO) order:assign_job(job_id: int) -> None: Appendsjob_idto the back of this worker's pending queue.execute_next_job() -> Optional[int]: Removes and returns the oldestjob_idat the front of this worker's pending queue, or returnsNoneif no tasks are waiting.
-
JobDispatcher()— Tracks active workers and routes incoming task IDs:add_executor(executor: Executor) -> None: Registersexecutorin the active pool. Ifexecutor.idis 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: Unregistersexecutor_idfrom the active pool (doing nothing ifexecutor_idis not active). Any pending tasks still sitting in the departing worker's queue are cleared from it and re-routed from oldest to newest throughdispatch, appending behind existing tasks on the chosen remaining workers (or entering the waiting buffer if no active workers remain).dispatch(job_id: int) -> None: Sendsjob_idto 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_idin a FIFO waiting queue until a worker is added.
get_state() -> Dict[str, List[int]]: Returns a dictionary mapping each activeexecutor_idto 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) <= 2000operations[i]is one of"add_executor","remove_executor","dispatch","execute_next_job", or"get_state"executor_idis a non-empty stringjob_idis an integer
Step-by-step walkthrough
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 withassign_job(job_id)andexecute_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 throughdispatchso 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 FIFOwaiting_jobsbuffer on the dispatcher and drain automatically once a worker joins. 4. Duplicate registrations and missing removals: Callingadd_executoron an already-active ID orremove_executoron an unknown ID is a safe no-op. 5. Directexecute_next_jobcalls: Callers invokeexecutor.execute_next_job()directly on the worker without going through the dispatcher, and subsequent dispatches immediately see the smaller queue length.Why monotonic sequence numbers beat list indices for rotation
Trace two workers
w1,w2whenw2completes 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 atw2inside[w1, w2, w3]) and then removedw2, the list would shrink to[w1, w3]where index1is alreadyw3—advancing the index by+1would skip right pastw3and wrongly choosew1!Instead, stamp each worker once upon registration with an ever-increasing integer sequence number (
added_seq = 0, 1, 2, ...) and storelast_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
w2is gone,last_picked_seq = 1still points straight tow3(2 > 1), or wraps around to index0when no active worker has a higher sequence number.Build Executor with a deque and live load queries
Because
execute_next_job()runs directly on anExecutorinstance without notifyingJobDispatcher, caching a separateload_by_idmap insideJobDispatcherwould leave stale counts whenever a worker finishes a job! Queryinglen(executor.queue)live during dispatch guarantees queue lengths are always up to date.Inside
Executor, store task IDs in Python'scollections.deque—a double-ended queue supportingO(1)right appends (append) andO(1)left pops (popleft), avoiding theO(k)shifting cost oflist.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)Pick the least-loaded worker in rotation order
Python
dicts preserve insertion order, and sincenext_seqstrictly increases,list(self.executors)is naturally ordered byadded_seq.Inside
_pick_executor_id: 1. Locatestart_index, the earliest active worker withadded_seq > self.last_picked_seq(defaulting to0to wrap around the ring). 2. Step across allnum_executorsworkers via(start_index + offset) % num_executors. 3. Updatebest_idonly 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: w2def _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_idHandle registration, removal, waiting buffer, and snapshots
Pay special attention to the order of operations in
remove_executor(executor_id): 1. Removeexecutor_idfromself.executorsbefore re-dispatching its tasks. If it stayed registered while its queue was emptied, its load would become0and it would immediately reclaim all of its own tasks! 2. Snapshot its queued tasks (orphaned_jobs), clear its deque, and callself.dispatch(job_id)from oldest to newest. If that worker was the last one in the pool,self.dispatchautomatically buffers those tasks inself.waiting_jobsuntil 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 stateTrace 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]}Complete solution
Putting
Executor,JobDispatcher, andrun_job_dispatchertogether: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 theEactive workers once finds the rotation start afterlast_picked_seqand selects the minimum live queue length, followed by anO(1)append to a deque (a double-ended queue supportingO(1)appends and pops at both ends).remove_executor—O(k * E)time forkorphaned tasks: Dictionary removal isO(1)average time, and each of thektasks on the departing worker is re-routed through anO(E)dispatchcall (or buffered inO(1)time ifEdropped to0).add_executor—O(1)time plusO(w)forwwaiting tasks: Dictionary insertion isO(1);waiting_jobsis non-empty only when the pool previously held0workers, so drainingwbuffered tasks onto this sole worker takesO(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 storesO(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_jobsin FIFO order and drain automatically as soon asadd_executorregisters a worker. - Removing the sole remaining worker while it holds tasks: Unregistering it first leaves
0active workers, so re-dispatching its orphaned tasks parks them safely inwaiting_jobsinstead of losing them. - Removing the worker that received the latest task: Leaving
self.last_picked_seqintact ensures the next tie-break still searches foradded_seq > last_picked_seqand lands on the exact successor that followed the departed worker. execute_next_jobon an empty queue or unknown ID: ReturnsNonecleanly without raisingIndexErrororKeyError.- Duplicate
add_executoror unknownremove_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_seqat the back of the rotation ring.
Common mistakes
- Caching queue lengths inside
JobDispatcherwithout completion hooks: Directexecutor.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 (
w2in 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: Overwritesbest_idon ties and picks the last tied worker around the circle instead of the first one afterlast_picked_seq. - Re-dispatching orphaned tasks before popping the worker from
self.executors: Once cleared, the departing worker has load0and immediately receives all its own tasks back! - Using
list.pop(0)orlist.pop()insideExecutor:list.pop(0)takesO(k)per dequeue, whilelist.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 picksmin(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 supportingO(log E)insert, delete, and successor search, such asSortedList) keyed byadded_seq, paired with a min-heap or sorted set of non-empty load keys.dispatchlooks up the minimum load bucket, binary-searches (bisect_right) for the firstadded_seq > last_picked_seq(wrapping to index0), and moves that worker frombuckets[load]tobuckets[load + 1]inO(log E)time. Because the router now indexes loads explicitly,Executor.execute_next_job()must invoke anon_job_completed(executor_id)callback on the router so the worker moves frombuckets[load]down tobuckets[load - 1]inO(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 withload() >= max_loadinside_pick_executor_id; when all workers are at capacity, hold incoming tasks inwaiting_jobs(or apply backpressure) and drain one waiting task whenever a worker finishes a job. For heterogeneous throughputrate(tasks per second), minimize estimated completion latency(executor.load() + 1) / executor.raterather than raw queue count, breaking ties with the sameadded_seqrotation. - 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-levelrouter_lock, and guard eachExecutor.queuewith its ownqueue_lockso workers can dequeue tasks in parallel. Because bothdispatch(select +assign_job) andremove_executor(pop fromexecutors+ drainqueue+ re-dispatch) acquirerouter_lockfirst, a worker cannot be selected once removal starts; enforcing a strict lock ordering (always acquiringrouter_lockbefore anyqueue_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_idwithout corrupting state).
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?
- How would you adapt the routing rule if workers have bounded queue limits or process jobs at different throughput rates?
- 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?
- If a worker process dies abruptly without calling remove_executor, what architectural mechanisms prevent its pending or in-flight tasks from disappearing?
Similar questions
- Implement a Conversational Flight Search and Booking Agent with Tool Calling
- In-Memory Feature Flag Rule Evaluator
- Locate Files Across a Directory Hierarchy and Return Absolute Paths
- Remaining Grid Leaves After Wind Shifts
- Benchmarking and Release-Gating Platform for Tool-Using AI Agents
- Greedy and Beam-Search Token Sequence Decoding
More Cresta interview questions
- Implement a Conversational Flight Search and Booking Agent with Tool Calling Medium
- Remaining Grid Leaves After Wind Shifts Medium
- In-Memory Feature Flag Rule Evaluator Medium Pro
- Benchmarking and Release-Gating Platform for Tool-Using AI Agents Medium Pro
- Longest Suffix-to-Prefix String Overlap Medium Pro
- Asynchronous Video Walkthrough of a Past AI System Medium Pro
- Locate Files Across a Directory Hierarchy and Return Absolute Paths Medium Pro
- Greedy and Beam-Search Token Sequence Decoding Medium Pro
- Taking a Validated Prototype to Production Easy Pro