# How to Speed Up a Slow CI Pipeline: Measure, Cache, Then Shard

A CI pipeline finishes when its slowest path finishes. Jobs run side by side, so making an already fast job faster changes nothing you can feel. That is why "add caching" sometimes helps a lot and sometimes does nothing.

The order of work matters. First, find where the time goes. Then remove work you don't need, cache work that repeats, and only after that split what is left across more machines.

The example run and the test suite in this post are made up. The scripts shown here generated them. They demonstrate the method, and the numbers are not benchmarks of your pipeline.

## Step 1: Find the slow step

GitHub Actions records when every job and step starts and ends. You can download those times from the REST API, using the "list jobs for a workflow run" endpoint. Each job comes with a list of its steps:

```bash
curl -L \
  -H "Accept: application/vnd.github+json" \
  -H "Authorization: Bearer $GITHUB_TOKEN" \
  "https://api.github.com/repos/OWNER/REPO/actions/runs/RUN_ID/jobs?per_page=100" \
  > jobs.json
```

The script below reads that file. It prints how long the whole run took, which jobs were slowest, and which steps cost the most. Some steps, such as skipped ones, can come back without timestamps, so the script ignores them.

```python
"""Summarize a GitHub Actions run from the "List jobs for a workflow run" API response.

Usage: python ci_timings.py jobs.json
"""
import json
import sys
from datetime import datetime

def parse(value):
    return datetime.fromisoformat(value.replace("Z", "+00:00"))

def seconds(start, end):
    return (parse(end) - parse(start)).total_seconds()

def fmt(secs):
    m, s = divmod(round(secs), 60)
    return f"{m}m{s:02d}s"

def summarize(payload, top=5):
    jobs = [j for j in payload["jobs"] if j.get("started_at") and j.get("completed_at")]
    first = min(parse(j.get("created_at") or j["started_at"]) for j in jobs)
    last = max(parse(j["completed_at"]) for j in jobs)
    wall = (last - first).total_seconds()
    busy = sum(seconds(j["started_at"], j["completed_at"]) for j in jobs)

    print(f"Wall clock: {fmt(wall)}   Sum of job times: {fmt(busy)}   ({busy / wall:.1f}x parallel)\n")
    print(f"{'job':<14}{'queued':>8}{'ran':>9}")
    for j in sorted(jobs, key=lambda j: -seconds(j["started_at"], j["completed_at"])):
        queued = seconds(j["created_at"], j["started_at"]) if j.get("created_at") else 0
        print(f"{j['name']:<14}{fmt(queued):>8}{fmt(seconds(j['started_at'], j['completed_at'])):>9}")

    steps = []
    for j in jobs:
        for s in j.get("steps", []):
            if s.get("started_at") and s.get("completed_at"):   # skipped steps have no timestamps
                steps.append((seconds(s["started_at"], s["completed_at"]), j["name"], s["name"]))
    print(f"\nSlowest {top} steps:")
    for secs, job, name in sorted(steps, reverse=True)[:top]:
        print(f"  {fmt(secs):>7}  {job} / {name}")

if __name__ == "__main__":
    summarize(json.load(open(sys.argv[1])))
```

On the made-up example run, which has four jobs (lint, unit tests, build, and end-to-end tests), it prints this:

```text
Wall clock: 12m47s   Sum of job times: 26m32s   (2.1x parallel)

job             queued      ran
e2e              0m21s   12m26s
unit-tests       0m09s    7m15s
build            0m15s    3m55s
lint             0m12s    2m56s

Slowest 5 steps:
    8m50s  e2e / Run Playwright
    4m45s  unit-tests / Run unit tests
    2m11s  unit-tests / Install dependencies
    2m11s  lint / Install dependencies
    2m11s  e2e / Install dependencies
```

Three things stand out.

The run is only as fast as the `e2e` job. Making the lint job faster would be wasted effort.

Inside the `e2e` job, the test step is the biggest piece.

The same 2m11s dependency install appears in every job. It takes three of the five slots in the slowest-steps list, even though no single install looks bad. Queue time is under 25 seconds everywhere, so waiting for a runner isn't the problem.

Run the script on several runs before you decide anything. One run is noisy, and a step that looks slow once may not be.

## Step 2: Cache what repeats

Installing the same dependencies in every run is the classic thing to cache. The `actions/cache` action saves files from one run and restores them in a later run, matched by a key.

The lookup works in two stages. It first looks for an exact match on `key`. If there is none, it tries each `restore-keys` entry as a prefix and restores the newest cache that starts with it.

```yaml
- uses: actions/checkout@v6

- name: Cache npm downloads
  uses: actions/cache@v4
  with:
    path: ~/.npm
    key: ${{ runner.os }}-npm-${{ hashFiles('**/package-lock.json') }}
    restore-keys: |
      ${{ runner.os }}-npm-

- run: npm ci
```

Action versions change, so check each action's releases before you copy this.

A few rules about how the cache behaves:

-   A cache entry can't be changed once it exists. That is why the key includes a hash of the lockfile. When your dependencies change, the key changes and a new cache is saved.
    
-   A new cache is saved only if the job succeeds.
    
-   Lookups check the current branch first, then the default branch. A feature branch can start from a cache built on `main`.
    
-   For npm, Yarn, and pnpm, the `setup-node` action can do all of this for you with `cache: npm` (or `yarn`, `pnpm`). Other setup actions offer similar built-in caching.
    
-   Never put secrets or tokens in a cached path.
    

Cache storage has limits. By default, each repository gets 10 GB, and entries that go unused for 7 days are deleted. When a repository goes over its limit, the least recently used entries are deleted first. Since November 2025, admins can raise the limit above 10 GB, and the extra storage costs money.

If your builds save many large caches, they can push each other out. Caches then get created and deleted over and over, and they rarely get used. This is called thrashing.

Check that a cache is worth it. Restoring it has to be faster than redoing the work. Compare the step's time before and after, using the script from Step 1.

## Step 3: Stop paying for work nobody needs

Two small settings cut waste without touching your tests. The first cancels an older run when a new commit arrives on the same branch. The second sets a time limit, so a stuck job can't run forever:

```yaml
concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  test:
    timeout-minutes: 20
```

Leave `cancel-in-progress` off for jobs that must finish once they start, such as deployments.

## Step 4: Split the slowest job across machines

Sharding means splitting your tests into groups and running each group on its own machine at the same time. Each group is a shard.

The `e2e` job is the slowest path, and its test step is the biggest piece, so that is where sharding helps. Two machines that each run half the tests take about half the time. But the job is only as fast as its slowest shard, so how you split matters.

To see how much, take a made-up suite of 300 test files. It has many fast unit tests, some integration tests, and a tail of slow end-to-end files, and together they take 38.6 minutes. Split four ways, a perfect split gives 9.7 minutes per shard.

| Strategy | Slowest shard | Compared with perfect |
| --- | --- | --- |
| Equal-count chunks (same number of files per shard) | 25.6 min | 2.65x |
| Round-robin | 11.4 min | 1.18x |
| Chunks cut using recorded durations | 9.8 min | 1.01x |
| Longest-first using recorded durations | 9.7 min | 1.00x |

Splitting by file count puts all the slow files together. The pipeline then waits 26 minutes instead of 10.

Once you know how long each test takes, almost any method that uses durations gets close to perfect. The last two rows barely differ. What matters most is having the duration data.

Here is the longest-first method. It gives the next-longest test to whichever shard has the least work so far:

```python
import heapq

def longest_first(durations, shards):
    """durations: {test_name: seconds}. Returns one list of test names per shard."""
    heap = [(0.0, i) for i in range(shards)]
    plan = [[] for _ in range(shards)]
    for name, seconds in sorted(durations.items(), key=lambda kv: -kv[1]):
        load, i = heapq.heappop(heap)
        plan[i].append(name)
        heapq.heappush(heap, (load + seconds, i))
    return plan
```

Durations go out of date as a suite changes, so this was tested too. The same suite was planned with wrong durations (each one multiplied by a random factor) and then run with the true ones, 2,000 times for each setting.

If the planned durations were off by about a third, longest-first averaged 1.06 times the perfect split, and 95 out of 100 trials came in under 1.11. If they were off by nearly double or half, it averaged 1.10, and 95 out of 100 trials stayed under 1.19. Chunking by duration did slightly worse in both cases.

So even badly outdated numbers cost about ten percent on average. That is small next to splitting blind. Refresh the durations now and then, and don't aim for perfect.

You rarely need to write the splitter yourself. Playwright splits tests with a flag and works with a job matrix. Its blob reporter and the `merge-reports` command combine the reports from all shards into one:

```yaml
strategy:
  fail-fast: false
  matrix:
    shardIndex: [1, 2, 3, 4]
    shardTotal: [4]
steps:
  - run: npx playwright test --shard=${{ matrix.shardIndex }}/${{ matrix.shardTotal }}
```

In Python, the `pytest-split` plugin records test durations from a full run with `pytest --store-durations`. Each job then runs one group, for example `pytest --splits 4 --group 1`. Its `least_duration` algorithm balances better than the default. Tests with no stored duration get the average, so you don't need to re-record after every change.

### More shards aren't always better

Every shard repeats the setup: checkout, install, and build. Here is the same made-up suite with two minutes of setup on each shard:

| Shards | Wall clock | Total runner time |
| --- | --- | --- |
| 1 | 40.6 min | 40.6 min |
| 2 | 21.3 min | 42.6 min |
| 4 | 11.7 min | 46.6 min |
| 8 | 6.8 min | 54.6 min |
| 16 | 4.4 min | 70.6 min |
| 32 | 3.2 min | 102.6 min |

Wall clock is how long you wait. Total runner time is the sum across all machines, which is what you pay for.

Going from 1 to 4 shards makes the run about 3.5 times faster and uses about 15 percent more runner time.

Going from 4 to 16 saves another 7 minutes, but runner time goes up by about half. At 32 shards you approach a floor set by the setup time and your single longest test.

This is where Step 2 pays off a second time. The cheaper your setup is, the more shards are worth running.

## Things to watch for

-   Tests that share state. If tests share a database or fixtures, running them on different machines can expose hidden coupling.
    
-   Flaky tests. More machines make them easier to see. Fix or quarantine them instead of retrying everything.
    
-   Reports. Merge the per-shard reports, or failures end up scattered across jobs.
    
-   Changes that affect each other. Faster setup, for example, changes the best number of shards. Re-measure after each change.
    

## References

-   GitHub Docs, [Dependency caching reference](https://docs.github.com/en/actions/reference/workflows-and-actions/dependency-caching): `actions/cache`, keys, `restore-keys`, matching order, `setup-*` caching, limits
    
-   GitHub Changelog, [GitHub Actions cache size can now exceed 10 GB per repository](https://github.blog/changelog/2025-11-20-github-actions-cache-size-can-now-exceed-10-gb-per-repository) (November 20, 2025)
    
-   GitHub Docs, [REST API endpoints for workflow jobs](https://docs.github.com/en/rest/actions/workflow-jobs): job and step timestamps
    
-   Playwright, [Sharding](https://playwright.dev/docs/test-sharding): `--shard`, matrix setup, blob reports, `merge-reports`
    
-   `pytest-split`: stored durations, `--splits` and `--group`, splitting algorithms

---

*Published via [ZyVOP](https://zyvop.com/how-to-speed-up-a-slow-ci-pipeline-measure-cache-then-shard-k5ywn?utm_source=hashnode&utm_medium=crosspost&utm_campaign=syndication) — Write once in Markdown, auto-backup to GitHub, and syndicate to Dev.to, Medium & Hashnode in 1 click.*
