Building a Production CI/CD System with Custom Job Orchestration
System DesignModel answerLast updated
Design a complete continuous integration and delivery platform for a large monorepo, with emphasis on the job scheduler that coordinates pipeline execution.
You're building a continuous integration and delivery platform for an engineering organization that maintains multiple microservices in a single large repository. Design the complete system architecture and explain your decisions across all layers.
Your design should address:
-
Version control integration — How the system connects to source control, what events trigger pipelines (code pushes, pull requests, releases, scheduled runs), how you handle repository-specific concerns like detecting which services changed in a monorepo, and branch protection requirements.
-
Build execution and artifact storage — How build jobs run (execution environments, isolation), how you ensure builds are reproducible, how build outputs and dependencies are cached, where artifacts are stored, and how long you retain them.
-
Test automation — The different test stages (unit, integration, end-to-end), how tests run in parallel, how you create isolated test environments for pull requests, and your strategy for handling unreliable tests that sometimes fail without code changes.
-
Execution environments — When to use containers versus virtual machines for running jobs, and how you guarantee that builds produce the same output given the same input.
-
Deployment approaches — Different strategies for releasing new versions (all-at-once updates, gradual rollouts, maintaining two versions simultaneously), how you use feature toggles, and how to safely update databases when the schema needs to change.
-
Rollback and monitoring — How you detect that a deployment has problems, how you automatically revert to the previous version, what telemetry you collect, and how incidents are escalated.
-
Security and compliance — How you scan for vulnerabilities and secrets, how you prove what went into each build, how you sign artifacts, how you control what can be deployed, and how you audit actions taken by the system.
-
Job scheduler design (the core system design challenge) — Design the service that orchestrates pipeline execution. This includes how you model dependencies between jobs (directed graphs), how you limit concurrent executions, how you prioritize work across teams, how you retry failures, how you cache results, and how you prevent any single team from monopolizing resources. Specify the data model, the storage systems you'll use, the APIs, and the key algorithms.
-
Scale and isolation — How the platform scales to support many teams, how you prevent one team's workload from affecting another, and how you enforce resource limits.
-
Efficiency and reliability — How you reduce costs (using interruptible compute, reusing cached work), and how you design the platform itself to stay available even when components fail.
-
Metrics and operational readiness — What indicators you track to measure both delivery performance and platform health, and how an on-call engineer would respond to common failures.
Walk through the important trade-offs in your design (speed versus control, single repository versus many repositories, push-based versus pull-based deployments). Describe several failure scenarios and explain how your design handles them.
Hints
Hint 1
Start by establishing assumptions about scale: number of engineers, services, daily pipeline runs, and throughput requirements. These numbers will justify your design choices.
Hint 2
The scheduler is the most complex component. Focus your time there: model the dependency graph, design the state machine for jobs, choose your storage layer, and explain how you ensure exactly-once execution.
Hint 3
For the deployment layer, think through what happens when a release causes errors. How do you detect the problem automatically? How do you roll back without human intervention?
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Production CI/CD Platform Design
This problem is intentionally broad. A strong response prioritizes the scheduler (the actual system design component) while covering the other layers concisely. Allocate roughly 5 minutes to requirements, 8 minutes to the pipeline overview, 25 minutes to scheduler design, and 7 minutes to trade-offs and failure modes.
Requirements and Scale Assumptions
Begin by establishing concrete numbers to ground your design:
- Organization: 1,500 engineers maintaining 120 services in a single repository
- Daily activity: approximately 4,000 pull requests and 25,000 pipeline executions
- Job volume: each pipeline runs about 25 jobs, yielding roughly 600,000 jobs per day (averaging 7 jobs/second, peaking at 70 jobs/second)
- Concurrent capacity: around 2,500 active workers at peak
- Log volume: approximately 800 GB daily at 1 MB per job, retained for 30 days in hot storage
Platform service-level objectives:
- Jobs start within 20 seconds (95th percentile) after becoming ready
- Control plane available 99.9% of the time
- Pull request feedback delivered in under 12 minutes (median)
- Zero duplicate or lost deployments
High-Level Pipeline Architecture
Version Control Integration
Adopt trunk-based development where engineers work on short-lived feature branches that merge into a single main branch. Require code review, designated owner approval, and successful validation before merging. Implement a serialization queue that tests each change on top of the current queue head rather than on the original base, ensuring the main branch stays functional.
Trigger events arrive via webhooks into a message bus. Support triggers from pull requests, pushes to protected branches, tag creation, scheduled execution, and manual invocation.
For monorepo change detection, build a service dependency graph (using build system metadata like Bazel queries or explicit dependency files). When code changes, traverse the graph to identify all affected services rather than relying on simple path matching, which misses transitive dependencies.
Build Execution and Artifacts
Define pipelines as code stored alongside application code, versioned together. Run each job in an isolated, ephemeral environment (container or VM) that is destroyed afterward to prevent state contamination.
Ensure reproducibility through pinned toolchains, base images referenced by cryptographic digest (not tags), locked dependency versions, and network isolation during build steps. Use content-addressed caching: store build outputs and intermediate layers keyed by input hash, so identical inputs retrieve cached results.
Store container images in an OCI-compliant registry and other artifacts (binaries, packages) in a dedicated repository, all keyed by commit hash and content digest.
Retention policy by artifact type:
- Pull request artifacts: 7 days
- Main branch builds: 90 days
- Tagged releases: indefinite retention
- Garbage collection uses reference counting from deployment records
Testing Strategy
Execute tests in stages: unit tests first, then integration tests (with containerized dependencies like databases), finally end-to-end tests in an isolated namespace created for each pull request.
Parallelize tests by sharding based on historical execution time. Use test selection analysis on pull requests to run only affected tests; full suites run on main branch and nightly.
Handle flaky tests by automatically retrying once on failure and marking the result as unstable rather than success. Track per-test failure rates; when a test exceeds the flakiness threshold, automatically quarantine it and file an issue with the owning team. Address root causes: seed random generators, mock time, eliminate shared global state.
Containers versus Virtual Machines
Default to containers for their speed, density, and reproducibility via digest pinning. Use virtual machines (lightweight VMs like Firecracker) for:
- Untrusted code from external contributors
- Jobs requiring privileged operations or nested virtualization
- Platform-specific builds (macOS, Windows) or GPU workloads
- Kernel or driver testing
Deployment Strategies
Implement GitOps: the CI pipeline writes the new image digest to an environment configuration repository, and a reconciliation controller (like Argo CD) applies changes to the cluster.
Use progressive rollout as default: deploy to 1% of traffic, then 10%, 50%, and finally 100%. Gate each stage on service-level metrics (error rate, latency percentiles, resource saturation) compared against the stable baseline. For stateful services requiring atomic cutover, use blue-green: maintain two complete environments and switch traffic instantly. Use rolling updates for internal or low-risk services.
Decouple deployment from feature release using feature flags to enable new behavior gradually.
For database schema changes, use expand-contract pattern:
- Add new column or table (nullable/optional)
- Deploy code that writes to both old and new schema
- Backfill existing data
- Deploy code that reads from new schema
- Remove old schema in a later release
Each migration must be compatible with the previous code version.
Observability and Rollback
The canary analyzer continuously compares metrics (error rate, latency percentiles, saturation) between the new version and the established baseline. On detecting regression, automatically halt the rollout and revert to the previous version by reverting the configuration commit.
Tag all logs with the deployed commit SHA. Inject deployment events as annotations on monitoring dashboards and distributed traces. Route alerts to the service owner with a link to the code changes.
Security and Compliance
Run static analysis, dependency vulnerability scanning, and secret detection in pre-commit hooks and CI. Scan running environments with dynamic analysis against the per-PR deployment.
Generate a software bill of materials for each artifact. Sign all artifacts cryptographically and attach build provenance documenting inputs, builder identity, and process (implementing SLSA level 3). Configure admission policies to reject unsigned images or those without verified provenance.
Use short-lived tokens obtained through OIDC federation rather than long-lived secrets. Log all approvals, deployments, and policy overrides to an append-only audit trail.
Core Component: Job Scheduler Design
Architecture Components
- API Layer (stateless): Receives pipeline submissions, parses the pipeline definition, expands it into a directed acyclic graph, and persists it
- PostgreSQL: Authoritative storage for pipeline runs and job state, partitioned by tenant for isolation
- Dispatcher Service: Multiple replicas, each owning a subset of tenant shards via distributed leader election (using etcd leases or Postgres advisory locks)
- Redis: Stores rate limit counters and concurrency tracking
- Worker Agents: Long-poll the dispatcher for work assignments; pull-based approach allows workers behind NAT and provides natural backpressure
- Object Storage: Durable log and artifact storage
API Design
POST /v1/pipelines/{id}/runs
Body: {commit_sha, trigger_type, parameters, priority}
Returns: {run_id}
GET /v1/runs/{run_id}
Returns: run metadata + job states
POST /v1/runs/{run_id}/cancel
POST /v1/jobs/{job_id}/retry
GET /v1/jobs/{job_id}/logs?offset=<bytes>&follow=<bool>
Returns: streaming logs (chunked transfer or SSE)
POST /v1/workers/claim
Body: {worker_id, labels, capacity}
Returns: job specification + lease_token (60s TTL)
POST /v1/workers/heartbeat
Body: {lease_token}
POST /v1/workers/complete
Body: {lease_token, exit_status, output_digest}
Data Model
CREATE TABLE runs (
run_id UUID PRIMARY KEY,
tenant_id VARCHAR,
pipeline_id VARCHAR,
commit_sha VARCHAR,
trigger_type VARCHAR,
priority INT,
status VARCHAR, -- pending, running, success, failed, cancelled
created_at TIMESTAMP
);
CREATE TABLE jobs (
job_id UUID PRIMARY KEY,
run_id UUID REFERENCES runs,
name VARCHAR,
status VARCHAR, -- waiting, ready, running, success, failed, skipped, cancelled
attempt INT DEFAULT 0,
max_retries INT,
upstream_count INT, -- remaining unsatisfied dependencies
cache_key VARCHAR,
required_labels JSONB,
concurrency_slot VARCHAR,
earliest_start TIMESTAMP,
worker_id VARCHAR,
lease_expires TIMESTAMP
);
CREATE TABLE job_dependencies (
upstream_job_id UUID,
downstream_job_id UUID,
PRIMARY KEY (upstream_job_id, downstream_job_id)
);
CREATE TABLE log_segments (
job_id UUID,
sequence INT,
storage_key VARCHAR,
byte_offset BIGINT,
PRIMARY KEY (job_id, sequence)
);
Dependency Graph Execution
When a pipeline is submitted:
- Validate the graph is acyclic using topological sort
- Set each job's
upstream_countto its number of dependencies - Mark jobs with zero dependencies as
ready
When a job completes successfully:
- In a single database transaction: mark the job complete, decrement
upstream_countfor all downstream jobs, and mark newly-ready jobs (those reaching zero) - Jobs marked
readybecome eligible for scheduling
On job failure:
- Mark all downstream jobs as
skippedunless they have therun_alwaysflag (cleanup tasks) - Optionally retry the failed job based on its retry budget
Scheduling Algorithm
The dispatcher periodically (every 2 seconds) queries for ready jobs:
SELECT * FROM jobs
WHERE status = 'ready'
AND earliest_start <= NOW()
AND tenant_id = $shard
ORDER BY priority DESC, created_at ASC
LIMIT 1000;
For each job:
- Check cache: if
cache_keyexists in cache store with a successful previous result, mark job complete immediately and use cached outputs - Check concurrency limits: if the job specifies a
concurrency_slot, check Redis counter; skip if limit reached - Check rate limits: use token bucket in Redis for tenant and global limits
- Match to worker: find an available worker with matching labels and capacity
- Create lease: atomically update job with worker assignment and expiration (60 seconds); send job spec to worker
- Track lease: if heartbeats stop arriving, expire the lease after TTL and mark the job as
readyagain for retry
Workers pull work by long-polling the claim endpoint. When the dispatcher has no work, it holds the request open until work arrives or timeout (30 seconds), reducing polling overhead.
Retry Strategy
Failed jobs retry automatically up to max_retries. Use exponential backoff: set earliest_start = NOW() + (2^attempt * base_delay). For infrastructure failures (worker crash, network timeout), retry immediately. For deterministic failures (compilation error, failing test), don't retry unless explicitly requested.
Concurrency Control
Some jobs must limit concurrency (database migrations, rate-limited API calls). Assign these jobs a concurrency_slot identifier. Maintain a Redis counter per slot. Before scheduling, increment the counter; decrement on completion. If incrementing would exceed the limit, skip the job in this scheduling round.
Priority and Fairness
Assign priority scores: user-triggered runs (pull requests, manual) get higher priority than automated runs (scheduled, post-merge). Within the same priority, use FIFO.
Track per-tenant job counts and apply weighted fair queuing: tenants with fewer recently scheduled jobs get preference. Combine this with priority: effective_score = priority * fairness_weight.
Caching
Generate a cache key from job inputs: code hash, dependency versions, environment variables, and the job definition itself. Before scheduling, query the cache. If a previous successful execution exists with the same key, mark the job complete and populate outputs from cache. Cache entries expire after 7 days of no use.
High Availability
Run multiple dispatcher replicas. Use leader election per tenant shard: each replica acquires leases for a subset of tenants. If a dispatcher crashes, another takes over its shards within the lease TTL (10 seconds).
PostgreSQL runs in a primary-replica configuration with synchronous replication. On primary failure, promote a replica. Use connection pooling (PgBouncer) to handle dispatcher and API connections.
Redis runs in cluster mode with replication. Treat Redis as a cache, not authoritative state: if Redis fails, scheduling continues but without rate limiting or concurrency enforcement until recovery.
Scalability and Multi-Tenancy
Partition database tables by tenant_id. Each dispatcher replica owns a set of tenant shards, distributing load. As load grows, add dispatcher replicas and rebalance shard assignments.
Horizontally scale worker pools independently: use autoscaling based on ready job queue depth. Workers can be heterogeneous (different CPU/memory/GPU, different labels).
Enforce per-tenant quotas: maximum concurrent jobs, maximum daily job-hours. Track usage in PostgreSQL; reject new runs when quota is exhausted. Use separate quotas for pull requests (higher priority, smaller quota) and scheduled jobs (lower priority, larger quota).
Cost Efficiency
Use spot or preemptible instances for workers, with fallback to on-demand for time-sensitive jobs. Implement aggressive caching: remote build cache, Docker layer cache, and test result cache.
Apply retention policies to reduce storage: delete pull-request artifacts after 7 days, compress old logs, archive infrequently accessed artifacts to cold storage.
Metrics and Operational Readiness
Platform Metrics
- Job throughput (jobs/second)
- Scheduling latency (time from
readytorunning) - Worker utilization (percentage busy)
- Queue depth by priority
- Cache hit rate
- Control-plane error rate and latency
Delivery Metrics
- Deployment frequency
- Lead time (commit to production)
- Change failure rate
- Mean time to restore service
On-Call Playbook
-
Symptom: Jobs stuck in
readystate
Diagnosis: Check dispatcher health, database locks, worker availability
Action: Restart dispatcher, clear stale locks, scale workers -
Symptom: High failure rate on a specific job
Diagnosis: Check recent code changes, infrastructure events
Action: Quarantine the job, roll back recent change, notify owner -
Symptom: Deployment rollout halted
Diagnosis: Check canary metrics for regression
Action: Confirm automatic rollback executed, verify previous version restored, notify owner
Key Trade-offs
Monorepo versus Multiple Repositories
- Monorepo: Atomic cross-service changes, shared tooling, unified versioning. Cost: larger clones, more complex change detection.
- Multiple repos: Independent release cycles, smaller scope. Cost: difficult cross-service refactoring, tooling fragmentation.
Push versus Pull Deployments
- Push (CI deploys directly): Faster, simpler. Cost: requires CI access to production, harder to audit.
- Pull (GitOps): Declarative, auditable, easier rollback. Cost: extra reconciliation delay, additional component.
Velocity versus Control
- Automated canary with metric gates: Fast, continuous deployment. Cost: requires good metrics and baselines.
- Manual approval gates: More control, human judgment. Cost: slower, bottleneck, after-hours toil.
Failure Scenarios
Worker crashes mid-job
The lease expires without heartbeat. Dispatcher marks the job ready again. New worker picks it up. Idempotent jobs handle this naturally; non-idempotent jobs need explicit cleanup or distributed locking.
Database primary failure
Replica is promoted to primary (automated via orchestration like Patroni). Brief unavailability (10-30 seconds). In-progress scheduling rounds fail and retry. No state loss due to synchronous replication.
Dispatcher crashes
Remaining dispatchers acquire orphaned tenant shards via leader election. Workers continue heartbeating and complete in-progress jobs. New jobs for affected shards are delayed by the lease TTL (10 seconds).
Corrupted cache entry
Job using cached output fails. Mark cache entry invalid and retry from scratch. Alert if cache invalidation rate exceeds threshold.
Network partition between dispatcher and workers
Leases expire without heartbeat. Dispatcher reschedules jobs. Workers may still be executing but cannot report completion. Use fencing tokens: workers include lease token when reporting; stale tokens are rejected. Incomplete work is retried.
Canary analyzer false positive
Deployment halts incorrectly due to metric noise. On-call reviews: if metrics are actually healthy, manually approve rollout continuation or adjust sensitivity thresholds. Include variance and confidence intervals in analysis to reduce false positives.
This design balances speed, reliability, and cost while maintaining operational simplicity. The pull-based worker model, PostgreSQL for state, and aggressive caching address the most common bottlenecks. The scheduler's use of graph-based dependencies, priority queuing, and cache-aware execution provides the flexibility large organizations need while maintaining fairness across teams.