Sub topic 13
Runtime budgets, caching, and parallelism
This chapter assumes you can read a GitHub Actions workflow, know what a status check is, and have already sorted checks into pull request, merge, and nightly stages. Placement decides where a check runs. This chapter covers how long each stage may take and how to keep it inside that limit.
Why a stage needs a runtime budget
A runtime budget is the longest a stage may take before you treat it as a problem. Without one, pipelines slow down a little with every added test, and nobody notices until developers stop waiting for results.
Budgets differ by stage because the people waiting differ.
| Stage | Who waits | Typical budget | What happens when it is exceeded |
|---|---|---|---|
| Pull request | The author, who is context-switching | 5 to 10 minutes | Authors push without waiting, batch changes, or ignore results |
| Merge queue or main | The queue, and every PR behind it | 15 to 30 minutes | Queue throughput drops; PRs pile up |
| Nightly | Nobody, until morning | 1 to 3 hours | Results arrive after the team starts work, or runs overlap |
These numbers are starting points. Pick yours by asking how long your team will wait before they stop looking at the result.
Merge queue time deserves extra attention. If each candidate commit takes 20 minutes and the queue runs one at a time, it can land about three changes per hour. Queues can build several candidates in parallel, but a long runtime still limits how fast changes land.
Measure before you optimize
Do not guess where the time goes. Look at three numbers for each workflow:
- Wall-clock time: start of the run to the end. This is what people feel.
- Billable or compute time: the sum of all job durations. This is what you pay for.
- Queue time: how long a job waits for a runner. This is often hidden inside wall-clock time.
Then break one run down by step. A typical Node.js job spends its time like this:
| Step | Time |
|---|---|
| Checkout | 5 s |
| Install dependencies, no cache | 90 s |
| Lint | 30 s |
| Unit tests | 240 s |
| Upload artifacts | 15 s |
Here the biggest costs are tests and installation. Caching attacks the installation. Parallelism attacks the tests. Moving checks between stages attacks both, because the cheapest check is one that does not run on the stage that is blocking someone.
Caching
A cache stores the result of slow, repeatable work so later runs can reuse it. Typical candidates are downloaded dependencies, compiled output, and build tool state.
The three workflows in this tutorial already use the simplest form. The cache: npm option in actions/setup-node stores the npm download cache, keyed on the lockfile. When package-lock.json is unchanged, the next run restores the cache and npm ci skips most downloads.
For finer control, use actions/cache directly:
name: pr-cached
on:
pull_request:
branches: [main]
jobs:
fast-checks:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- uses: actions/cache@v4
with:
path: ~/.npm
key: npm-${{ runner.os }}-${{ hashFiles('package-lock.json') }}
restore-keys: |
npm-${{ runner.os }}-
- run: npm ci
- run: npm run lint
- run: npm testThe key must match exactly for a full hit. If it does not, restore-keys falls back to the most recent cache whose key starts with that prefix. That gives a partial hit: most packages are present and only the changed ones download.
Cache gotchas
- Caches are scoped by branch. In GitHub Actions, a run can restore caches from its own branch and from the base branch, but not from sibling branches. Make sure
mainruns often enough to keep a fresh cache for pull requests to fall back on. The merge workflow, which runs on every push tomain, helps here. - Caches are evicted. GitHub removes entries not accessed for seven days and enforces a per-repository size limit. A nightly job that runs once a day will keep its own cache warm, but a rarely used workflow starts cold.
- A stale or poisoned cache produces confusing failures. If a build passes locally and fails only in CI with odd errors, rerun with the cache disabled or change the key prefix.
- Do not cache what is cheap to regenerate. Restoring a large cache can take longer than rebuilding a small one. Measure restore time as well as save time.
- Do not cache secrets or test results that should be recomputed. Caching test output can hide real failures.
Parallelism
Parallelism runs independent work at the same time. It reduces wall-clock time, but it does not reduce compute time, and it usually increases it because each job repeats checkout and setup.
Parallel jobs
Jobs in one workflow run in parallel unless you declare dependencies with needs. Splitting lint, unit tests, and type checking into separate jobs means the stage takes as long as its slowest job, not the sum. The trade-off is that each job pays setup cost again, and you get more status checks to manage as required checks.
Matrix and sharding
A matrix runs the same job with different values. You can use it for operating systems and language versions, and also to shard a long test suite. Sharding splits one suite into slices that run on separate runners.
name: sharded-tests
on:
pull_request:
branches: [main]
jobs:
unit:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
shard: [1, 2, 3, 4]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- run: npm ci
- run: npx jest --shard=${{ matrix.shard }}/4Jest supports --shard from version 28. With four shards, a 240-second suite takes roughly 60 seconds plus setup. Setup is about 40 seconds with a warm cache, so the real saving is closer to 240 to 100 seconds, not 240 to 60.
Points to watch:
- Diminishing returns. Each shard adds fixed overhead. Past a point, more shards add cost without reducing time.
- Uneven shards. Splitting by file count can leave one shard with all the slow tests. Some tools can balance by recorded timings.
fail-fast. The default,true, cancels the other matrix jobs when one fails. That saves compute, but you lose the failure information from the rest. For test shards,falseis usually better on pull requests because the author sees every failure in one run.- Required check names. Each matrix entry becomes its own check name, such as
unit (1). If you require them individually in branch protection, changing the shard count breaks the rule. A common fix is a final job thatneedsthe matrix and acts as the single required check.
unit-result:
if: always()
needs: unit
runs-on: ubuntu-latest
steps:
- run: |
if [ "${{ needs.unit.result }}" != "success" ]; then
echo "Unit tests did not succeed: ${{ needs.unit.result }}"
exit 1
fiPlace that job under jobs: in the same file as the matrix. The if: always() matters. Without it, a failed unit job causes unit-result to be skipped, and a skipped required check can be treated as passing or as pending forever, depending on your settings.
Other ways to spend less time
- Cancel superseded runs. When an author pushes again, the earlier run is wasted. Add a concurrency group:
concurrency:
group: pr-${{ github.event.pull_request.number }}
cancel-in-progress: trueUse this on pull request workflows. Do not use cancel-in-progress on main pushes or nightly runs, where you want every run to complete and report.
- Set
timeout-minuteson every job. The default is 360 minutes, so a hung test can hold a runner for six hours. The nightly example sets 120 minutes; give pull request jobs a much lower limit, such as 15. - Fail fast inside the job. Order steps so cheap checks run first. A lint failure in 30 seconds beats waiting four minutes for tests that were going to be thrown away.
- Use path filters, covered earlier, so documentation-only changes skip the test jobs.
- Use larger runners for hot paths. A runner with more cores can cut a CPU-bound build in half. It costs more per minute, so compare the total cost, not the rate.
Cost and trade-offs
Speed and cost pull against each other. Use this table to reason about each lever.
| Lever | Wall-clock effect | Compute cost effect | Main risk |
|---|---|---|---|
| Dependency cache | Lower | Lower | Stale cache, eviction |
| Sharding | Much lower | Higher | Uneven shards, many check names |
| Parallel jobs | Lower | Slightly higher | Repeated setup |
| Concurrency cancel | None per run | Lower | Cancelling a run you wanted to see |
| Moving a check to nightly | Lower for PRs | Same or lower | Later failure detection |
| Larger runner | Lower | Depends | Higher per-minute price |
A good rule is to pay for parallelism on the pull request stage, where human time is the expensive resource, and to stay frugal on the nightly stage, where nobody is waiting. A nightly run can use one big serial job with a generous timeout.
Keeping the budget honest
Budgets drift. Add a recurring habit:
- Record the median and the 90th percentile run time of each workflow. The 90th percentile shows the slow runs people remember.
- Set an alert or a review trigger when the median passes the budget, for example 80 percent of the limit.
- When a stage is over budget, apply the levers in order: cache, then parallelize, then move checks to a later stage.
- Watch for retries. A job that passes only after a rerun costs double and signals a flaky test, which is a placement and quarantine problem, not a speed problem.
The next chapter ties these measurements back to placement decisions: when runtime, failure, and escape data say a check should move.
Exercise
A pull request workflow has one job. Step times are: checkout 5 s, npm ci with no cache 100 s, lint 30 s, unit tests 300 s. The budget is 5 minutes (300 s). Name two changes that bring wall-clock time under the budget, and say which one raises compute time.
Show answer
Add dependency caching (for example cache: npm) so npm ci drops to roughly 20 s on a hit; this lowers both wall-clock and compute time. Then shard the unit tests into four jobs with a matrix; each shard takes about 75 s of tests plus about 25 s of checkout and warm install, so the longest job is near 100 s, and lint can run in a separate parallel job. Sharding raises compute time because every shard repeats checkout and install. Caching alone gives about 355 s, which is still over budget, so sharding (or moving slow tests to the merge stage) is also needed.
Exercise
Your sharded unit matrix jobs are all required checks by name. Why is changing from four shards to six risky, and what is the fix?
Show answer
Each matrix entry is its own check name. After the change, unit (5) and unit (6) exist but unit (1) to unit (4) may still be required under their old names, or the new names are not required at all, so merges either block on checks that never report or skip checks that should gate. The fix is an aggregate job that uses needs: unit and if: always(), fails unless the matrix result is success, and is the only check listed in branch protection.