Job Scheduler with Dependency Resolution
Data Structure DesignModel answerLast 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
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is maintaining a dependency graph while efficiently identifying which jobs can run next. Each job moves through a clear state machine, and we need both forward pointers (dependencies) and backward pointers (dependents) for efficient updates.
State Machine
Each job progresses through these states:
- PENDING: submitted but has unsatisfied dependencies
- READY: all dependencies met, available for workers to claim
- RUNNING: claimed by a worker, currently executing
- COMPLETED: finished successfully
- FAILED: execution failed or a dependency failed
Data Structures
from enum import Enum
from threading import Lock
from typing import Set, Dict, List, Optional
class JobStatus(Enum):
PENDING = "pending"
READY = "ready"
RUNNING = "running"
COMPLETED = "completed"
FAILED = "failed"
class Job:
def __init__(self, job_id: str, dependencies: Set[str]):
self.job_id = job_id
self.status = JobStatus.PENDING
self.dependencies = dependencies.copy()
self.unmet_dependencies = dependencies.copy()
self.dependents = set() # Jobs waiting on this one
class JobScheduler:
def __init__(self):
self.jobs: Dict[str, Job] = {}
self.ready_queue: List[str] = []
self.lock = Lock()
def submit(self, job_id: str, dependencies: Set[str]) -> bool:
"""Register a new job. Returns False if job_id already exists."""
with self.lock:
if job_id in self.jobs:
return False
# Detect self-dependency
if job_id in dependencies:
raise ValueError(f"Job {job_id} cannot depend on itself")
job = Job(job_id, dependencies)
self.jobs[job_id] = job
# Wire up reverse edges and check for already-completed deps
for dep_id in dependencies:
if dep_id not in self.jobs:
# Dependency not yet submitted; create placeholder
self.jobs[dep_id] = Job(dep_id, set())
dep_job = self.jobs[dep_id]
dep_job.dependents.add(job_id)
# Check if dependency already finished
if dep_job.status == JobStatus.COMPLETED:
job.unmet_dependencies.discard(dep_id)
elif dep_job.status == JobStatus.FAILED:
job.status = JobStatus.FAILED
return True
# If no unmet dependencies, mark ready
if not job.unmet_dependencies and job.status != JobStatus.FAILED:
job.status = JobStatus.READY
self.ready_queue.append(job_id)
return True
def get_status(self, job_id: str) -> Optional[JobStatus]:
"""Returns current status, or None if job doesn't exist."""
with self.lock:
job = self.jobs.get(job_id)
return job.status if job else None
def claim_job(self) -> Optional[str]:
"""Worker calls this to get a job to execute. Returns None if nothing ready."""
with self.lock:
while self.ready_queue:
job_id = self.ready_queue.pop(0)
job = self.jobs[job_id]
# Double-check it's still ready (defensive)
if job.status == JobStatus.READY:
job.status = JobStatus.RUNNING
return job_id
return None
def report_success(self, job_id: str):
"""Worker reports successful completion."""
with self.lock:
job = self.jobs.get(job_id)
if not job or job.status != JobStatus.RUNNING:
raise ValueError(f"Job {job_id} is not running")
job.status = JobStatus.COMPLETED
# Unblock dependents
for dependent_id in job.dependents:
dependent = self.jobs[dependent_id]
dependent.unmet_dependencies.discard(job_id)
if not dependent.unmet_dependencies and dependent.status == JobStatus.PENDING:
dependent.status = JobStatus.READY
self.ready_queue.append(dependent_id)
def report_failure(self, job_id: str):
"""Worker reports failure; cascade to dependents."""
with self.lock:
job = self.jobs.get(job_id)
if not job or job.status != JobStatus.RUNNING:
raise ValueError(f"Job {job_id} is not running")
job.status = JobStatus.FAILED
# Cascade failure to all dependents recursively
self._cascade_failure(job_id)
def _cascade_failure(self, job_id: str):
"""Mark all transitive dependents as failed."""
job = self.jobs[job_id]
for dependent_id in job.dependents:
dependent = self.jobs[dependent_id]
if dependent.status in (JobStatus.PENDING, JobStatus.READY):
dependent.status = JobStatus.FAILED
# Remove from ready queue if present
if dependent_id in self.ready_queue:
self.ready_queue.remove(dependent_id)
# Recursively fail downstream
self._cascade_failure(dependent_id)
Cycle Detection
The implementation above allows cycles to form but prevents infinite loops because circular jobs will never become ready (they always have at least one unmet dependency). For stricter validation, add cycle detection at submission time using DFS:
def _has_cycle(self, start_id: str, visited: Set[str], rec_stack: Set[str]) -> bool:
visited.add(start_id)
rec_stack.add(start_id)
job = self.jobs.get(start_id)
if job:
for dep_id in job.dependencies:
if dep_id not in visited:
if self._has_cycle(dep_id, visited, rec_stack):
return True
elif dep_id in rec_stack:
return True
rec_stack.remove(start_id)
return False
Call this in submit() after wiring dependencies, and reject the submission if it returns True.
Complexity
- submit: O(D) where D is the number of direct dependencies (checking each dependency's status and wiring reverse edges)
- get_status: O(1)
- claim_job: O(1) amortized (pops from ready queue)
- report_success: O(D') where D' is the number of direct dependents
- report_failure: O(N) worst case if the entire graph must be marked failed
- Space: O(N + E) for N jobs and E dependency edges
Thread Safety
The single Lock ensures atomic transitions. Critical points:
- claim_job atomically changes READY → RUNNING, preventing duplicate claims
- report_success/failure cannot interleave with other state changes
- Ready queue modifications are protected
For higher concurrency, consider finer-grained locks per job or lock-free queues, though the added complexity is often unnecessary unless throughput demands it.
Common Mistakes
- Forgetting reverse edges makes it expensive to find newly runnable jobs (you'd scan all pending jobs after every completion)
- Not cascading failure states leaves dependent jobs blocked forever
- Allowing a job to be claimed twice causes duplicate execution
- Checking for cycles only on the newly submitted job misses cycles formed by earlier submissions