Build a Pipeline Execution Platform for Thousands of Tenants
System DesignModel answerLast updated
Design a scalable, multi-tenant CI/CD system that runs Git-triggered job pipelines with strong isolation, fair scheduling, live log streaming, and per-tenant billing.
The Problem
You are the founding engineer on a cloud-hosted pipeline execution service. Software teams connect their source repositories, drop a YAML workflow file into each repo, and the platform automatically runs those workflows whenever code is pushed. The service must handle thousands of independent organizations simultaneously, keep every organization's workload fully isolated from every other, and stay highly available under bursty load.
Walk through your architecture from start to finish, then go deep on each numbered area below.
What one pipeline run looks like
A developer pushes a commit. The platform receives a notification, reads the workflow file pinned to that exact commit, compiles it into a graph of jobs, executes those jobs on isolated compute, streams output to the developer's browser in real time, and records resource consumption for billing at the end.
Areas to cover
1. Ingesting push notifications The platform receives push events from SCM webhooks or an internal service API. Each event carries a repository ID, a commit SHA, a branch name, and a change summary. How do you authenticate callers, validate payloads, deduplicate repeated deliveries, and persist events durably before acknowledging them? How do you fan work out to downstream processors? What happens when those processors fall behind the arrival rate?
2. Fetching and compiling the workflow definition Every repository stores a YAML pipeline definition at a fixed path. How do you retrieve that file at the exact pushed commit (not the current branch tip)? How do you validate its schema, expand matrix build dimensions, construct the job dependency graph, detect cycles, and produce an immutable compiled plan that makes future re-runs reproducible?
3. Run and job lifecycle Define the state machine for a run and for each individual job. Explain how you handle job dependencies, conditional execution, matrix jobs, retries with exponential backoff, per-job timeouts, cancellation requests, idempotent state transitions, and manual approval gates.
4. Scheduling work fairly across tenants When thousands of organizations have queued jobs, how do you decide what to dispatch next? Describe your fairness mechanism, how you enforce per-tenant concurrency caps and minute quotas, and how you prevent a single large organization from crowding out smaller ones.
5. Compute runners and workload isolation Compare available runner form factors: shared containers, microVMs (e.g., Firecracker), and dedicated VM pools. How does a runner claim a job, clone source at the right commit, receive narrowly scoped secrets, restore build caches safely, and report results? How do you detect and recover from a runner that dies silently mid-job?
6. Live log and status streaming Developers expect to watch job output as it is produced. Trace the path from bytes written on a runner through to text appearing in a browser tab. How do you support late-joining viewers, client reconnects, and long-term log retention?
7. Storage systems Name each storage system your design relies on (relational DB, object store, message bus, cache, secret store) and describe exactly what it owns and why that system was chosen for that responsibility.
8. Tenant isolation, access control, and secret handling How do you prevent one tenant's jobs, logs, and secrets from being accessible to another? Describe your RBAC model, how secrets are scoped and injected into jobs, and how you enforce security policy at runtime.
9. Scaling the system How does the runner fleet grow and shrink in response to queue depth? How do you scale control-plane services horizontally? How do you shard the scheduler as dispatch throughput grows? How do you scale the metadata database?
10. Metering usage and billing tenants Which resource dimensions do you meter (compute time, storage, egress)? How do you collect, aggregate, and expose that data? How do budget caps and overage alerts work?
11. Observability and tamper-evident audit Describe your approach to structured logs, metrics, and distributed traces across control-plane services and runners. How do you produce an audit trail of security-relevant actions — secret access, approval decisions, permission changes — that cannot be quietly altered after the fact?
12. Reliability, recovery, and zero-downtime deployments How do you guarantee no push event is silently lost? How do you back up and restore the metadata database? How do you handle a full availability-zone or region outage? How do you roll out a database schema change or a new control-plane binary without dropping in-flight runs?
13. Key trade-offs and rollout strategy Discuss: shared runner pools vs. dedicated per-tenant pools; platform-managed runners vs. customer-hosted agents; and how you would phase the build of this system from a minimal first version to full production scale.
What a strong answer looks like
Cover every area above with enough detail to reveal genuine design decisions. Use rough numbers to justify component choices. Name trade-offs rather than presenting every decision as the obvious right answer. Code is not required.
Hints
Hint 1
Size the system before picking any components. Rough math — 2M runs/day at 5 jobs each, 8-minute average duration — puts peak concurrent jobs around 150k. That single number drives runner form factor, scheduler architecture, log pipeline throughput, and database write rates. Without it, every subsequent decision floats.
Hint 2
Idempotency is the central correctness challenge, not any individual component. Push events arrive at least once, runners crash mid-job, and retry logic fires from multiple code paths simultaneously. Every state transition should be a compare-and-set conditional write, and every message consumer should be able to re-process a message it already handled without changing the outcome. Design for this…
Hint 3
Fairness and isolation sound similar but require different mechanisms. Fairness is a scheduling policy question — whose job gets the next available runner slot. Isolation is a security and reliability question — preventing one tenant's workload from affecting another's correctness, performance, or data visibility. Answer them separately: fairness via weighted fair queuing across per-tenant ready q…
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Establish scale before drawing anything
Rough numbers anchor every downstream decision.
| Quantity | Estimate |
|---|---|
| Organizations | 5,000 |
| Repositories | 500k |
| Pipeline runs per day | 2M (~23/s average, ~150/s peak) |
| Jobs per day | ~10M (5 jobs per run) |
| Peak concurrent jobs | ~150k (8-min average job, 150/s peak ingest) |
| Log data per day | ~10 TB (~1 MB per job) |
| Control-plane status writes | Low thousands per second |
The control plane is not unusually large by modern standards. The genuinely hard problems are runner fleet economics, strong isolation at 150k concurrent VMs, log ingest throughput, and fair scheduling without a single bottleneck.
Functional must-haves: receive push events; fetch and compile the workflow YAML at the exact commit; execute a job DAG with matrices, retries, conditionals, approvals, and cancellations; stream live logs; meter and bill per tenant.
Non-functional must-haves: no lost events; strong tenant isolation; live status latency under ~1 s; 99.95% control-plane availability.
2. High-level architecture
Request flow, in order:
- Event gateway — authenticates, deduplicates, and persists incoming push events, then publishes to the message bus via a transactional outbox.
- Durable message bus (Kafka, partitioned by
tenant_id) — absorbs bursts, enforces ordering per tenant, decouples intake from processing. - Planner workers — consume events, fetch the YAML at the pushed SHA, validate and compile it into a job DAG, write an immutable plan blob to the object store, and create a
runrow in the metadata DB. - Orchestrator — drives job state transitions, evaluates
needsdependencies and runtimeif:conditions, enqueues ready jobs, fires retries, enforces timeouts, handles cancellations and approval gates. - Fair scheduler — reads per-tenant ready queues, checks concurrency caps, and dispatches jobs to the runner fleet.
- Runner fleet (ephemeral microVMs by default) — claims a lease, clones source, executes steps, ships log chunks, and reports completion.
- Log pipeline — ingest service buffers chunks, writes them to the object store, and tails new chunks to browser clients over Server-Sent Events.
All control-plane services are stateless. Durable state lives only in the metadata DB, Kafka, and the object store.
3. Deep dives
Event intake
Authenticate incoming webhooks with HMAC signature verification; use mTLS or short-lived service tokens for internal callers. Validate payload structure and confirm the repository ID belongs to the claimed tenant. Deduplicate with INSERT ... ON CONFLICT (delivery_id) DO NOTHING — SCMs supply delivery IDs; internal callers generate them. Persist the event row and enqueue to Kafka atomically via a transactional outbox pattern. Return HTTP 202 only after both writes succeed.
Backpressure: Kafka absorbs burst traffic naturally since consumers pull. A slow planner raises consumer lag rather than causing data loss. If a tenant exceeds their inbound rate tier, return HTTP 429 with a Retry-After header. For repeated pushes to the same branch, optionally supersede a still-queued run with the newer SHA ("latest-push-wins") to prevent unbounded queue growth.
Workflow compilation
Fetch the YAML through the SCM API using a short-lived, repo-scoped installation token, addressed by the exact SHA — never the branch tip, which may have advanced. Validate the document against a versioned JSON Schema. Enforce hard limits: max job count, matrix cardinality ≤ 256, file size. Expand matrices into concrete job instances, resolve needs edges, run a topological sort, and reject cycles immediately. Evaluate static if: expressions; leave runtime conditions for the orchestrator. Write the compiled plan as a content-addressed JSON blob. The run row stores the plan hash, making re-runs bit-for-bit reproducible even if the YAML is later changed. Planning is idempotent on delivery_id.
Run and job state machine
Job states: PENDING → QUEUED → LEASED → RUNNING → {SUCCEEDED, FAILED, TIMED_OUT, CANCELLED, SKIPPED}, with WAITING_APPROVAL as a hold state before QUEUED.
Run state is derived: QUEUED, RUNNING, SUCCEEDED, FAILED, CANCELLED.
Every transition is a conditional write: UPDATE jobs SET state=new WHERE job_id=? AND state=expected AND fence=current. Stale retries that arrive with an old fence value are silently ignored. When a job finishes, the orchestrator evaluates its downstream dependents — enqueue them if their needs are satisfied and their if: is true, otherwise mark them SKIPPED (or fail fast).
Retries apply only to infrastructure failures or explicitly configured exit codes. Backoff: 10 s, 40 s, 160 s with jitter. Each attempt increments a counter and issues a new fencing token.
Timeouts are stored as (job_id, deadline) in a durable timer service. On expiry, the orchestrator transitions the job to TIMED_OUT and sends a kill signal to the runner via the next heartbeat response.
Cancellation: set CANCEL_REQUESTED. The runner reads this on its next heartbeat, sends SIGTERM, waits a grace period, then force-kills. Approval gates hold a job in WAITING_APPROVAL until an authorized user approves, which writes an audit record before transitioning to QUEUED.
Scheduling and fairness
Maintain a ready queue per tenant. The scheduler uses deficit round-robin (or virtual-time weighted fair queuing) across tenants that currently have runnable jobs. A job is dispatched only when two conditions hold: the tenant is under its concurrency cap (tracked in Redis with atomic decrements, released on completion or lease expiry) and the tenant has remaining quota-minutes in the current window. Within a tenant, dispatch is FIFO by job priority. Noisy-neighbor protection comes from a combination of per-tenant API rate limits, cgroup CPU/memory quotas inside runner VMs, bounded matrix sizes, and routing large tenants to dedicated pools.
Runners and isolation
| Form factor | Strengths | Weaknesses |
|---|---|---|
| Shared containers | Fast startup, high density | Shared kernel; weak for untrusted third-party code |
| microVMs (Firecracker) | ~150 ms boot, own kernel, strong isolation | Small memory overhead |
| Dedicated VM pools | Strongest isolation, GPU support, compliance | Higher cost, slower scale-out |
MicroVMs are the right default for shared pools. Dedicated pools are offered as a higher tier.
Execution flow: the runner atomically claims a lease with a 30-second expiry and a fencing token, boots a fresh ephemeral VM (never reused across tenants), clones the repo at the exact SHA using a scoped read token, restores the build cache (keyed by tenant + repo + lockfile hash; caches are tenant-scoped to prevent poisoning), and fetches secrets just in time via OIDC token exchange with the secret service. The runner sends heartbeats every 10 s; a missed heartbeat causes the orchestrator to expire the lease and re-queue the job after a brief grace period.
Live log streaming
The runner batches log bytes into small chunks (e.g., 4 KB or 500 ms, whichever comes first) and POSTs them with a monotonically increasing sequence number to the log ingest service. The ingest service writes chunks to the object store and publishes sequence numbers to a fan-out bus (Redis pub/sub or a lightweight Kafka topic). A streaming gateway tails new chunk references and sends them to browser clients as SSE events with a cursor. A late-joining viewer requests logs from cursor 0; the gateway replays stored chunks then switches to live tail. Log data is retained in the object store under lifecycle rules (e.g., 90 days on standard storage, then glacier).
Storage systems
- Metadata DB (CockroachDB, Spanner, or Aurora): runs, jobs, events, usage records, audit log. Every table has
tenant_idas the leading key. Row-level security prevents cross-tenant reads at the DB layer. - Object store (S3-compatible): immutable plan blobs, log chunks, build artifacts, caches. Per-tenant key prefixes with bucket policies.
- Message bus (Kafka): event intake, orchestrator notifications, log ingest fan-out. Partitioned by
tenant_id. - Cache (Redis): concurrency token counters, SSE fan-out pub/sub, short-lived dedup keys.
- Secret store (HashiCorp Vault or cloud KMS): tenant secrets encrypted with per-tenant data keys under a KMS master key. Jobs receive OIDC tokens and exchange them for the specific secrets their job definition is allowed to read.
Tenant isolation and RBAC
Every resource (run, job, log, secret) is namespaced by tenant_id. Row-level security in the DB enforces this at the query layer. Runners for one tenant never share a VM or network namespace with another tenant's runners. RBAC has three principal levels: organization admin, project writer, and project reader. Secrets are scoped to an environment and a job name pattern; the secret service refuses requests outside that scope. A policy engine (OPA or equivalent) evaluates runtime policy checks before any sensitive action executes.
Scaling
The runner fleet scales on queue depth: a controller monitors per-tenant lag and the global ready-queue length, issues scale-out requests to the cloud provider, and boots new runner VMs within a target of under 60 s. Control-plane services are stateless pods behind a load balancer; horizontal scaling is unremarkable. The scheduler shards by hashing tenant_id to scheduler instances; re-sharding requires only a config change since no in-memory state is authoritative. The metadata DB uses read replicas for query-heavy workloads and range-based partitioning on tenant_id as row counts grow.
Metering and billing
Meter three dimensions: compute (CPU-seconds and RAM-GB-seconds per job), storage (GB-days of artifact and log retention), and egress (GB transferred out of the platform network). The runner emits a usage record on job completion. A metering pipeline (Kafka consumer → aggregation workers → time-series store) rolls records into hourly and daily buckets per tenant. A billing service reads daily buckets, applies plan rates, and exposes a usage API. Budget alerts fire when projected monthly spend crosses a configurable threshold; hard caps pause new job dispatch after a grace period.
Observability and audit
Every service emits structured JSON logs with trace_id, tenant_id, and job_id. Metrics (counters, histograms) are scraped by Prometheus and visualized in Grafana. Distributed traces (OpenTelemetry) cover the full path from event intake through planner, orchestrator, scheduler, and runner heartbeat. The audit log is an append-only table where each row stores a hash of the previous row, creating a hash chain. Any row deletion or modification breaks the chain, which is verified by a periodic background checker. Security-relevant actions — secret reads, approval decisions, RBAC changes, runner lease grants — always write an audit record as part of the same DB transaction as the action itself.
Reliability and deployments
No lost events: Kafka with acks=all, min.insync.replicas=2, and the transactional outbox pattern. Consumers commit offsets only after successfully writing to the DB.
Database recovery: continuous WAL shipping to cross-region object storage, point-in-time recovery (PITR) with a 30-day window, daily full snapshots tested by automated restore drills.
Region failure: active-passive setup with a recovery time objective of under 15 minutes. Kafka topics replicate cross-region; the standby region's control plane can be promoted by flipping DNS. Runners are regional; in-flight jobs on the failed region are timed out and re-queued on recovery.
Zero-downtime deploys: schema migrations follow expand-and-contract — add new columns as nullable, deploy new code that writes both old and new columns, backfill, flip reads, then drop the old columns in a later release. Control-plane binary rollouts use rolling deploys with at most 25% of pods replaced at a time. In-flight jobs are drained from pods before shutdown via a SIGTERM handler that stops accepting new leases.
4. Trade-offs summary
Shared vs. dedicated runners: shared pools are cost-efficient and fine for most workloads, but dedicated pools are necessary for compliance requirements, GPU workloads, or tenants who need stronger isolation guarantees. Offer dedicated as a higher tier rather than defaulting to it.
Platform-managed vs. customer-hosted agents: managed runners remove operational burden from customers but require the platform to handle all egress control and secret injection. Customer-hosted agents let enterprises keep sensitive code inside their own network but shift the operational complexity back to them and make isolation harder to enforce. Support both, but managed is the default.
Phased rollout: phase 1 — single region, shared container runners, no matrix support, basic log storage; phase 2 — microVM isolation, matrix expansion, fair scheduler, live streaming; phase 3 — multi-region, dedicated pools, full metering and billing, policy engine, PITR.
The most common design mistake is conflating fairness and isolation. Fairness is a scheduling policy; isolation is a security property. They require separate mechanisms and separate reasoning.