Build a Fast Pipeline for a Million-Test Suite Under Ten Minutes
System DesignModel answerLast updated
Design a CI pipeline that compiles a code change and executes roughly one million tests, returning results in ten minutes, while justifying sharding, caching, flakiness and cost decisions.
You own the test infrastructure for a very large monorepo. The test suite contains about 1,000,000 tests. When an engineer submits a change, your pipeline must compile it, execute the tests, and report which ones failed. A complete run must finish within 10 minutes of wall-clock time.
Design this pipeline. Do not simply list components: for each major decision, explain the alternatives you considered and why you chose what you did.
Given
- Roughly 1,000,000 tests per full run.
- A hard 10-minute wall-clock budget for a full run.
- Per-test durations, submission rate and cost limits are not provided. Either ask about them or state explicit assumptions and carry them through your numbers.
Questions you may want to raise with the interviewer
- Does the 10 minutes include compilation and machine startup, or only test execution?
- Is the duration distribution mostly fast unit tests, or is there a long tail of slow integration tests? Is historical timing data available?
- Must every change run every test, or may the system run only the tests a change could affect?
- Are tests hermetic? How common are flaky tests?
- What is the peak number of changes per hour, and is there a spending cap?
What to cover
- A capacity estimate tying test count, durations and the time budget to the number of executors and machines.
- How tests are partitioned and scheduled so no shard overruns, including very long tests and slow machines.
- How build outputs reach thousands of executors quickly, and what is reused between runs.
- Running everything versus running a selected or cached subset, and how you catch regressions that selection misses.
- Handling flaky tests, executor failures and retries without blowing the budget.
- Cost versus latency (warm pool versus autoscaling) and the metrics that prove you are meeting the target.
Hints
Hint 1
Start with arithmetic: total test-seconds divided by the time left for execution gives the minimum parallelism. Then add headroom for startup, stragglers and retries.
Hint 2
Think about scheduling as a bin-packing or work-queue problem. Use historical durations to balance shards, and consider pulling work dynamically instead of assigning fixed shards up front. Decide what to do with tests longer than a single shard's budget.
Hint 3
Most of the cost and latency win comes from not redoing work: content-addressed build caching, cached test results keyed by input hash, and dependency-based test selection with a periodic full run as a safety net.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify and state assumptions
I would first ask whether the 10 minutes covers build and provisioning. I will assume it is end to end, from submit to report, which is the stricter reading. I will also assume:
- Mean test duration of about 0.5 s, so total work is roughly 500,000 test-seconds. The distribution has a long tail: a few thousand tests take 30 s to several minutes.
- Tests are mostly hermetic; about 0.5% are flaky.
- Peak load of about 300 changes per hour, so several full-suite runs can overlap.
2. Capacity estimate
Budget the 10 minutes roughly as: 1.5 min for build and analysis, 1 min for distribution and startup, 6 min for test execution, and 1.5 min as slack for stragglers, retries and reporting.
- 500,000 test-seconds over a 360 s execution window needs about 1,400 busy cores.
- Real efficiency is perhaps 60-70% because of setup, imbalance and tail effects, so I would plan for about 2,000-2,500 cores. With 32-core machines that is roughly 70-80 machines per run.
- With overlapping runs at peak, that is several hundred machines. Without any reuse this is expensive, which motivates the caching and selection below.
The key point is that the budget fixes parallelism, and parallelism fixes cost, so the biggest lever is reducing the work, not adding machines.
3. Build stage
- Use a hermetic, incremental build system with a remote content-addressed cache. Each action is keyed by the hash of its inputs. Most changes touch a small part of the dependency graph, so most outputs are cache hits.
- A remote build executor farm handles cache misses in parallel.
- The output is a set of test binaries plus a manifest of tests and their expected durations.
Trade-off: remote caching needs strict hermeticity. Non-deterministic build steps poison the cache, so I would add a check that rebuilds a sample of actions and compares hashes.
4. Partitioning and scheduling
Static sharding by historical duration (longest-processing-time-first bin packing) is simple but fails when estimates are wrong, machines are slow, or new tests have no history.
I prefer a hybrid:
- A central scheduler holds a queue of test batches, ordered longest first, which is the standard way to limit the tail.
- Executors pull work, so fast machines naturally take more and slow ones take less.
- Small tests are grouped into batches of about 5-10 s to amortize process startup. Large tests run alone.
- Tests longer than the budget allows are split (by test case or file) or moved to a separate longer-running tier that reports asynchronously and gates merge only if configured.
- Tests with no history get a conservative default estimate and are scheduled early.
Straggler control: if a batch exceeds, say, 3x its expected duration, launch a speculative duplicate on another executor and take whichever finishes first.
5. Artifact distribution
Thousands of executors fetching a multi-GB build from one place will saturate it.
- Store artifacts in object storage, fronted by a tiered cache: a per-rack or per-zone cache, then a per-machine local cache.
- Fetch only the files needed by the assigned tests (the manifest lists dependencies), and use chunk-level deduplication so unchanged layers are already on disk.
- Keep warm machines with a recent checkout and base image already loaded so only a delta is transferred.
6. Do less work: caching and selection
- Test result caching: if a test's transitive input hash is unchanged, reuse the prior result. For a hermetic suite this alone can skip the large majority of tests.
- Dependency-based selection: run tests whose dependency closure intersects the changed files. Be conservative for changes to widely shared libraries, which legitimately run most tests.
- Safety net: run the full suite periodically (for example continuously on the main branch, or on a rolling post-submit basis). Any failure the selection missed is attributed with automated bisection to the offending change and triggers a rollback or alert.
The 10-minute guarantee should hold even in the worst case (a full run), so I would size capacity for that but expect typical runs to use a fraction.
7. Flaky tests and failures
- Retries: re-run failed tests a limited number of times (for example up to 2) on a different executor. Pass-after-retry is reported as flaky, not as a failure.
- Quarantine: track per-test flake rate. Tests above a threshold are moved out of the blocking path, assigned to an owner, and monitored until fixed. Without this, a 0.5% flake rate over 1M tests would mean thousands of spurious failures per run.
- Executor failure: heartbeats plus lease timeouts. If a lease expires, the batch returns to the queue. Because tests are idempotent, re-execution is safe.
- Retry budget: cap total retry time so a bad change cannot consume the slack window. If it is exhausted, report partial results clearly instead of missing the deadline.
- Fail fast: if a build error or a large cluster of identical failures appears, stop early and report.
8. Cost versus latency
- A warm baseline pool sized for typical load, plus autoscaling (and preemptible or spot capacity for retryable work) for peaks. Cold-starting hundreds of machines costs minutes, so scale predictively from submission rate and time of day.
- Prioritize: pre-merge runs for blocking changes ahead of batch or post-submit work.
- Offer tiers: a fast subset (impacted tests) for quick feedback and the full run as the gate.
9. Metrics
- p50/p95/p99 end-to-end latency, with a breakdown by stage (build, distribution, execution, tail).
- Queue wait time, executor utilization, cache hit rates (build, test result, artifact).
- Flake rate, retry rate, and escaped-regression rate from the safety-net runs.
- Cost per run and per change.
Alert on the p95 tail, not the mean, since the budget is a worst-case promise.
Common mistakes
- Giving a machine count without showing the arithmetic or the overhead assumptions.
- Using only static sharding, then ignoring stragglers and slow machines.
- Forgetting artifact distribution, which is often the real bottleneck at thousands of executors.
- Treating test selection as free: it needs a safety net.
- Retrying flaky tests with no cap, which silently breaks the time budget.