KatInterview

Parallel Job Scheduler with Dependency Management

Data Structure DesignModel answer
MediumModel answerData Structure Designconcurrencygraphstopological-sort

Last 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:

  1. Honor dependencies: No task may begin until every task it depends on has completed successfully
  2. Limit concurrency: Respect a maximum number of simultaneously executing tasks
  3. Handle failures gracefully: When a task fails, all tasks that transitively depend on it should be marked as cancelled and never executed
  4. 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_workers can 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_workers is 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