Build a Distributed Pipeline Execution Engine
System DesignModel answerLast updated
Design a fault-tolerant scheduler that executes dependency graphs across a worker fleet with lease-based dispatch and deployment safety.
You're building the core execution engine for a platform that runs automated build, test, and deployment workflows. Engineers submit jobs as dependency graphs—each node is a task, and edges represent "must run after" relationships. Your system must assign tasks to machines in a worker pool, track progress, recover from crashes, and enforce safety rules when deploying to shared environments.
Your Job
Design the scheduler and execution runtime. Explain how tasks move from submitted to complete, how workers claim and execute them, and how the system stays correct under partial failures.
Functional Scope
Dependency orchestration
Jobs arrive as directed acyclic graphs. A task becomes eligible only after all its dependencies finish successfully. If any dependency fails and cannot be retried, cancel the entire job immediately.
Worker assignment
Workers advertise capabilities—operating system, architecture, attached hardware. Tasks declare requirements. The scheduler matches tasks to compatible workers and grants short-lived execution leases.
Fault tolerance
Workers may crash, hang, or become partitioned. The scheduler must detect stalled tasks, reassign them, and prevent duplicate or conflicting executions. Tasks should be retried with exponential backoff up to a configured limit.
Real-time visibility
Clients query job and task status at any time. State transitions—queued, running, succeeded, failed, cancelled—must be observable and durable.
Deployment guards
Some tasks deploy code to shared target environments (staging, production). The system must serialize or gate concurrent access so two tasks never deploy conflicting changes to the same environment simultaneously.
Scale & Constraints
- 50,000 jobs per day, averaging 10 tasks each → 500,000 tasks daily
- Peak dispatch rate: 50 tasks/second
- Up to 5,000 concurrent workers
- Task duration: 30 seconds to 2 hours
- Multi-tenant: prevent one large job from blocking others
- At-least-once task dispatch; tolerate scheduler restarts without state loss
What to Address
- State model: Schema for jobs, tasks, dependencies, worker leases, and deployment locks; task and job lifecycle states
- Scheduling logic: How the system identifies ready tasks, matches them to workers, and dispatches them safely
- Lease protocol: Worker heartbeats, timeout detection, and reassignment of abandoned tasks
- Deployment safety: Mechanism to prevent concurrent deploys to the same environment and handle ordering or mutual exclusion
- Fairness: Strategy to balance work across tenants when workers are saturated
You may assume artifact storage (logs, binaries) is handled separately. Focus on the control plane.
Hints
Hint 1
Model task readiness with an in-degree counter that decrements transactionally when dependencies complete
Hint 2
Use conditional updates (compare-and-swap on a lease token) to make worker operations idempotent under retries
Hint 3
A separate lock table with fencing tokens can serialize deploys; the token travels to the target and rejects stale operations
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Distributed Pipeline Execution Engine
1. Clarify and Size the Problem
First, translate requirements into concrete load numbers to guide technology choices.
| Dimension | Value |
|---|---|
| Average task rate | 500K/day ≈ 6/sec, 50/sec peak |
| Concurrent executions | ≤5,000 (one per worker) |
| Heartbeat load | 5K workers × 6/min ≈ 500 writes/sec |
| Metadata footprint | ~1 KB/task × 500K/day ≈ 500 MB/day hot state |
Takeaway: Throughput is modest. The hard part is correctness under failures—idempotency, fencing, and preventing lost or duplicate work. A single strongly consistent database (PostgreSQL with replication, CockroachDB, or Spanner) handles this scale comfortably. Route artifacts and logs to object storage to keep the control plane lightweight.
Key clarifications to ask:
- Should deploys to the same environment be strictly FIFO, or is mutual exclusion sufficient?
- Can tasks be deduplicated by content hash (caching)?
- Are there priority tiers or SLAs across tenants?
2. API Surface
Client API (REST/gRPC):
POST /jobs {tenant, repo, commit, dag} → job_id
GET /jobs/{id} → {status, tasks: [{id, name, status, started, ended}]}
POST /jobs/{id}/cancel
Worker protocol (gRPC, long-lived streams):
ClaimTask(worker_id, labels, capacity) → {task_id, lease_token, expires_at} | wait
Heartbeat(task_id, lease_token) → {renewed: true|false, should_cancel}
ReportComplete(task_id, lease_token, outcome, logs) → ack
Workers pull tasks via long-poll. This is simpler than push: the scheduler never targets a dead worker, and backpressure is automatic.
3. Data Model and State Machines
Core tables:
jobs (
id, tenant_id, repo, commit, status, created_at, updated_at, version
)
tasks (
id, job_id, name,
required_labels JSONB, -- {"os":"linux","arch":"arm64"}
deploy_target TEXT, -- NULL or "prod", "staging"
status, -- BLOCKED | READY | RUNNING | SUCCESS | FAILED | CANCELLED
pending_deps INT DEFAULT 0, -- in-degree, decremented on parent success
attempt INT DEFAULT 0,
max_retries INT,
eligible_after TIMESTAMP, -- for exponential backoff
lease_token BIGINT DEFAULT 0, -- CAS field
lease_holder TEXT,
lease_expires_at TIMESTAMP,
version BIGINT -- optimistic lock for updates
)
task_deps (parent_task_id, child_task_id)
deploy_locks (
target PRIMARY KEY, -- "prod", "staging"
held_by_task_id,
fence_token BIGINT, -- monotonic, passed to deploy executor
expires_at TIMESTAMP
)
workers (
id, labels JSONB, last_seen TIMESTAMP, capacity INT
)
Task state machine:
BLOCKED (pending_deps > 0)
↓ (parent completes, pending_deps → 0)
READY
↓ (worker claims, CAS lease_token)
RUNNING
↓ success ↓ retryable failure (attempt++, backoff) ↓ exhausted retries
SUCCESS READY FAILED
↓
(cancel downstream)
Any non-terminal → CANCELLED (user cancels job or upstream fails)
Job status is derived:
RUNNINGif any task is non-terminalSUCCESSif all tasks areSUCCESSFAILEDif any task reachesFAILEDCANCELLEDif explicitly cancelled or a critical task fails
4. Architecture
┌─────────┐ ┌──────────────┐ ┌──────────────┐
│ Clients │─────▶│ API Service │──────▶│ PostgreSQL │ (source of truth)
└─────────┘ └──────────────┘ └───────┬──────┘
│ CDC / polling
┌───────▼────────┐
│ Scheduler │ (stateless, sharded by tenant hash)
│ - ready queues │ (in-memory cache)
└───────┬────────┘
│
┌──────────────────────────────┴───────────────────┐
│ │
┌────────▼────────┐ ┌──────────▼─────────┐
│ Worker (ClaimTask, │ │ Reaper (lease GC) │
│ Heartbeat loop) │ │ every 10s │
└────────┬───────────┘ └────────────────────┘
│
┌───────▼────────┐
│ Object Storage │ (logs, binaries)
└────────────────┘
Readiness and Dependency Resolution
When a job is submitted:
- Validate the DAG for cycles (topological sort).
- Insert all tasks. For each task, set
pending_deps = COUNT(incoming edges). Tasks with zero in-degree start inREADY; others inBLOCKED.
When a task completes successfully, one atomic transaction:
-- Mark task complete (guarded by lease token)
UPDATE tasks SET status='SUCCESS', lease_token=NULL WHERE id=? AND lease_token=?;
-- Decrement children's pending_deps
UPDATE tasks SET pending_deps = pending_deps - 1 WHERE id IN (child IDs);
-- Flip newly unblocked children to READY
UPDATE tasks SET status='READY' WHERE pending_deps=0 AND status='BLOCKED';
This ensures exactly-once unblocking: a scheduler crash mid-transaction rolls back, so no child is half-resolved. Duplicate completions (zombie worker retries) fail the CAS check and are ignored.
Scheduling Loop
The scheduler maintains in-memory ready queues, keyed by (tenant_id, label_signature). These are a cache—rebuilt from the database on failover.
When a worker polls with labels L:
- Find queues where
required_labels ⊆ L(precompute an index: label-set → queue list). - Pick a tenant using the fairness policy (round-robin weighted by queue depth, or deficit round-robin).
- Pop a task
Tand attempt:UPDATE tasks SET status='RUNNING', lease_token=lease_token+1, lease_holder=?, lease_expires_at=NOW()+30s WHERE id=? AND status='READY' AND eligible_after <= NOW(); - If the update succeeds (1 row affected), return the task and new
lease_tokento the worker. If it fails (another scheduler won the race), try the next task.
Why pull? Workers know their own capacity and health. Long-poll mimics push latency. A dead worker simply stops pulling; the scheduler never pushes to a corpse.
5. Lease Protocol and Failure Handling
Lease lifecycle:
- TTL = 30 seconds. Workers heartbeat every 10 seconds.
- Each heartbeat conditionally extends
lease_expires_atonly iflease_tokenmatches. A 2-hour task renews its lease ~240 times.
Reaper (background process): Every 10 seconds:
UPDATE tasks
SET status='READY', attempt=attempt+1, eligible_after=NOW() + backoff(attempt), lease_token=NULL
WHERE status='RUNNING' AND lease_expires_at < NOW() AND attempt < max_retries;
UPDATE tasks SET status='FAILED'
WHERE status='RUNNING' AND lease_expires_at < NOW() AND attempt >= max_retries;
The reaper also releases any deploy_locks held by expired tasks.
Exponential backoff:
eligible_after = now + min(base_delay * 2^attempt, max_delay) + jitter
The scheduler ignores tasks not yet eligible, naturally spacing retries.
Cancellation:
One transaction marks the job CANCELLED and updates all non-terminal tasks to CANCELLED. Workers learn about it in the next heartbeat response (should_cancel=true) and kill the subprocess. New work is never dispatched for cancelled tasks.
Partitioned workers: A network-split worker cannot heartbeat. After 30s, the lease expires and the task is reassigned. When the zombie reconnects, all its writes (heartbeat, completion) fail the token check and are ignored. Idempotency is essential: tasks must tolerate re-execution (content-addressed artifact paths, declarative deploys).
6. Deployment Safety
Tasks with deploy_target = 'prod' must not run concurrently. Use a lock table with fencing tokens:
-- Task attempts to acquire lock
INSERT INTO deploy_locks (target, held_by_task_id, fence_token, expires_at)
VALUES ('prod', ?, 1, NOW() + INTERVAL '30s')
ON CONFLICT (target) DO UPDATE
SET held_by_task_id=?, fence_token=fence_token+1, expires_at=?
WHERE expires_at < NOW();
- A task becomes dispatchable only after acquiring the lock.
- The lock is renewed with each heartbeat and released on completion/failure/cancellation.
- The fence token is passed to the deploy target (e.g., Kubernetes annotation, deploy API header). The target rejects operations with stale tokens, so a zombie deployer cannot overwrite a newer deploy.
FIFO ordering (optional): Maintain a deploy_queue(target, seq, task_id). Tasks wait their turn in strict order (commit N before N+1). When a deploy completes, dequeue the next task and grant the lock. This prevents late deploys from clobbering newer ones.
Semaphores: Extend locks to support max_concurrency > 1 for environments like staging that tolerate parallel deploys of different services.
7. Fairness
When workers are saturated, prevent one tenant from monopolizing the pool:
Deficit round-robin: Track a virtual "deficit" counter per tenant. Each scheduling round:
- Add
weightto each tenant's deficit (weight = priority or 1 for equal fairness). - Serve tenants in deficit order. For each task dispatched, decrement that tenant's deficit by the task's cost (fixed at 1, or proportional to estimated runtime).
- This amortizes fairness over time: a tenant submitting 1,000 tasks won't block one submitting 10.
Alternatively, cap the fraction of workers any single tenant can use (e.g., ≤20% unless the cluster is underutilized).
8. Trade-offs and Extensions
Consistency vs. latency:
This design prioritizes correctness (strong consistency, CAS guards). If you relax to eventual consistency (e.g., DynamoDB with conditional writes), carefully handle read-your-writes for status queries and race windows in dependency resolution.
Caching:
Hash task inputs (code, dependencies, config). If a match exists in a cache table, skip execution and reuse the artifact reference. Invalidate on TTL or explicit purge.
Priority and preemption:
Add a priority field. High-priority tasks jump the ready queue. For preemption, the scheduler can revoke a low-priority lease (cancel via heartbeat) to free a worker.
Observability:
Emit events (task claimed, completed, retried) to a stream (Kafka, Kinesis). Aggregate into dashboards (p50/p99 task duration, retry rate by tenant). Store task logs with correlation IDs for tracing.
Scalability:
Shard the scheduler by tenant hash. Each shard owns a subset of tenants' ready queues. The database itself can scale horizontally (CockroachDB, Spanner). For 10× load (5M tasks/day), the architecture remains the same; add database read replicas and more scheduler replicas.
Common mistakes:
- Forgetting idempotency: duplicate task execution must be safe.
- Using distributed locks without fencing tokens: zombies can corrupt state.
- Rebuilding the ready queue on every poll: cache it and refresh incrementally.
- Ignoring fairness: large jobs can starve small ones in multi-tenant systems.
This design balances simplicity, correctness, and operational clarity—testable, debuggable, and ready to run in production.