Building a DAG Workflow Engine on Kubernetes
System DesignModel answerLast updated
Design a Kubernetes-native system that schedules containerized DAG tasks with dependency ordering, retries, durable state, and multi-tenant isolation.
Context
You are asked to design a service that lets users hand in multi-step computational workflows. Each workflow is a directed acyclic graph (DAG): every node is a containerized batch job, every edge says "this task cannot start until that one has finished successfully." The execution substrate is a Kubernetes cluster.
Walk through the design as you would in an interview: nail down scale, define the user-facing API, pick the storage model, describe how the control plane uses Kubernetes primitives, and then go deep on dependency scheduling, failure recovery, and tenant isolation. Expect follow-up questions about what happens when the orchestrator itself dies mid-run.
What the system must do
- Accept workflows: a caller posts a JSON (or YAML) DAG; nodes carry an image, command, resource requests, and an optional retry/backoff policy; edges encode dependencies.
- Schedule correctly: a node launches only once every upstream node has succeeded; downstream nodes of a failed node never run.
- Handle failures: per-task retry limits with configurable backoff, and the ability to distinguish a user-code failure from an infrastructure failure.
- Persist state: after a control-plane restart, in-flight workflows resume without losing progress or double-launching work.
- Serve observability: users can poll status, follow logs live, and see per-attempt history.
Non-functional expectations
- Thousands of concurrent workflow runs and ~100k live task objects at steady state.
- Hard logical isolation between tenants (namespaces, quotas, RBAC).
- Finished runs remain queryable for weeks.
Deliverables
- The public API surface (submit, query, cancel, stream, logs).
- The architecture: which Kubernetes objects you create, what the controllers watch, and where the source of truth lives.
- How dependency resolution and retry scheduling are implemented.
- A crash-recovery story for the orchestrator, and how you avoid duplicate pod launches.
- Your reasoning on tenant isolation and observability.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Scope and numbers first
I'd spend the first few minutes pinning the workload, because the numbers decide the storage design:
- ~5,000 concurrent workflow runs; average 20 tasks, tail up to ~1,000.
- ~100k live task objects; peak creation rate 100–200 pods/sec.
- Task durations span seconds to hours — so I must not hold anything in memory that a crash could lose.
- Hundreds of tenants, each mapped to a namespace.
Three semantics to confirm with the interviewer: tasks are batch processes (exit code is the signal, not a long-running server); delivery is at-least-once, so tasks must be idempotent; finished runs stay queryable for weeks.
2. API layer
A thin gateway fronts everything — users never touch kubectl. It authenticates, maps the caller to a tenant namespace, validates the DAG, and translates into a custom resource.
POST /v1/tenants/{t}/workflows (Idempotency-Key header, DAG body)
GET /v1/tenants/{t}/workflows/{id} phase + per-task status
GET /v1/tenants/{t}/workflows?phase=Running
GET /v1/tenants/{t}/workflows/{id}/events SSE stream of state transitions
GET /v1/tenants/{t}/workflows/{id}/tasks/{task}/logs?follow=true&attempt=2
POST /v1/tenants/{t}/workflows/{id}:cancel
POST /v1/tenants/{t}/workflows/{id}:retry resume from failed nodes
Validation on submit: unique node names, every dependency exists, and — critically — no cycles. Run Kahn's algorithm in O(V+E); reject with a 422 listing the offending edge. Enforce a max node count and payload size before writing anything.
3. Data model: two stores with different jobs
In-flight state lives in the Kubernetes API. A Workflow CRD holds an immutable spec (the DAG, images, resources, retry policy, activeDeadlineSeconds) and a mutable status with a top-level phase (Pending/Running/Succeeded/Failed/Cancelled) plus a nodes map keyed by task name: {phase, attempt, podName, startedAt, finishedAt, nextRetryAt, exitCode}.
I deliberately do not create one CRD per task by default. With ~20 tasks per workflow that multiplies etcd objects and watch traffic roughly 20×. A separate Task CRD only earns its keep when tasks need independent lifecycles or RBAC.
History lives in Postgres. Tables for workflows (spec, phase, timestamps, tenant) and task_attempts (workflow, task, attempt, phase, pod, start, end, exit code, log URI). Listing and searching never touch etcd.
The tension between the two: etcd caps object size (~1.5 MB) and has limited write throughput, but it is watchable and naturally fits reconciliation. Postgres handles queries and retention but isn't watchable. So: live state in .status, batched status writes (never one write per pod event), offload the nodes map to Postgres for very large DAGs keeping a pointer, and archive terminal workflows to Postgres so an etcd TTL can reclaim them.
4. Architecture
Client → API gateway → kube-apiserver (Workflow CR)
↑ watch
Workflow Controller (leader-elected, stateless)
↓ creates Pods (ownerRef = Workflow)
Archiver → Postgres Fluent Bit → Loki/S3 (logs)
Controller. Built with controller-runtime. Informers on Workflow and on Pods labeled wf=<id>, feeding a rate-limited workqueue. It is level-triggered: every reconcile compares desired state to observed pods and writes the difference.
Pods, not Jobs. I create bare Pods with restartPolicy: Never. A Job gives me its own retry controller, which I'd have to disable (backoffLimit: 0) because retry and backoff are user-configurable here. Bare Pods keep retry logic in one place. I track completion by watching pod phase and exit codes centrally rather than trusting a sidecar to phone home; a sidecar only makes sense if I need artifact upload after the main container exits.
Logs. A node-level agent ships container logs to Loki/S3 keyed by {tenant, workflow, task, attempt}. Live tailing proxies the apiserver log stream; finished pods read from the store. The controller never carries log data.
5. Dependency resolution and retries
The reconcile loop is the heart of the system:
reconcile(wf):
pods = list pods labeled wf=wf.id
update wf.status.nodes from pod phases / exit codes
for task in topological order:
if node failed and now >= nextRetryAt: launch(task, attempt+1)
if node pending and all parents Succeeded and tenant has quota: launch(task, attempt)
if any parent permanently failed: mark node Skipped
recompute wf.phase; write status (optimistic concurrency on resourceVersion)
requeue after the earliest nextRetryAt
Backoff delay is min(base × factor^attempt, max) plus jitter, persisted as nextRetryAt in status so a restart can't reset the clock. I separate failure classes: non-zero exits count against the user's retry budget; evictions, node loss, and node-level OOM kills retry on infrastructure budget without consuming it. That distinction is a common follow-up.
6. Surviving an orchestrator crash
- Leader election via a Lease; a standby promotes in ~15 s. Running pods are untouched while the controller is down — only scheduling of the next wave pauses.
- Stateless controller: on restart it lists all Workflows and Pods and rebuilds state from observed reality.
- Deterministic pod names
{wf}-{task}-{attempt}. If the controller creates a pod and dies before recording it, the retrycreatereturnsAlreadyExistsand the controller adopts the existing pod — no duplicate launches. This is the single most important trick for at-least-once safety. - ownerReferences garbage-collect pods with their workflow; a finalizer archives status and log pointers before deletion.
- Scale-out: shard workflows across controller replicas by hashing workflow ID, each shard with its own Lease.
7. Isolation and observability
One namespace per tenant, RBAC scoped to it, ResourceQuota and LimitRange to bound CPU/memory/pod count, and a dedicated ServiceAccount for task pods with no API permissions. Network policies block cross-namespace traffic.
Observability: status via the API, live logs through the gateway, per-attempt history in Postgres, and controller metrics (reconcile latency, queue depth, launch rate) for operators.
Common mistakes to name: storing DAG state only in memory, one CRD per task, unbounded status writes hammering etcd, Job-level retries fighting user retry policy, and non-deterministic pod names causing duplicate work after a crash.