# Scaling pipelines: reuse, your own runners, speed and cost

When one pipeline becomes fifty: reusable workflows and composite actions, self-hosted runners run safely, and faster, cheaper pipelines through measurement, not guesses.

Course: [CI/CD Pipelines](https://devops.rajeev.pro/courses/cicd), lesson 12. About 35 minutes, intermediate. Source: https://devops.rajeev.pro/courses/cicd/12-scaling-pipelines

## What you will learn

- Turn a pipeline into a reusable workflow with inputs, outputs and secrets, and call it from other repositories
- Package repeated steps as a composite action
- Choose between reusable workflows and composite actions
- Explain when self-hosted runners are worth it, and run them safely and ephemerally
- Find what makes a pipeline slow or expensive, and fix the biggest cause first
- Build only the services a change affects in a monorepo
- Measure delivery with the four DORA metrics

## From one pipeline to fifty

One repository with one `ci.yml` is easy. Fifty services with fifty copies of it isn't: a fix to one has
to be made fifty times, and they drift apart. Two tools share pipeline code, at two sizes:

Copying a workflow is fast at first, then each copy drifts as teams make local edits. A reusable workflow or
composite action lets the team fix common steps once and roll out changes deliberately. In a monorepo, path-aware
jobs avoid rebuilding unrelated services. In this lesson, you'll choose the right reuse boundary, isolate
self-hosted runners, and measure pipeline time before optimizing.

> **Figure.** Two levels of reuse. On the left, a reusable workflow, node-ci.yml with on: workflow_call, owns whole jobs: lint, unit and integration, each with its runner and permissions. Service repositories call it as a single job with uses: and pass inputs such as node-version, and secrets. On the right, a composite action, setup-shop, bundles steps: setup-node with caching and npm ci. Jobs call it as one step. The reusable workflow itself uses the composite action in each of its jobs. Reusable workflows share pipelines; composite actions share steps.
>
> A reusable workflow shares whole jobs. A composite action shares a few steps inside a job. Big setups use both.

|            | Reusable workflow                                  | Composite action                         |
| ---------- | -------------------------------------------------- | ---------------------------------------- |
| Shares     | whole **jobs**, with their runners and permissions | a sequence of **steps**                  |
| Defined by | `on: workflow_call` in `.github/workflows/`        | `runs: using: composite` in `action.yml` |
| Called as  | a job: `jobs.x.uses:`                              | a step: `steps[].uses:`                  |
| Secrets    | passed explicitly, or `secrets: inherit`           | only through inputs                      |
| Use for    | "the standard Node pipeline"                       | "set up Node and install deps"           |

## Reusable workflows: share a whole pipeline

A reusable workflow is a normal workflow whose trigger is `workflow_call`, with typed inputs and outputs:

```yaml
# .github/workflows/node-ci.yml
name: Node CI (reusable)

on:
  workflow_call:
    inputs:
      node-version:
        type: string
        default: '22'
      run-integration:
        type: boolean
        default: true
    outputs:
      coverage-ok:
        description: Whether the coverage threshold passed
        value: ${{ jobs.unit.outputs.coverage-ok }}

permissions:
  contents: read

jobs:
  lint:
    runs-on: ubuntu-latest
    timeout-minutes: 5
    steps:
      - uses: actions/checkout@v7
      - uses: ./.github/actions/setup-shop
        with:
          node-version: ${{ inputs.node-version }}
      - run: npm run lint

  unit:
    runs-on: ubuntu-latest
    timeout-minutes: 10
    outputs:
      coverage-ok: ${{ steps.cov.outcome == 'success' }}
    steps:
      - uses: actions/checkout@v7
      - uses: ./.github/actions/setup-shop
        with:
          node-version: ${{ inputs.node-version }}
      - id: cov
        run: npm run test:coverage

  integration:
    if: inputs.run-integration
    needs: [lint, unit]
    runs-on: ubuntu-latest
    timeout-minutes: 15
    steps:
      - uses: actions/checkout@v7
      - uses: ./.github/actions/setup-shop
        with:
          node-version: ${{ inputs.node-version }}
      - run: npm run test:integration
```

The caller shrinks to a few lines:

```yaml
# .github/workflows/ci.yml
jobs:
  node:
    uses: ./.github/workflows/node-ci.yml             # same repository
    with:
      node-version: '22'

  # from a shared repository, pinned to a tag or SHA, like any action:
  # node:
  #   uses: your-org/ci-templates/.github/workflows/node-ci.yml@v1
  #   with: { run-integration: false }
  #   secrets: inherit
```

The checks appear as `node / lint`, `node / unit`, `node / integration`; use those names in required
status checks. Keep shared workflows in one `ci-templates` repository, version them with tags (the Git
course's _Releases_ lesson), and callers upgrade deliberately. For a private shared repository, allow access
under its _Settings → Actions → General → Access_.

Choose a reusable workflow when the shared unit is a whole job or pipeline stage, including its runner and
permissions. The caller passes declared inputs and receives outputs from the called workflow. Version the shared
workflow and test updates before consumers adopt them; a breaking change can affect many repositories. Keep the
permissions narrow in both the caller and the reusable workflow, and pass secrets explicitly when possible so
the shared code receives only what it needs.

> **Video.** [GitHub Actions Reusable Workflows FULL TUTORIAL with Examples: Templates on Steroids](https://www.youtube.com/watch?v=lRypYtmbKMs) (CoderDave)

## Composite actions: share steps

When several jobs start with the same three steps, make them one:

```yaml
# .github/actions/setup-shop/action.yml
name: Set up shop-api
description: Install Node and the npm dependencies, with caching.
inputs:
  node-version:
    description: Node.js version to install
    default: '22'
runs:
  using: composite
  steps:
    - uses: actions/setup-node@v7
      with:
        node-version: ${{ inputs.node-version }}
        cache: npm
    - run: npm ci
      shell: bash
```

```yaml
steps:
  - uses: actions/checkout@v7                 # local actions need the code checked out first
  - uses: ./.github/actions/setup-shop
    with:
      node-version: '22'
```

> **Composite run steps need a shell.** A workflow's `run:` steps default to bash; a composite action's don't, so each `run:` needs `shell: bash`. actionlint doesn't check this inside `action.yml`, so the mistake shows up only as a failed run. Composite actions also can't read `secrets` directly: pass what they need as inputs.

Use a composite action when several workflows need the same small sequence inside one job, such as installing
Node and dependencies. It does not create a new runner or job boundary. Keep its inputs explicit and avoid
letting the action silently choose credentials or deployment permissions. Because the action runs in the caller's
job, it inherits that job's available context and permissions. Review its source like any other code dependency.

> **Video.** [GitHub Custom Actions Explained | Composite Actions with 2 Demos](https://www.youtube.com/watch?v=v6VdLk1gQSc) (Cloud With VarJosh)

## Self-hosted runners

GitHub-hosted runners suit most work. Run jobs on your own machines when you need something they can't
give: hardware (GPUs, ARM, lots of memory), access inside a private network (a database behind a firewall),
or very high volume where your own machines are cheaper.

```yaml
runs-on: [self-hosted, linux, x64, gpu]    # labels you gave your runner
```

| Do                                                                            | Why                                                                                    |
| ----------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
| Use them for **private** repositories only                                    | a public repo's pull request runs a stranger's code on your machine                    |
| Make them **ephemeral**: one job, then destroyed                              | a persistent runner keeps what the last job left behind: files, credentials, processes |
| Run them with **Actions Runner Controller** on Kubernetes, or autoscaling VMs | fresh runners on demand, scaled to the queue                                           |
| Give the machine **least access**                                             | it has whatever network and cloud rights you grant it                                  |
| Keep them **patched**                                                         | you now own the OS, the tools and their CVEs                                           |

The setup itself is short (_Settings → Actions → Runners → New self-hosted runner_ prints the commands);
the work is running them safely afterwards.

A self-hosted runner executes workflow code on infrastructure your organization controls. That enables private
network access or special hardware, but the same access makes untrusted pull requests dangerous. Use isolated,
ephemeral machines for each job, patch their operating system, restrict network and cloud permissions, and remove
the runner after use. Do not treat a persistent runner as a disposable GitHub-hosted machine: files and processes
from one build can affect the next. Measure the operating cost, including maintenance, before assuming self-hosting
is cheaper.

> **Video.** [Self-Hosted GitHub Actions Runners — Power, Cost and Security Risks](https://www.youtube.com/watch?v=MfwjrPJYbBw&t=30s) (Backend Deep Dives)

## Speed and cost

A slow pipeline is paid twice: in runner minutes, and in developers waiting. Measure first: the run summary
shows each job's duration, and expanding a job shows each step's. Then fix the biggest cause:

| Cause                                        | Fix                                                                         |
| -------------------------------------------- | --------------------------------------------------------------------------- |
| Dependencies installed from scratch each run | cache them (lesson 3); `npm ci` with `cache: npm`                           |
| Runs that don't need to happen               | `paths-ignore` for docs; `concurrency` with `cancel-in-progress` on PRs     |
| Everything in one long job                   | split into parallel jobs; run slow jobs only after fast ones pass (`needs`) |
| A slow test suite                            | run tests in parallel or shard them across a matrix                         |
| Rebuilding images from zero                  | Docker layer caching (lesson 6)                                             |
| Hung jobs                                    | `timeout-minutes` on every job (the default is 6 hours)                     |
| Artifacts kept for 90 days                   | `retention-days` you actually need                                          |
| Expensive runners for cheap work             | Linux for anything that doesn't need Windows or macOS                       |

Add one change at a time and compare durations over a few runs: runner speed varies from run to run, so one
fast run proves nothing.

Start by identifying the slowest job or step in the summary. Cache dependencies when the lockfile and runtime
define a safe cache key. Use concurrency cancellation for superseded pull-request runs, and split independent
checks only when the parallel work saves more time than runner startup costs. Put timeouts on jobs that could hang.
Retain artifacts only as long as reviewers or release processes need them. Measure again after each change so you
can keep the improvements that actually reduce wait time or cost.

## Monorepo pipelines: build only what changed

A monorepo keeps many services in one repository. A pull request can change an API and a shared library together.
That keeps their versions in one history, but can make CI slow. If every change builds every service, a one-line
fix waits for work it did not affect.

Ask Git what changed, then build the services that depend on those files. This requires tracking shared-library
dependencies as well as direct service paths. A small repository with two services and a shared library looks like this:

```text
services/api/   services/web/   libs/shared/   docs/
```

```bash
#!/usr/bin/env bash
# affected.sh: print the services a change touches. A change in libs/shared touches every service.
base=${1:-main}
changed=$(git diff --name-only "$base"...HEAD)
if grep -q '^libs/shared/' <<<"$changed"; then ls services; exit; fi
grep -o '^services/[^/]*' <<<"$changed" | cut -d/ -f2 | sort -u
```

```sh
$ git diff --name-only main...HEAD          # branch fix-api
services/api/index.js
$ ./affected.sh
api
$ git diff --name-only main...HEAD          # branch shared-change
libs/shared/index.js
$ ./affected.sh
api
web
$ ./affected.sh                             # branch docs-only: nothing to build
$
```

The three dots matter: `main...HEAD` compares against the point where the branch left main, so commits that
landed on main since then don't count as your changes.

In GitHub Actions, one small job turns that list into JSON, and a matrix fans out over it:

```yaml
jobs:
  changes:
    runs-on: ubuntu-latest
    outputs:
      services: ${{ steps.affected.outputs.services }}
    steps:
      - uses: actions/checkout@v7
        with:
          fetch-depth: 0 # the full history, so the diff has a merge base
      - id: affected
        env:
          BASE: origin/${{ github.base_ref }}
        run: echo "services=$(./affected.sh "$BASE" | python3 -c 'import json,sys; print(json.dumps([l.strip() for l in sys.stdin if l.strip()]))')" >> "$GITHUB_OUTPUT"
  test:
    needs: changes
    if: needs.changes.outputs.services != '[]'
    runs-on: ubuntu-latest
    strategy:
      matrix:
        service: ${{ fromJSON(needs.changes.outputs.services) }}
    steps:
      - uses: actions/checkout@v7
      - run: echo "testing services/${{ matrix.service }}"
```

```sh
$ ./affected.sh | python3 -c 'import json,sys; print(json.dumps([l.strip() for l in sys.stdin if l.strip()]))'
["api", "web"]
$ actionlint && echo clean
clean
```

This is also the answer to the path-filter trap from lesson 3: the `changes` job always runs, so a required
check always reports, and the decision happens inside the pipeline. Once dependencies between packages get
complicated, build tools that know the dependency graph do the same job better: Nx and Turborepo for
JavaScript, Bazel or Pants across languages, with remote caching so a package that didn't change is never
rebuilt anywhere.

Keep the change-detection job as a required status check even when no service needs work. It reports success for
the pull request, while its output controls which matrix jobs run. Test the dependency map with changes to each
service, shared libraries, workflows and documentation. A missed dependency can skip a necessary test; a broad
dependency can waste runner time. When the graph grows beyond simple path rules, use a build tool that models
the graph and can explain why a target is affected.

## DORA metrics: is delivery getting better?

"The pipeline is faster" is a feeling. The DORA research program found four numbers that separate teams that
deliver well from teams that don't, two for speed and two for stability:

| Metric                    | Question                                                     | Measured from                |
| ------------------------- | ------------------------------------------------------------ | ---------------------------- |
| **Deployment frequency**  | how often do we deploy to production?                        | deploy events                |
| **Lead time for changes** | how long from a commit to that commit running in production? | commit time → deploy time    |
| **Change failure rate**   | what share of deploys cause a failure that needs fixing?     | deploys followed by a fix    |
| **Time to restore**       | when a deploy breaks things, how fast is it fixed?           | failed deploy → fix deployed |

The point of measuring all four together: speed bought by skipping tests shows up straight away as a worse
failure rate.

You don't need a product to start. If every production deploy creates a tag (`deploy-001`, `deploy-002`, …)
and fixes start with `hotfix:`, git already holds the data. A short script over two weeks of a test repository:

```python
# dora.py: deploy-* tags are deploys; a "hotfix:" commit marks the deploy before it as failed.
import statistics, subprocess
from datetime import datetime

def git(*args):
    return subprocess.run(["git", *args], capture_output=True, text=True, check=True).stdout.split("\n")

tags = [l.split() for l in git("for-each-ref", "--sort=creatordate", "--format=%(refname:short) %(creatordate:iso-strict)", "refs/tags/deploy-*") if l]
deploys = [(name, datetime.fromisoformat(when)) for name, when in tags]

lead_hours, failed, restore_hours, prev = [], 0, [], None
for i, (name, at) in enumerate(deploys):
    span = f"{prev}..{name}" if prev else name
    for line in filter(None, git("log", "--format=%cI %s", span)):
        when, subject = line.split(" ", 1)
        lead_hours.append((at - datetime.fromisoformat(when)).total_seconds() / 3600)
        if subject.startswith("hotfix:"):
            failed += 1
            restore_hours.append((at - deploys[i - 1][1]).total_seconds() / 3600)
    prev = name

days = (deploys[-1][1] - deploys[0][1]).days + 1
print(f"deploys:               {len(deploys)} in {days} days ({len(deploys) / days * 7:.1f} a week)")
print(f"lead time for changes: median {statistics.median(lead_hours):.1f} h")
print(f"change failure rate:   {failed}/{len(deploys) - failed} = {failed / (len(deploys) - failed):.0%}")
print(f"time to restore:       median {statistics.median(restore_hours):.1f} h")
```

```sh
$ python3 dora.py
deploys:               9 in 11 days (5.7 a week)
lead time for changes: median 3.0 h
change failure rate:   2/7 = 29%
time to restore:       median 1.4 h
```

Two of the seven feature deploys needed a hotfix, and both were fixed within two hours. That's the trade-off the
metrics show: deploying small and often makes each fix quick. Look at the trend month to month, not one number,
and never set the metrics as individual targets: people learn to game deploy counts quickly. In real teams the
deploy events come from the pipeline or Argo CD, and failures from incidents. GitHub, GitLab and tools like
Sleuth or Faros collect them for you.

> **Treat pipelines like a product.** A platform team that owns `ci-templates` gives every service the same tested, secure pipeline: pinned actions, read-only tokens, the standard checks. Services call it and add only what's special about them. Version it, write a changelog, and announce breaking changes, like any library.

> **Video.** [DORA Metrics Explained](https://www.youtube.com/watch?v=YOvEIFLWz3I&t=9s) (Sleuth TV)

## Mission: Turn shop-api's pipeline into a template

Refactor shop-api's CI: move the repeated setup steps into a composite action, move lint, unit and integration into a reusable workflow with inputs and an output, and call it from a ten-line ci.yml. Prove it behaves exactly as before.

- You need: The shop-api repository from the earlier lessons, actionlint
- You'll have: ci.yml calling node-ci.yml, with the same required checks passing

```sh
$ mkdir -p .github/actions/setup-shop
$ nano .github/actions/setup-shop/action.yml    # the composite action from this lesson
$ nano .github/workflows/node-ci.yml            # the reusable workflow
$ nano .github/workflows/ci.yml                 # on: pull_request/push, one job: uses node-ci.yml
$ actionlint && echo "workflows OK"
workflows OK
$ git switch -c ci/reusable && git add .github && git commit -m "ci: reusable workflow and composite action"
$ git push -u origin ci/reusable && gh pr create --fill && gh pr checks --watch
```

The pull request shows `node / lint`, `node / unit` and `node / integration`. Update the ruleset's required
checks to those new names before merging, or the old names wait forever as _Expected_. The setup steps now
live in one file: change the Node version there and every job follows.

## Try it

- Move shop-api's lint, unit and integration jobs into `node-ci.yml` with `on: workflow_call`, and call it from `ci.yml`.
- Create `.github/actions/setup-shop/action.yml` and replace the setup steps in every job with it.
- Remove `shell: bash` from a composite `run:` step and see the run fail, then put it back.
- Open a run's summary and find its slowest job and step from the timings.
- Add `paths-ignore` for docs and `cancel-in-progress` for pull requests, and compare the minutes used over a week.
- Read the self-hosted runner security notes and list what would be exposed on your machine.
- Run `git diff --name-only main...HEAD` on a branch and work out which parts of your project it affects.

## Quiz

1. What is a reusable workflow?
   - A workflow copied into each repository
   - **A workflow with on workflow_call that other workflows run as a job, passing inputs and secrets** (answer)
   - A composite action
   - A scheduled workflow
   Why: One file owns the whole pipeline: jobs, runners, permissions. Fix it once and every caller gets the fix at the version they pin.

2. When is a composite action the better choice than a reusable workflow?
   - Never
   - **When you want to reuse a few steps inside jobs, not a whole set of jobs** (answer)
   - When you need different runners per job
   - For secrets
   Why: Composite actions bundle steps that run inside the caller's job. Reusable workflows bundle whole jobs.

3. What does every run step in a composite action need that a workflow run step doesn't?
   - A name
   - **An explicit shell, such as shell: bash** (answer)
   - An id
   - A timeout
   Why: Composite actions have no default shell. actionlint doesn't catch a missing one, so the run fails instead.

4. Why should self-hosted runners never be used for public repositories?
   - They are too slow
   - **Anyone can open a pull request whose workflow runs code on your machine, inside your network** (answer)
   - GitHub forbids it
   - They cost money
   Why: A persistent runner keeps whatever that code leaves behind for the next job. Use ephemeral runners, and private repositories only.

5. A pipeline takes 14 minutes. What do you do first?
   - Buy bigger runners
   - **Look at the job and step timings to find the slowest part, then fix that** (answer)
   - Delete tests
   - Run it less often
   Why: Usually one step (an install without cache, a serial test suite, a rebuilt image) dominates. Measure, fix the biggest, measure again.

6. In a monorepo, a pull request changes only libs/shared. What should CI build?
   - Nothing, since no service changed
   - Only the shared library
   - **Every service that uses libs/shared** (answer)
   Why: A shared library change can break any service that depends on it. affected.sh printed both api and web for the shared-change branch.

7. A team doubles its deploy count by skipping integration tests. Which DORA metric shows the damage?
   - **Change failure rate** (answer)
   - Deployment frequency
   - Lead time for changes
   Why: The four metrics balance each other: speed bought by cutting checks shows up as more deploys that need a fix.

## Resources

- [GitHub Docs: reusing workflows](https://docs.github.com/en/actions/how-tos/reuse-automations/reuse-workflows) (GitHub Docs)
- [GitHub Docs: creating a composite action](https://docs.github.com/en/actions/tutorials/create-actions/create-a-composite-action) (GitHub Docs)
- [GitHub Docs: self-hosted runners](https://docs.github.com/en/actions/concepts/runners/self-hosted-runners) (GitHub Docs)
- [Actions Runner Controller (ARC)](https://github.com/actions/actions-runner-controller) (GitHub)
- [GitHub Docs: about billing for GitHub Actions](https://docs.github.com/en/billing/concepts/product-billing/github-actions) (GitHub Docs)
