Sub topic 4
Fan-out and fan-in: combining parallel and sequential jobs
This chapter assumes you can read a workflow file and know that needs makes one job wait for another. You should also know that each job runs on its own runner.
The pattern
Most pipelines combine both ideas. Several independent jobs start together (fan-out). A later job waits for all of them (fan-in). Linting and testing don't depend on each other, so they run side by side. Building only makes sense once both pass.
You create fan-out by giving several jobs the same upstream job, or no upstream job at all. You create fan-in by listing several jobs in one needs array.
A complete example
name: CI
on: [push]
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: npm ci
- run: npm run lint
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: npm ci
- run: npm test
build:
needs: [lint, test]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: npm ci
- run: npm run build
deploy:
needs: build
runs-on: ubuntu-latest
steps:
- run: echo "Deploying"lint and test have no needs, so they start at the same time. build waits for both. deploy waits for build.
How the timing works
The workflow's total time follows the longest path through the graph, not the sum of all jobs. Suppose lint takes 1 minute, test takes 4, build takes 2, and deploy takes 1.
| Layout | Total time |
|---|---|
| All four jobs in sequence | 8 minutes |
| lint and test in parallel | 4 + 2 + 1 = 7 minutes |
The fan-in job starts only when the slowest of its dependencies finishes. Speeding up lint would not help here, because test is the bottleneck.
Why `build` repeats checkout and install
build runs actions/checkout and npm ci again. Each job gets a fresh runner, and files from lint and test are not there. Ordering jobs with needs does not carry over the filesystem. To pass files forward, use artifacts, which a later chapter covers.
Rules for fan-in
needsaccepts a single job ID or an array.needs: buildandneeds: [build]mean the same thing.- A fan-in job runs only if every listed job succeeded. If
lintfails,buildanddeployare skipped, even iftestpassed. - A job can be both a fan-in point and a fan-out source. Two jobs could each declare
needs: buildand run in parallel after it.
Common mistakes
- Listing a job ID that doesn't exist or is misspelled. The workflow is rejected when it is parsed.
- Assuming the order of jobs in the file controls execution order. Only
needsdoes. - Adding
needsbetween jobs that are actually independent. This turns parallel work into a slower chain.
Exercise
A workflow has jobs a, b, c, and d. Job c has needs: [a, b], and d has needs: c. Job a takes 3 minutes, b takes 5, c takes 2, and d takes 1. How long does the workflow take if everything succeeds, and which jobs run at the same time?
Show answer
It takes 5 + 2 + 1 = 8 minutes. Jobs a and b run at the same time. c starts when b finishes at minute 5, then d runs after c.