Skip to content

Design a CI/CD System

A system design interview walkthrough for a CI/CD system, covering webhook triggers, job graphs, queues, worker pools, caching and fair scheduling.

Intermediate24 minUpdated 2 December 2026

Before this: Message Queues, Back-of-the-envelope Estimations

"Design a CI/CD system" is a question about a work queue with an expensive, untrusted payload. Triggering a pipeline is cheap: a webhook arrives and a row is written. Running it costs real machines and minutes, and the code it runs was written by someone else.

The interviewer is checking whether you notice that the interesting load is not requests per second. It is machine-seconds. A few dozen new jobs a second sounds trivial until each one holds a worker for four minutes. They also want to see you handle the failure that defines this domain: a worker dies in the middle of a build, and the system must neither lose the job nor run it twice with side effects.

If you know the message queue lesson, the skeleton will feel familiar. The new parts are the dependency graph between jobs, fair sharing between teams, and isolation.

Clarify the requirements

Functional requirements:

  1. A push or pull request triggers a pipeline defined in a file in the repository.
  2. A pipeline is a graph of jobs: some run in parallel, some wait for others (build, then test, then deploy).
  3. Each job runs a list of commands in an isolated environment on a worker.
  4. Users see live logs and the final status of every job.
  5. Jobs can produce artifacts (binaries, test reports) and reuse caches (dependencies).
  6. Users can cancel a run, and a newer push cancels the older run on the same branch.
  7. Deploy jobs can read secrets.

Out of scope, said aloud: the source code hosting itself, the deploy targets (we trigger them), and a pipeline authoring UI.

Non-functional requirements:

  • Start fast: a job should begin within about 30 seconds of being ready, or developers stop trusting the tool.
  • No lost jobs. A crashed worker must not strand a job, and a retry must be safe.
  • Fairness. One team launching 5,000 jobs must not block everyone else.
  • Isolation. A job from a forked pull request is untrusted code. It must not read secrets or touch another job.
  • Logs are durable and stream with a delay of a second or two.

Estimate the scale

Assume 20,000 engineers, each triggering 5 pipeline runs a day, and a run averaging 8 jobs. That is 40 jobs per engineer per day. A job averages 4 minutes (240 s) and writes 2 MB of logs.

Job arrivals: 20,000 × 40 = 800,000 jobs a day ÷ 86,400 s ≈ 9.3 jobs per second, and about 28 per second at the 3× peak. Pipelines are submitted during working hours, so the peak is real.

Compute: 800,000 jobs × 240 s = 192 million machine-seconds a day. ÷ 86,400 = about 2,200 workers busy on average, and roughly 6,700 at the peak. This is the number that costs money.

Logs: 800,000 × 2 MB = 1.6 TB a day. Kept for 90 days, about 146 TB (0.25 of a year × 365 days × 1.6 TB).

Artifacts: if one job in five uploads a 100 MB artifact, that is 160,000 × 100 MB = 16 TB a day, mostly dead within 30 days, so a lifecycle rule matters.

Status reads: 20 checks per engineer a day is 400,000 ÷ 86,400 ≈ 4.6 per second, plus log streaming for the few jobs people are watching.

"The control plane is tiny: 9 jobs a second needs one small database and one queue. The data plane is the system: thousands of workers, terabytes of logs. Design the scheduler for fairness and failure, not for request throughput, and design workers to be cheap to start and throw away."

Check the arithmetic with the capacity estimator, which reproduces the log storage.

API and data model

POST /v1/webhooks/git                  { repo, sha, branch, event }      -> 202
GET  /v1/runs/{runId}                                                    -> { status, jobs[] }
POST /v1/runs/{runId}/cancel
GET  /v1/jobs/{jobId}/logs?from=<offset>                                 -> chunks
POST /v1/workers/lease        { workerId, labels[] }                     -> job | 204
POST /v1/jobs/{jobId}/heartbeat   { leaseToken }
POST /v1/jobs/{jobId}/finish      { leaseToken, status, artifacts[] }
pipeline_run  (run_id PK, repo, sha, branch, status, created_at, dedupe_key UNIQUE)
job           (job_id PK, run_id, name, needs[], status, attempt, lease_owner, lease_expires_at)
log_chunk     (job_id, seq) -> bytes      // object storage, appended in chunks

The non-obvious choice is the lease. A worker does not own a job; it holds a lease with an expiry and renews it with heartbeats. If the lease lapses, the job is available again.

High-level design

We simulate the heart of it: a webhook gateway, the pipeline service that creates jobs, the job queue, a worker pool and the artifact store.

Git webhooks pass a gateway to a trigger service that queues jobs, and a worker pool runs them and stores artifacts in object storage.git webhooksgatewaypipeline apijob queuebuild workersartifact store
Git webhooks pass a gateway to a trigger service that queues jobs, and a worker pool runs them and stores artifacts in object storage.
  • The pipeline service turns a webhook into a run and enqueues the jobs that are ready.
  • Workers take one job at a time from the queue and upload artifacts to object storage.
Describe this diagram

Components

  • git webhooks (Client)
  • gateway (API gateway)
  • pipeline api (Service)
  • job queue (SQS queue)
  • build workers (Service)
  • artifact store (Object storage (S3))

Connections

  • git webhooks sends to gateway
  • gateway sends to pipeline api
  • pipeline api sends to job queue
  • job queue sends to build workers
  • build workers sends to artifact store

Run it, then try cutting the consumers or raising the load, and watch the queue depth and age: that backlog is the "waiting for a runner" message every developer knows.

The write path: a webhook is verified (signature check), deduplicated by (repo, sha, event) and turned into a run. The service parses the pipeline file, stores the job graph and enqueues only the jobs with no unmet dependencies.

The read path: status is a lookup by run id. Logs stream from chunks that workers append to object storage, with the live tail held in a small cache.

The interesting problem: getting jobs onto workers

How a job travels from "ready" to "running on a machine" decides latency, fairness and recovery. Three designs:

Approach A: a scheduler pushes jobs to workers

A central scheduler tracks every worker's state and sends each job to a chosen one.

Good: it can make smart placement choices (a warm cache, a matching machine type).

Bad: it must know which workers are alive and idle, so it holds a lot of state. When it fails, scheduling stops. A worker that dies after receiving a job leaves it stuck until someone notices.

Approach B: workers pull from a queue

Workers ask for work ("lease a job with label linux-large"). The queue hands out one job per request.

Good: the scheduler holds no worker list. Adding capacity means starting more workers. A dead worker simply stops pulling.

Bad: a plain FIFO queue is unfair: one team's 5,000 jobs sit ahead of everyone else's.

Approach C: pull with leases, per-team fair queues and autoscaling

Keep the pull model and fix its weaknesses:

  • Leases. A leased job is invisible to others for 60 seconds, extended by heartbeats. A missed heartbeat returns it to the queue, with attempt + 1. This is the same visibility timeout idea as in a message queue.
  • Fair queues. One logical queue per team (or per repo), and the dispatcher serves them round-robin, weighted by plan. A team with 5,000 jobs gets its share and then waits; others are not delayed.
  • Autoscaling on queue age. Scale worker count on the age of the oldest waiting job, not on CPU. Start workers from warm images so a new one takes seconds, and discard each worker after one job so state never leaks between jobs.
Conceptual diagramlease 60sheartbeatfinishunlocksRun createdReady jobsTeam A queueTeam B queueFair dispatcherEphemeral workerJob status
Diagram, as text
  • Run created leads to Ready jobs
  • Ready jobs leads to Team A queue
  • Ready jobs leads to Team B queue
  • Team A queue leads to Fair dispatcher
  • Team B queue leads to Fair dispatcher
  • Fair dispatcher leads to Ephemeral worker (lease 60s)
  • Ephemeral worker leads to Fair dispatcher (heartbeat)
  • Ephemeral worker leads to Job status (finish)
  • Job status leads to Ready jobs (unlocks)

This is the answer to aim for: pull for resilience, fair queues for fairness, and autoscaling on wait time for cost. Compare the general scheduler design in design a job scheduler.

The second decision: the pipeline graph and its state machine

A run is a directed acyclic graph. Each job has needs: the jobs that must succeed first. Model every job as a small state machine: pending → ready → leased → running → succeeded | failed | canceled, with retrying after a lost lease.

The scheduler's core loop is event-driven. When a job finishes, it checks the jobs that depend on it, and any whose needs are all satisfied move to ready and are enqueued. A failure marks its dependents skipped unless they say when: always. Store the state in a database with transactions, because "mark succeeded and enqueue successors" must happen together; otherwise a crash between the two strands the run. Write the successor jobs through a transactional outbox so the queue write is not lost.

Cancelation is a flag on the run. The dispatcher stops handing out its ready jobs, and running workers see the flag on their next heartbeat and stop. A new push to the same branch sets that flag on the previous run, which is how you save machines.

Caching is a second decision inside this one. Dependency caches are keyed by a hash of the lockfile (key = hash(package-lock.json)), stored in object storage and restored at job start. A cache hit can cut minutes from a build. Never let a job from an untrusted fork write to a cache that trusted branches read, or it can poison them.

Bottlenecks and failures

A worker dies mid-build. Its heartbeat stops, the lease expires, and the job returns to the queue as attempt 2. The partial logs are kept, marked with the attempt number. Cap attempts at three and fail the job with "infrastructure error", which is different from "tests failed", so developers do not debug their code for an outage.

Thundering herd on the hour. Scheduled nightly pipelines and a Monday-morning rush spike the queue. Autoscale on queue age, and keep a warm pool of idle workers sized to a few minutes of peak arrival. The fair queues stop one team from consuming the pool.

Log volume. 1.6 TB a day is too much to write through the database. Workers stream log chunks to object storage and publish a small "new chunk" event; the UI tails the latest chunks. Mask known secret values in the stream before it leaves the worker.

Untrusted code. A forked pull request can run anything. Run it in a sandbox with no secrets, no access to the internal network and a hard CPU, memory and time limit. Secrets go only to jobs on protected branches, injected at start and never written to logs. The sandbox model is the subject of design LeetCode, and the application security lesson covers the supply-chain risks.

What if the queue or database is down? Webhooks return 503 and the git host retries delivery, so no push is lost. Running jobs continue and finish when the store returns, because workers buffer their final status and retry it.

Duplicate webhooks. Git hosts redeliver. The dedupe_key on a run makes the second delivery a no-op.

Trade-offs to name aloud

  • Pull over push: simpler and more resilient, at the cost of less clever placement.
  • Ephemeral workers: clean isolation and no state leaks, but a cold start on every job, which warm pools soften.
  • Fair queues: protects small teams, while a big team may wait longer for its burst.
  • At-least-once execution: a job can run twice after a lost lease, so deploy steps must be idempotent.
  • Autoscaling on queue age: responsive to what developers feel, but it can overshoot and cost more than a fixed fleet.

What interviewers listen for

  • A working answer: a webhook creates a run, jobs go on a queue, workers pull and run them, and logs and artifacts go to object storage.
  • A strong answer: sizes the system in machine-seconds, uses leases and heartbeats for lost workers, models the job graph as a state machine and keeps fair queues per team.
  • A standout answer: separates infrastructure failures from test failures, makes jobs safe to run twice, isolates untrusted forks from secrets and caches, and autoscales on queue age.

Check your understanding

Common mistakes

Sizing by requests per second. 9 jobs a second is nothing. The cost is thousands of concurrently busy workers, so size and scale in machine-seconds.

One FIFO queue for everyone. The first big burst makes small teams wait behind it, and the complaints reach you.

Push scheduling with no lease. If a worker dies after receiving a job, nobody knows. Leases make failure a normal event.

Treating "worker died" like "tests failed." Retrying on infrastructure errors and failing loudly on test errors are different policies, and developers need to see which one happened.

Letting forks see secrets. One workflow that exposes a deploy key to a pull request from a stranger is a breach. Gate secrets on branch protection.

Writing logs through the main database. Terabytes a day belong in chunks in object storage, with only metadata in the database.

Practice

Monday 9:00 AM, the job queue's oldest item is 14 minutes old and still growing. Walk through your diagnosis and the fixes, in order.

Write your own answer first, on paper or in a note. Then compare.

Show a hint

Ask first whether workers are the problem, the queue is, or one tenant is.

Show a strong answer

Look at supply and demand. Compare jobs arriving per second against jobs finishing. If arrivals are higher, you need workers. If workers are idle while jobs wait, the dispatcher or the lease logic is broken.

Check who is waiting. Break the queue down by team. If one team holds 80% of it, the fair queues are working but that team's burst is large. Fair share caps the damage; the rest of the queue should still be moving, so also check whether other teams' wait times are normal.

Scale on the right signal. Raise worker capacity from the queue's oldest-job age. Warm images start in seconds, so the backlog drains in minutes. Check that your cloud quota allows the instance count you need.

Look for stuck leases. Many jobs in leased with old heartbeats means a worker group died. Expired leases return them to the queue automatically, but check the lease timeout is not set to many minutes.

Prevent the repeat. Keep a warm pool sized for the Monday ramp, and schedule nightly jobs away from the 9:00 peak.

The pattern worth keeping: a queue that grows is a symptom. Split it by cause (not enough workers, a broken dispatcher, one tenant) before you add machines.

A deploy job to production ran twice because its worker's lease expired while it was still running. Nothing visible broke this time. How do you make sure it can never cause damage?

Write your own answer first, on paper or in a note. Then compare.

Show a hint

You cannot prevent two runs. You can make a second run harmless.

Show a strong answer

Fence the finish. Every lease carries a token that increases on each attempt. Only the job's current token may report success or failure, so the stale worker's result is rejected.

Make the deploy idempotent. Give the deploy a key made of (run id, target, version). The deploy tool checks whether that version is already live and does nothing if it is. Applying the same version twice is a no-op.

Take a lock on the target. Deploys to one environment go through a mutual-exclusion lock held by the current lease, so two attempts cannot change production at the same moment.

Lengthen the heartbeat for long steps. A deploy that legitimately takes ten minutes should renew its lease from a side thread, so slow does not look like dead.

The pattern worth keeping: at-least-once execution is the norm. Put the protection in the side effect (idempotency key, fencing token), not in the hope that a job runs only once.

Key takeaways

  • Size by machine-seconds. About 9 jobs a second becomes thousands of busy workers.
  • Workers pull jobs under a lease, and a missed heartbeat returns the job to the queue.
  • Give each team its own queue and dispatch fairly, so a burst cannot starve others.
  • A pipeline is a DAG, and each job is a small state machine whose transitions are transactional.
  • Jobs run at least once, so protect side effects with idempotency keys and fencing tokens.
  • Untrusted code gets no secrets and no shared caches.

Further reading

  • Google, "Site Reliability Engineering" (O'Reilly, 2016), the chapter on distributed periodic scheduling with cron: scheduling and failure handling at scale.
  • Martin Kleppmann, "Designing Data-Intensive Applications" (O'Reilly, 2017), the chapter on distributed systems trouble: leases, fencing tokens and unreliable clocks.
  • Jez Humble and David Farley, "Continuous Delivery" (Addison-Wesley, 2010): the pipeline and deployment practices this system supports.
  • Amazon Web Services documentation, "Amazon SQS visibility timeout": the same lease-style idea in a managed queue.

Check yourself

3 questions in this lesson. Answer each once to complete it.

Practice this

Lessons in this track