Parallel Job Scheduler with Dependency Management
Data Structure DesignModel answerLast updated
Build a concurrent task executor that honors dependencies, enforces worker limits, and propagates failures through dependent jobs.
Problem
Design and implement a job execution system that runs tasks in parallel while respecting their dependency constraints. Each task has an identifier, a list of prerequisite task identifiers it must wait for, and an executable function.
Your system must:
- Honor dependencies: No task may begin until every task it depends on has completed successfully
- Limit concurrency: Respect a maximum number of simultaneously executing tasks
- Handle failures gracefully: When a task fails, all tasks that transitively depend on it should be marked as cancelled and never executed
- Return comprehensive results: Provide the final status (SUCCESS, FAILED, or CANCELLED) for every task
Interface
class Job:
def __init__(self, job_id: str, dependencies: List[str], task_func: Callable):
self.job_id = job_id
self.dependencies = dependencies # list of prerequisite job_ids
self.task_func = task_func # function to execute
def execute_all(jobs: List[Job], max_workers: int) -> Dict[str, str]:
"""
Execute all jobs respecting dependencies and concurrency limits.
Returns: {job_id: status} where status is SUCCESS, FAILED, or CANCELLED
"""
pass
Specifications
- The dependency graph is guaranteed to be acyclic (a DAG)
- A task is considered failed if its function raises an exception
- Up to 10,000 jobs may be provided
max_workerscan be up to 100- Job identifiers are unique strings
Example Scenario
Given tasks A (no dependencies), B (depends on A), and C (depends on A):
- If A completes successfully, both B and C become eligible and may run concurrently
- If A fails, both B and C should be marked CANCELLED without executing
Edge Cases to Consider
- What happens if a dependency references a non-existent job ID?
- How should the system behave with an empty job list?
- What if
max_workersis set to an invalid value? - Although the problem states the graph is acyclic, how would you detect cycles if that assumption were violated?
Hints
Hint 1
Start by computing each job's in-degree: how many dependencies must complete before it's ready to run
Hint 2
Use topological ordering principles—jobs with zero pending dependencies can execute immediately
Hint 3
When a job fails, traverse its descendants in the dependency graph to mark them all as cancelled
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution Approach
This problem combines topological sorting with concurrent execution. The core insight is to maintain readiness state for each job and schedule work as dependencies resolve.
High-Level Strategy
1. Build the dependency graph
Create an adjacency list tracking which jobs depend on each job (the "children"). For each job, maintain a counter of unresolved dependencies (its in-degree in the graph).
2. Initialize the ready queue
Any job with zero dependencies starts in a ready-to-execute state.
3. Coordinate execution
Use a single coordinator thread that:
- Submits ready jobs to a thread pool (up to the worker limit)
- Waits for any running job to complete
- Processes completion: on success, decrements children's dependency counts; on failure, cancels all descendants
- Adds newly-ready jobs to the queue
4. Propagate failures
When a job fails, perform a graph traversal from that job to mark all reachable descendants as CANCELLED. This prevents them from ever being scheduled.
Why This Design Works
Correctness invariants:
- A job is submitted only when its dependency counter reaches zero, guaranteeing all prerequisites succeeded
- Failed jobs trigger immediate downstream cancellation before any dependent becomes ready
- The coordinator is the single source of truth for state, eliminating race conditions
- Each job receives exactly one terminal status
Concurrency control:
By limiting in-flight futures rather than relying on the thread pool's internal queue, we maintain precise control over scheduling order and can easily add priority logic later.
Implementation
from collections import deque
from concurrent.futures import ThreadPoolExecutor, wait, FIRST_COMPLETED
from typing import Callable, Dict, List
SUCCESS, FAILED, CANCELLED = "SUCCESS", "FAILED", "CANCELLED"
class Job:
def __init__(self, job_id: str, dependencies: List[str], task_func: Callable):
self.job_id = job_id
self.dependencies = dependencies
self.task_func = task_func
def execute_all(jobs: List[Job], max_workers: int) -> Dict[str, str]:
if max_workers < 1:
raise ValueError("max_workers must be positive")
# Build job lookup and validate uniqueness
job_map: Dict[str, Job] = {}
for job in jobs:
if job.job_id in job_map:
raise ValueError(f"Duplicate job ID: {job.job_id}")
job_map[job.job_id] = job
# Build dependency graph
dependents: Dict[str, List[str]] = {jid: [] for jid in job_map}
unresolved_deps: Dict[str, int] = {}
status: Dict[str, str] = {}
invalid_jobs = []
for jid, job in job_map.items():
deps = set(job.dependencies) # deduplicate
valid_deps = [d for d in deps if d in job_map]
if len(valid_deps) < len(deps):
invalid_jobs.append(jid)
unresolved_deps[jid] = len(valid_deps)
for dep in valid_deps:
dependents[dep].append(jid)
# Cancel jobs with missing dependencies
def mark_cancelled_subtree(root: str) -> None:
"""DFS to cancel all descendants of a failed/cancelled job"""
stack = list(dependents[root])
while stack:
child = stack.pop()
if child not in status:
status[child] = CANCELLED
stack.extend(dependents[child])
for jid in invalid_jobs:
if jid not in status:
status[jid] = CANCELLED
mark_cancelled_subtree(jid)
# Initialize ready queue with zero-dependency jobs
ready_queue = deque(
jid for jid in job_map
if unresolved_deps[jid] == 0 and jid not in status
)
active_futures = {} # Future -> job_id mapping
with ThreadPoolExecutor(max_workers=max_workers) as executor:
while ready_queue or active_futures:
# Submit ready jobs up to worker limit
while ready_queue and len(active_futures) < max_workers:
jid = ready_queue.popleft()
if jid in status: # defensive check
continue
future = executor.submit(job_map[jid].task_func)
active_futures[future] = jid
if not active_futures:
break
# Wait for at least one job to complete
completed, _ = wait(active_futures, return_when=FIRST_COMPLETED)
for future in completed:
jid = active_futures.pop(future)
if future.exception() is None:
# Success: unlock dependent jobs
status[jid] = SUCCESS
for dependent in dependents[jid]:
unresolved_deps[dependent] -= 1
if unresolved_deps[dependent] == 0 and dependent not in status:
ready_queue.append(dependent)
else:
# Failure: cancel all downstream jobs
status[jid] = FAILED
mark_cancelled_subtree(jid)
# Mark any unreachable jobs (would only occur with cycles, which are ruled out)
for jid in job_map:
status.setdefault(jid, CANCELLED)
return status
Complexity Analysis
- Time: O(V + E) for graph construction and traversal, plus O(V · W) for coordination overhead where W is
max_workers - Space: O(V + E) for the adjacency list and tracking structures
- Actual runtime is dominated by task execution, not coordination
Edge Case Handling
Missing dependencies: Jobs referencing non-existent IDs are immediately cancelled along with their dependents. Alternatively, you could raise a validation error—state your preference to the interviewer.
Empty job list: Return an empty dictionary.
Invalid max_workers: Raise ValueError for values less than 1.
Cycles: Although ruled out by the problem statement, any jobs in a cycle would never reach zero unresolved dependencies. The final loop catches them and marks them CANCELLED.
Duplicate dependencies: Using set() deduplicates them so counts remain accurate.
Common Mistakes
- Race conditions: If multiple threads update dependency counters without coordination, jobs may execute before all dependencies complete
- Deadlock: Submitting all jobs to a fixed-size thread pool can deadlock if later jobs depend on earlier ones that can't start
- Memory leaks: Failing to clean up completed futures or maintaining references to all task results
- Incorrect cancellation: Only marking immediate children instead of the full transitive closure
Follow-Up Extensions
Priority scheduling: Add priority values and use a heap instead of a deque for the ready queue.
Retry logic: Wrap task functions in retry logic with exponential backoff before marking them failed.
Resource constraints: Track resource requirements per job (memory, CPU) and schedule based on available resources, not just worker count.
Partial success semantics: Allow jobs to specify whether they're retriable or whether their failure should cancel dependents.