Home

Bin-packing your CI shards

November 29, 2026

A test suite split across parallel jobs is only as fast as its slowest job. On a large codebase I work on, tests were split evenly by file count. Most shards finished quickly. One took several times longer than the rest, and every pull request waited for it.

Why splitting by file count fails

Test files aren't the same size. A file with three unit tests and a file with forty browser tests count the same when you split by count. In a modular codebase it gets worse: some areas have heavy integration tests and some have almost none, and their files tend to sit next to each other. An even split by count is an uneven split by time.

Split by time instead

Two parts.

Record timings. Each CI run saves how long every test file took, and the latest timings feed the next run. Files with no history get a default estimate so new tests don't break the split.

Pack greedily. With durations known, this is classic bin-packing: fill N bins so the fullest one is as small as possible. The optimal answer is expensive, but the greedy approximation is simple and good enough:

  1. Sort files by duration, longest first.
  2. Put each file into the shard with the least total time so far.

Longest-first matters: the big files go in early, and the small ones fill the gaps evenly at the end.

ts
1function packShards(
2 files: { path: string; seconds: number }[],
3 shards: number,
4) {
5 const bins = Array.from({ length: shards }, () => ({
6 total: 0,
7 files: [] as string[],
8 }))
9 for (const file of [...files].sort((a, b) => b.seconds - a.seconds)) {
10 const lightest = bins.reduce((min, bin) =>
11 bin.total < min.total ? bin : min,
12 )
13 lightest.files.push(file.path)
14 lightest.total += file.seconds
15 }
16 return bins
17}

With the same number of runners, the slowest shard became about four times faster.

Small things around it

  • Run the tests of code that depends on what changed, not only the tests next to the change.
  • Cache build layers between runs.
  • Watch for CI runs that hang instead of failing.
  • Make time-dependent tests independent of time zones and daylight saving, because the flakiest test is the one that fails twice a year.

The lesson

When something is slow, measure where the time goes before adding machines. The split was the bug, not the number of runners. And greedy algorithms deserve more credit than they get: a ten-line approximation fixed what more hardware wouldn't have.