KatInterview

Job Scheduler with Dependency Resolution

Data Structure DesignModel answer
MediumModel answerData Structure Designstate-machinedependency-graphconcurrency

Last updated

Build a thread-safe scheduler that accepts jobs with dependencies, identifies runnable jobs, and tracks state transitions through success and failure.

You need to build a scheduler class that manages jobs and their dependencies. Each job has a unique identifier and may require other jobs to complete successfully before it can start.

Your class should support:

  • Registering a job along with the identifiers of jobs it depends upon
  • Retrieving the current state of any job
  • Allowing workers to claim jobs that are ready to execute
  • Recording the outcome when a worker finishes a job (success or failure)

Requirements

Design the interface and internal structure. Your implementation should handle:

  • Jobs submitted in any order (a job may reference dependencies not yet registered)
  • Circular dependency detection
  • Propagation of failure states (when a dependency fails, downstream jobs cannot run)
  • Concurrent access by multiple workers claiming and completing jobs simultaneously

Start with a single-threaded design, then extend it to handle concurrent workers safely.

Key Questions to Address

  • How do you represent each job's lifecycle (pending, ready, running, completed, failed)?
  • What data structures efficiently track which jobs become runnable when a dependency completes?
  • How do you prevent race conditions when two workers try to claim the same job?
  • Should you detect dependency cycles at submission time or when a job attempts to run?
  • What happens to jobs that depend on a failed job?

Hints

Hint 1

Track both forward edges (what each job depends on) and reverse edges (what depends on each job) to efficiently propagate state changes

Hint 2

Use atomic state transitions to prevent two workers from claiming the same job

Hint 3

Consider maintaining a ready queue of jobs with zero unsatisfied dependencies