Build a Multi-Step Job Execution Engine with Dependency Management
System DesignModel answerLast updated
Design a system that executes jobs composed of dependent tasks, managing state, handling failures, and coordinating parallel work across distributed workers.
You need to design an execution engine for multi-step jobs. Users create job templates that define multiple tasks and their dependencies, then launch executions of those templates. The system must run each task in dependency order, maintain execution state, recover from failures, and provide visibility into progress.
Your design should address:
- Data modeling: How you represent job templates, execution instances, and individual task states
- Execution coordination: How tasks become ready to run, get assigned to workers, and report completion
- Reliability: Handling worker crashes, task failures, retries, and ensuring progress
- Scalability: Supporting many concurrent job executions and distributing work efficiently
- Multi-tenancy: Preventing one team's workload from starving another's
Before designing, clarify:
- What types of tasks does the system execute? (API calls, containers, scripts, etc.)
- How are executions triggered? (Manual API requests, schedules, external events)
- Expected scale: number of job templates, concurrent executions, tasks per job, and task duration
- Dependency patterns: strictly sequential, parallel fan-out/fan-in, or arbitrary DAGs?
- Failure handling requirements: automatic retries, timeouts, manual intervention, rollback logic
- Multi-tenancy needs: isolation level, priority guarantees, resource quotas
Hints
Hint 1
Model job executions and tasks as separate entities with explicit state transitions
Hint 2
Use a durable queue or database to coordinate which tasks are ready to execute
Hint 3
Design for at-least-once execution semantics and make task implementations idempotent
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Requirements Clarification
First, I'd establish scope with the interviewer:
Functional requirements:
- Store job templates with task definitions and dependency DAGs
- Launch job executions and track individual task states
- Execute tasks in dependency order, supporting parallel execution where possible
- Provide APIs to query execution status and task results
- Handle task retries and timeout enforcement
Scale assumptions:
- 10,000 active job templates across all tenants
- 1,000 concurrent job executions, each with 5-50 tasks
- Task duration: 10 seconds to 10 minutes typical, up to 1 hour outliers
- 10-100 workers processing tasks
- Multi-tenant with 50-100 distinct teams
Non-functional requirements:
- Durability: no lost executions or incorrect state after crashes
- At-least-once execution with idempotency
- Fairness: prevent one tenant from monopolizing workers
- Observability: detailed logs and metrics per execution
High-Level Architecture
Components:
- API Service: REST endpoints for creating job templates, starting executions, querying status
- Orchestrator: Evaluates task dependencies, transitions task states, enqueues ready tasks
- Task Queue: Durable queue of tasks ready for execution (e.g., Redis, SQS, or database-backed)
- Workers: Pull tasks from queue, execute them, report results
- State Store: Persistent database (PostgreSQL, MySQL) storing job templates, executions, and task states
- Metadata Store: Time-series database for metrics and execution logs
Data Model
JobTemplate:
id, name, tenant_id, version, created_at
tasks: [{ task_id, config, dependencies: [task_ids] }]
Version job templates so modifications don't affect in-flight executions.
JobExecution:
id, template_id, template_version, status (pending/running/completed/failed),
started_at, completed_at, triggered_by
TaskExecution:
id, job_execution_id, task_id, status (pending/ready/running/succeeded/failed/retrying),
attempt_count, max_retries, timeout_seconds, worker_id,
started_at, completed_at, result_data, error_message
State machine for TaskExecution:
- pending → ready (when dependencies complete)
- ready → running (worker claims it)
- running → succeeded | failed | retrying
- retrying → ready (after backoff delay)
Execution Flow
1. Starting an execution:
- API creates JobExecution record and TaskExecution records for all tasks in pending state
- Orchestrator evaluates: tasks with no dependencies transition to ready and are enqueued
2. Task scheduling:
- Orchestrator runs periodically (every 1-5 seconds) or is triggered by task completions
- Checks for ready tasks (pending tasks whose dependencies all succeeded)
- Enqueues ready tasks to the task queue with tenant_id and priority metadata
3. Task execution:
- Worker polls queue, claims a task (updates status to running, sets worker_id, started_at)
- Worker executes task (call API, run container, invoke script)
- Worker reports result: updates TaskExecution to succeeded or failed
- If task times out or worker crashes, orchestrator detects stale running tasks and re-enqueues them
4. Completion:
- When all tasks reach terminal states, orchestrator marks JobExecution as completed or failed
Reliability Mechanisms
Durable state:
- All state transitions persisted to database before being visible to other components
- Task queue is durable (persisted in Redis with AOF, or use database as queue)
At-least-once with idempotency:
- Tasks may execute multiple times due to retries or worker crashes
- Task implementations must be idempotent (use unique execution_id as idempotency key)
- Workers include execution_id in all external calls
Retries and timeouts:
- TaskExecution has max_retries (e.g., 3) and timeout_seconds (e.g., 600)
- On failure, if attempt_count < max_retries, transition to retrying with exponential backoff
- Orchestrator detects tasks running beyond timeout and re-enqueues them
Heartbeats:
- Workers update heartbeat_at timestamp every 30 seconds while executing
- Orchestrator detects stale running tasks (no heartbeat for 2 minutes) and reassigns them
Crash recovery:
- On orchestrator restart, scan for jobs in running state and resume coordination
- On worker crash, orchestrator detects via missing heartbeats and re-enqueues tasks
Scaling and Fairness
Horizontal scaling:
- API service: stateless, scale horizontally behind load balancer
- Workers: stateless consumers, add more workers to increase throughput
- Orchestrator: can run multiple instances with leader election (using etcd or database locks) or partition by job_execution_id
Queue-based load distribution:
- Task queue naturally distributes work across workers
- Use priority queues to handle urgent tasks first
Tenant isolation:
- Tag tasks with tenant_id in queue
- Workers pull tasks round-robin across tenants or use weighted fair queueing
- Implement per-tenant rate limits (e.g., max 100 concurrent tasks per tenant)
- Use separate worker pools per tenant for strong isolation if needed
Database optimization:
- Index on (job_execution_id, status) for orchestrator queries
- Index on (status, started_at) for timeout detection
- Partition TaskExecution by tenant_id or time for large scale
Observability
Metrics:
- Task execution latency (p50, p95, p99) per task type and tenant
- Task success/failure rates
- Queue depth and worker utilization
- Per-tenant execution counts and resource usage
Logging:
- Structured logs for every state transition with execution_id and task_id
- Capture stdout/stderr from task execution
- Store in centralized logging system (Elasticsearch, CloudWatch)
Tracing:
- Distributed tracing across API → orchestrator → worker → external services
- Correlate all operations with job_execution_id
Trade-offs and Extensions
Database vs. message queue:
- Database as queue: simpler, ACID guarantees, but slower at high throughput
- Dedicated queue (RabbitMQ, SQS): higher throughput, but need separate state store
Orchestrator design:
- Centralized orchestrator: simpler, but single point of coordination
- Decentralized (saga pattern): each task execution decides its next task, scales better but harder to reason about
Advanced features:
- Dynamic DAGs: tasks that determine next steps at runtime
- Conditional branching: run tasks only if conditions met
- Human-in-the-loop: pause for manual approval before continuing
- Compensation/rollback: define cleanup tasks for partial failures
- Fan-out limits: cap parallelism to avoid overwhelming downstream services
This design provides a solid foundation for a production-grade workflow orchestration system, balancing simplicity with the reliability and scale requirements of a multi-tenant environment.