Design a Fault-Tolerant Orchestration Engine for ML Pipelines
System DesignModel answerLast updated
Design a multi-tenant ML workflow scheduler that handles versioned DAGs, heterogeneous compute routing, data quality enforcement, and reproducible lineage tracking.
Context
A growing ML platform team runs hundreds of pipelines every day — ingesting raw data, computing features, training models, and promoting artifacts to production. Today those pipelines are glued together with cron jobs and ad-hoc scripts. The team needs a purpose-built orchestration service to replace that patchwork.
You are asked to design that service from scratch. Think of it as an ML-aware workflow engine: something that knows about GPU pools, terabyte-scale datasets, data contracts, and reproducibility — not just task dependencies.
Functional Requirements
- Versioned workflow definitions. Pipelines are defined in code. Each version captures task logic, dependency graph, container images, and environment configuration immutably.
- Reliable task execution. The engine must survive worker crashes. It needs durable state, configurable retry behavior, and a mechanism to detect and recover stalled tasks.
- Heterogeneous compute. Tasks declare their resource needs (CPU, high-memory, GPU). The scheduler routes each task to the appropriate pool.
- Data quality enforcement. Before any dataset becomes visible to downstream consumers, automated checks must pass: schema consistency, null-rate limits, and statistical distribution tests. Publication must be atomic — no consumer should ever observe a partially written or unvalidated dataset.
- Lineage and backfill. Every run records what inputs it consumed and what outputs it produced (by content hash), along with the exact code version and parameters used. Historical re-runs must not reprocess partitions that already have valid results.
- Fair resource sharing. No single team or pipeline should be able to monopolize shared compute pools.
Scale Assumptions
- 500 registered pipelines; ~10,000 DAG runs per day; ~20 tasks per run → roughly 200,000 task executions per day.
- Peak concurrency around 3,000 simultaneously running tasks.
- Dataset artifacts range from 1 GB to 20 TB; the orchestrator never moves data — it tracks URIs and hashes.
- Task dispatch must happen within 5 seconds of all upstream dependencies completing.
What to Cover in Your Answer
- Architecture overview — identify the major components, what each one owns, and how they communicate.
- Task state machine and crash recovery — how transitions are made durable and how the system handles zombie workers without duplicate commits.
- Atomic dataset publication and quality gates — the exact sequence from task output to consumer-visible dataset, including how concurrent writers are handled.
- Fair-share scheduling — how the engine prevents resource starvation across tenants and task types.
- Lineage and reproducible backfills — the data model and lookup strategy for skipping already-valid partitions.
Address trade-offs throughout. Where you make a design choice, briefly explain what you gave up.
Hints
Hint 1
Start by converting the scale numbers into concrete rates — tasks per second, state writes per second, heartbeats per second. Those numbers determine whether a single Postgres instance is viable or whether you need something heavier, and they give you something concrete to defend in the interview.
Hint 2
For crash recovery, the key insight is separating 'duplicate execution' (which you cannot fully prevent across a network partition) from 'duplicate commit' (which you can prevent with a lease epoch and a compare-and-swap on the final state transition). Be explicit about which guarantee you are actually providing.
Hint 3
Atomic dataset publication is essentially a pointer swap. Model it as an alias record with an optimistic-concurrency revision counter. The quality gate runs as a first-class task in the DAG, not as an out-of-band side process — that way it participates in retry, lineage, and observability like any other task.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Scoping and Numbers First
Before drawing boxes, turn the requirements into rates. 10,000 runs/day × 20 tasks = 200,000 task executions per day, or about 2.3 tasks/s on average. Assuming 10–20× bursts at the top of the hour, peak dispatch is around 50 tasks/s. Each task goes through roughly 6 state transitions, giving ~1.2 M state writes/day. Heartbeats from 3,000 concurrent tasks every 10 s add about 300 writes/s on top. A single well-indexed Postgres instance handles this comfortably — throughput is not the constraint; durability and correct concurrent transitions are.
Dataset artifacts range up to 20 TB, but the orchestrator never touches the bytes. It stores URIs and content hashes only. Data lives in object storage (S3, GCS) behind Iceberg or Delta table abstractions.
Dispatch latency of under 5 s rules out pure minute-granularity polling. The scheduler must react to events, with a periodic sweep as a safety net for anything missed.
Architecture Overview
Control plane — owns scheduling logic and metadata:
- API server / DAG compiler. Accepts workflow registrations, validates DAGs for acyclicity via topological sort, and pins container images by digest (never by mutable tag). Returns an immutable
workflow_version_id. - Metadata store. Postgres, the single source of truth for all task states, lease records, dataset versions, and lineage edges.
- Scheduler (stateless, sharded by
run_idhash with leader election per shard). Listens for task-completion events and re-evaluates readiness for downstream tasks. Stateless design means any scheduler replica can take over a shard without replay. - Admission controller. Enforces per-tenant quotas and fair-share weights before a task enters a pool queue.
- Reaper. Periodically scans for tasks whose lease has expired and moves them back into retry.
- Catalog service. Owns dataset versions and the alias → version pointer.
Data plane — where work actually happens:
- Per-pool queues (
cpu-std,highmem,gpu-a100, etc.). At this scale,SELECT … FOR UPDATE SKIP LOCKEDon a Postgres table is a perfectly valid queue. Redis Streams or SQS work too; the choice matters more for operational simplicity than raw throughput. - Workers (Kubernetes pods, Ray clusters, Spark drivers). Workers pull from the queue — natural backpressure, and a dead worker just stops pulling.
- Object storage for all artifact bytes.
Task State Machine and Worker Recovery
States: PENDING → READY → QUEUED → RUNNING → SUCCEEDED, with failure paths leading to RETRY_WAIT → READY or FAILED_FINAL, and terminal states UPSTREAM_FAILED, SKIPPED, and CACHED.
Durable transitions. Every state change is a conditional update:
UPDATE task_run
SET state = 'RUNNING',
lease_epoch = lease_epoch + 1,
lease_owner = :worker_id,
lease_expiry = now() + interval '60 seconds'
WHERE id = :id AND state = 'QUEUED'
RETURNING lease_epoch;
If the row is already claimed (race between two workers), the update matches zero rows and the losing worker discards the task. No application-level locking needed.
Transactional outbox for dispatch. When a parent task completes, the same database transaction that marks it SUCCEEDED also marks eligible children READY and inserts an outbox row. A relay process reads the outbox and publishes to the queue. This means a scheduler crash between "mark ready" and "publish to queue" is harmless — the relay will retry. Duplicate queue messages are fine because the claim is itself a CAS.
Lease fencing. Workers heartbeat every 10 s with a 60 s lease. The reaper finds rows where state = 'RUNNING' AND lease_expiry < now(), increments lease_epoch, and moves the task to RETRY_WAIT with exponential backoff plus jitter: min(base × 2^n, cap).
A zombie worker that comes back after a network partition tries to call complete with its original lease_epoch. The orchestrator rejects mismatched epochs, so the zombie cannot commit its outputs.
Honest about guarantees. This prevents duplicate commits, not duplicate execution — a task may run twice on different workers if the first worker stalls long enough for the lease to expire. Correctness comes from two properties: tasks write outputs to a unique staging path keyed by (task_run_id, attempt), and only the attempt holding the current epoch can register those outputs. Exactly-once execution across a network partition is not achievable; say so in the interview rather than pretending otherwise.
Retry policy should distinguish preemption and transient I/O errors (retryable, should not consume retry budget) from user exceptions and validation failures (non-retryable). Exit codes or error class tags on the exception carry this signal.
Quality Gates and Atomic Dataset Publication
Publication follows four steps, all modeled as first-class tasks in the DAG:
- Write to staging. The producing task writes output to an immutable path (
s3://…/staging/{task_run_id}/{attempt}/) and registers adataset_versionrow withstate = STAGEDand a content hash. - Gate task runs. A lightweight gate task (CPU pool, no GPU needed) checks: schema hash against the registered contract, null rates per column, row-count delta against a trailing baseline, and distribution drift (PSI or KS on sampled data). For 20 TB tables, compute metrics on a statistical sample plus partition-level aggregates — full scans are too slow to be routine.
- Promote on pass. The gate marks the version
VALIDATED, then swaps the alias with optimistic concurrency:
UPDATE dataset_alias
SET version_id = :new_version, revision = revision + 1
WHERE dataset_id = :d AND alias = 'prod' AND revision = :expected_revision;
If this update matches zero rows, another writer raced ahead. The loser re-reads the current alias and promotes only if its partition watermark is strictly newer — preventing an old backfill from overwriting a fresher daily run.
- Consumers pin at read time. A consumer resolves
prodto a concrete URI once when its task starts and uses that URI throughout. A concurrent alias swap never changes data mid-read.
On gate failure: mark the version REJECTED, set downstream tasks to UPSTREAM_FAILED, alert the owning team, and retain the rejected version for debugging. Do not delete it immediately.
Fair-Share Scheduling
Model each compute pool as a resource with a total capacity. Each tenant gets a guaranteed share (e.g., 20% of the GPU pool) and a burst ceiling (e.g., 60%). A weighted fair-share algorithm sorts the ready queue by (tasks_running_for_tenant / tenant_weight) — the tenant with the lowest ratio gets the next slot.
Priority lanes (high / normal / low) operate within each tenant's allocation. A high-priority task can jump ahead of normal-priority tasks from the same tenant, but cannot consume another tenant's guaranteed share. This prevents a mis-configured pipeline from starving neighboring teams.
Lineage and Reproducible Backfills
The lineage data model is straightforward:
task_runcarriesworkflow_version_id,params_hash, andcache_key = hash(task_def_id + input_content_hashes + cache_version).lineage_edge(task_run_id, dataset_version_id, direction IN|OUT)records every dataset consumed and produced.
Before dispatching a task, the scheduler checks for an existing task_run with a matching cache_key in SUCCEEDED state. If found, the task is marked CACHED and its outputs are reused — no recomputation. Changing any input dataset, any parameter, or bumping the task's cache_version invalidates the cache naturally.
For backfills, launch_backfill(workflow_version_id, partitions[], params) launches one run per partition. Partitions whose cache keys already resolve to a valid SUCCEEDED task run are skipped at admission time, not after paying the scheduling cost.
Common Mistakes to Avoid
- Scheduler with local state. If the scheduler holds readiness state in memory, a crash loses it. Keep all state in Postgres and make the scheduler purely reactive.
- Mutable image tags. Pinning to
latestmeans two runs of the sameworkflow_version_idcan execute different code. Always resolve to a digest at registration time. - Quality gate as a side process. Running validation outside the DAG means it has no retry policy, no lineage record, and no visibility in the run graph. Model it as a task.
- Alias swap without optimistic concurrency. A plain
UPDATE … SET version_id = :newwith no revision check lets a slow backfill silently overwrite a newer production dataset.