Build Pipeline Engine: DAG Scheduling and Log Streaming
System DesignModel answerLast updated
Design a CI backend that ingests code events, executes dependency-ordered job graphs on worker fleets, and streams live build logs to developers.
Background
Your team is building the core backend for an enterprise build automation platform. Engineers push code, the platform runs a sequence of build, test, and deploy steps, and developers watch output appear in their browser in near real time. You are responsible for the server-side design.
What You Need to Support
Functional Requirements
- Event ingestion and deduplication: Receive code change notifications from version control systems via webhooks, acknowledge them quickly, and avoid processing the same event twice. Automatically cancel in-progress builds that have been superseded by a newer commit on the same branch.
- Dependency-aware execution: Each pipeline is a Directed Acyclic Graph (DAG) of jobs. A job should only be dispatched after all of its upstream dependencies have succeeded.
- Worker dispatch with leases: Assign jobs to worker nodes (VMs or containers). Use a lease and heartbeat mechanism so that if a worker silently dies, its job is detected and retried by another worker.
- Live log streaming and archival: Workers emit stdout/stderr continuously. Active browser sessions should see new output with under one second of latency. Once a job finishes, its complete log must be durably stored.
- Fair resource allocation: No single large team or runaway pipeline should starve other tenants of worker capacity.
Non-Functional Requirements
- Job dispatch latency under 5 seconds when workers are available.
- Log delivery latency from worker emit to browser under 1 second.
- Horizontal scalability for both the scheduling layer and the log delivery layer.
- At-least-once job execution with exactly-once state transitions.
Scale to Design For
| Dimension | Number |
|---|---|
| Pipeline runs per day | 50,000 |
| Jobs per pipeline (average) | 10 |
| Concurrently running jobs at peak | 10,000 |
| Peak aggregate log ingest rate | 200 MB/s |
| Average log size per build | 5 MB over ~10 minutes |
| Hot log retention | 7 days |
| Cold archive retention | 90 days |
What Is Expected
Cover each of the following areas. You do not need to go equally deep on all of them, but you should demonstrate judgment about which trade-offs matter most.
- Ingestion and pipeline creation: How webhooks are received, deduplicated, and turned into a DAG of jobs in your data store.
- Scheduling and lease management: How jobs move through states, how workers acquire and renew leases, and how stranded jobs are recovered safely.
- Log streaming pipeline: The full path from worker process to browser, including how you handle the transition from live streaming to durable archival.
- Isolation and fairness: How you prevent one tenant from monopolizing the worker fleet.
Hints
Hint 1
Start by separating the control plane (low QPS, correctness-critical) from the log data plane (high throughput, slightly loss-tolerant until archived). The two paths have very different reliability and latency contracts, so they warrant different technology choices.
Hint 2
For exactly-once state transitions with at-least-once delivery, a compare-and-swap update on a versioned row is your primitive. Combine it with a transactional outbox so that the state change and the downstream event are always published together or not at all.
Hint 3
For log streaming, think about three distinct concerns separately: transport from worker to your backend (batched, sequenced), fan-out to active browser sessions (low latency, many consumers), and durable archival (high durability, cost-efficient). A single technology rarely handles all three well.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Size the System First
Good numbers anchor every design decision.
| Quantity | Estimate |
|---|---|
| Pipeline rate | 50k/day ≈ 0.6/s average; ~6/s at 10x peak |
| Job dispatches | ~10 jobs/pipeline → ~60/s at peak |
| Heartbeats | 10k concurrent jobs × 1 heartbeat/10s = 1,000/s |
| Log ingest | 200 MB/s peak; ~20 KB/s per job on average |
| Hot log storage | 50k builds × 5 MB × 7 days ≈ 1.75 TB |
| Cold archive | ~10x compression → ~2.3 TB over 90 days |
The control plane is low-QPS but must be strongly consistent. The log path is high-throughput but tolerates brief gaps during transit as long as archival is complete. Treat them as separate subsystems.
2. API Surface
External (REST)
POST /webhooks/{provider}— signature-verified, returns 202 immediately.GET /pipelines/{id}— returns DAG with per-job states.POST /pipelines/{id}/cancel,POST /jobs/{id}/retry.WS /jobs/{id}/logs?offset=N— live log stream, resumable from byte offset.
Worker-facing (gRPC)
Lease(pool, labels)→{job_id, lease_id, fencing_token, ttl}Heartbeat(lease_id, fencing_token)→{ok | cancel | lease_lost}Complete(lease_id, fencing_token, result)AppendLogs(job_id, seq, chunk)
3. Data Model
Use a sharded relational database (Postgres or MySQL), sharded by pipeline_id.
pipeline: id, repo, branch, commit_sha, tenant_id, state, dedup_key, created_at, version
job: id, pipeline_id, name, state (PENDING|READY|QUEUED|RUNNING|SUCCESS|FAILED|CANCELED|SKIPPED), attempt, pending_parents, lease_id, lease_expires_at, fencing_token, version
job_edge: (pipeline_id, parent_job_id, child_job_id)
log_segment: (job_id, seq_start, seq_end, object_key, size_bytes) — written by the archiver as S3 segments complete.
outbox: (id, event_type, payload, published_at) — written transactionally alongside state changes, relayed to Kafka by a tail worker.
Every state transition is a conditional update:
UPDATE job
SET state = 'RUNNING', lease_id = ?, fencing_token = ?, lease_expires_at = now() + interval '30s', version = version + 1
WHERE id = ? AND state = 'QUEUED' AND version = ?;
If the row count is zero, the transition was lost to a race and the caller retries. This compare-and-swap is what gives exactly-once state transitions even with at-least-once delivery.
4. Architecture Overview
VCS webhook
│
▼
Ingestion Gateway (verify HMAC, write to Kafka vcs-events, ack 202)
│
▼
Pipeline Service (consume vcs-events, dedup, expand DAG, write DB + outbox)
│
▼
State DB ──outbox relay──> Kafka (job-ready events)
│
▼
Scheduler (fair-share, per-pool queues)
│ Lease / Heartbeat / Complete (gRPC)
▼
Worker Agents (containers or VMs)
│ │
│ AppendLogs │ Complete
▼ ▼
Kafka (logs, State DB (CAS update)
keyed by job_id)
│
├──> Live Fan-out Layer (WebSocket servers + Redis ring buffer)
│ ▼
│ Browser clients
│
└──> Archiver ──> S3 segments ──> compacted final object
5. Ingestion and DAG Execution
Webhook ingestion. The gateway verifies the provider HMAC, writes the raw event to Kafka, and returns 202. It deduplicates on the provider's delivery ID using Redis SET NX EX 86400 before enqueuing. This prevents processing the same push event twice if the provider retries.
Add a reconciliation poller that periodically diffs branch tips against the last-seen SHA for each repo. This catches webhooks silently dropped by the VCS provider.
Superseded-build cancellation. The dedup_key is (repo, branch, pipeline_definition_id). When a new pipeline is created for a branch, the service sets any older non-terminal pipelines for the same key to CANCELING. The scheduler propagates cancellation to RUNNING jobs via the heartbeat response. Protected branches (e.g., main) are configurable to retain every build.
DAG fan-out. On pipeline creation, jobs are inserted with pending_parents set to their in-degree. Root jobs (in-degree 0) start in READY. When a job transitions to SUCCESS, one transaction:
- Decrements
pending_parentson each child. - Sets any child whose count hits zero to READY.
- Writes the outbox events.
Because this lives inside the same CAS transaction as the parent's SUCCESS, it happens exactly once. If the parent's CAS fails due to a concurrent retry, the decrement does not happen, and the retry will redo it.
6. Scheduler and Lease Management
Queues. READY jobs are enqueued into per-(pool, tenant) logical queues. These can be Postgres rows selected with FOR UPDATE SKIP LOCKED or Redis sorted sets. The scheduler is stateless and horizontally partitioned by pool.
Dispatch. Workers long-poll Lease(). The scheduler picks a tenant via fair-share (see Section 8), pops a job, and does the QUEUED→RUNNING CAS. The worker receives the job within a few milliseconds, well inside the 5-second target.
Heartbeats. Each worker heartbeats every 10 seconds, extending lease_expires_at. The response carries control signals (cancel, lease_lost). If the worker crashes, heartbeats stop and the lease naturally expires.
Reaper. A background process scans for state = 'RUNNING' AND lease_expires_at < now(). For each expired row it does a CAS: increment attempt, clear the lease, and return to QUEUED. After a configurable maximum attempts, the job goes to FAILED with reason infra_timeout. Retries are safe because:
- Build steps are hermetic; artifact keys include the attempt number.
- Any
Complete()carrying a stale fencing token is rejected. - Steps with side effects (deploys) are flagged
no_auto_retry.
7. Live Log Pipeline
Worker side. The agent reads from the process stdout/stderr via a pty or pipe. It batches output every 200 ms or 64 KB, whichever comes first, assigns a monotonically increasing sequence number, and calls AppendLogs. A small local disk buffer (ring file of ~50 MB) survives brief network interruptions.
Transport. The log ingest service produces to a Kafka topic build-logs, partitioned by job_id. Per-job ordering is preserved. 200 MB/s across 100 partitions at RF=3 is well within typical Kafka capacity. Kafka retention here is short (24 hours); it is a transport, not the archive.
Live fan-out. WebSocket gateway nodes consume Kafka and maintain a ~1 MB per-job ring buffer in Redis for the tail of each active job. When a browser connects with WS /jobs/{id}/logs?offset=N, it:
- Reads from the Redis tail buffer (or from completed S3 segments if the offset is far behind).
- Switches to live push once caught up.
Jobs are pinned to WebSocket nodes via consistent hashing on job_id, or via Redis pub/sub channels job:{id}. End-to-end latency is the 200 ms batch window plus ~50 ms Kafka propagation, comfortably under 1 second. No fan-out work happens for jobs with zero subscribers.
Archival. A separate Kafka consumer group writes segments to S3 as they fill (~5–10 MB or 60 seconds). Each completed segment is recorded in log_segment. On job completion, the archiver flushes the final partial segment and writes a manifest object. The hot S3 tier (7 days) uses standard storage class; after 7 days a lifecycle rule transitions objects to cold storage (Glacier or equivalent) for the remaining 83 days.
8. Fairness and Isolation
Fair-share scheduling. Each tenant has a weight (proportional to their tier or seat count). The scheduler tracks running job counts per tenant. When choosing the next job to dispatch, it picks the tenant with the largest deficit between their entitlement and their current usage. This is weighted fair queuing at the tenant level, not the job level.
Hard caps. A tenant quota table enforces a ceiling on concurrently running jobs regardless of fair-share. Jobs beyond the cap stay in READY but are not dispatched until the tenant drops below their limit.
Worker isolation. Each job runs in a fresh container or ephemeral VM. Resource limits (CPU, memory, disk) are set at launch via cgroup constraints or VM sizing. Network egress is restricted to a job-specific namespace to prevent cross-tenant data leakage.
Common Mistakes to Avoid
- Skipping the fencing token. Without it, a slow worker that recovers after a lease expiry can complete a job that has already been reassigned and completed by another worker, corrupting state.
- Using Kafka as the log archive. Kafka is expensive for long retention and not designed for random-offset reads. Write to object storage early.
- Single fan-out service. If one service both consumes Kafka and pushes to browsers, slow consumers back-pressure ingestion. Keep the Kafka consumer and the WebSocket push path decoupled via the Redis buffer.
- No reconciliation poller. Relying purely on webhooks means any dropped event leaves a commit never built. The periodic poller is cheap insurance.
- Cascading DAG failure without SKIPPED state. If a parent fails and children are left in READY, they will be dispatched unnecessarily. Mark descendants SKIPPED immediately on parent failure, except for jobs explicitly marked
always_run.