Sub topic 2
Why cache dependencies in CI
This chapter assumes you can read and write a GitHub Actions workflow file, know basic YAML, and have used a package manager such as npm, pip, or Cargo. Later chapters cover the actions/cache syntax. This chapter covers the reasoning: what a cache saves, what it can't save, and how to tell whether it is worth adding.
The problem: every job starts from nothing
GitHub-hosted runners are fresh virtual machines. A job gets a clean machine, runs its steps, and the machine is discarded. Nothing you installed, downloaded, or compiled survives into the next run.
For a typical Node.js project, each run repeats the same work:
- Check out the code.
- Download hundreds of packages from the registry.
- Unpack them and run any install scripts.
- Run the tests.
Step 2 and step 3 rarely change between runs. The lock file is often identical to the one from the previous commit, so you download the same bytes again. Multiply that by every push, every pull request update, and every job in a matrix, and the repetition adds up.
A cache stores files from one run so that a later run can restore them instead of regenerating them.
What caching does
A cache is a saved copy of a directory, stored by GitHub and identified by a string called a key. The cycle has three parts:
- Restore. Early in the job, you ask for a cache by key. If one exists, its files are unpacked onto the runner.
- Work. Your install or build step runs. With the files already present, it has less to do.
- Save. At the end of the job, if the key was not found, the directory is packed and stored under that key for future runs.
The first run after a change is always a miss. It pays the full cost and fills the cache. Later runs with the same key get the benefit.
What to cache and what not to
The best candidates are files that are expensive to produce and cheap to reuse:
- Package manager download caches. For npm this is
~/.npm, for pip it is~/.cache/pip, and for Cargo it is~/.cargo/registry. - Compiled build outputs that a tool can reuse, such as Cargo's
targetdirectory or Gradle's build cache. - Downloaded toolchains or large data files that you fetch from the network on every run.
Be more careful with these:
node_modulesitself. Caching it looks tempting, butnpm cideletesnode_modulesbefore installing, so the restored copy is thrown away. Caching~/.npmletsnpm ciskip the network and still produce a clean install from the lock file.- Anything platform-specific. Compiled native modules built on Linux are not valid on Windows or macOS. This matters once you use a matrix, which a later chapter covers.
- Secrets or credentials. Cache contents can be restored by other workflow runs in the repository. Don't put tokens or private keys in a cached directory.
Measuring before you cache
Caching adds steps, and each step has a cost. Before adding it, measure how long the install takes now. The workflow below times the install step with the shell's time keyword. It works with any project that has a package.json and a package-lock.json.
name: Measure install
on: [push]
jobs:
baseline:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- name: Install dependencies
run: time npm ciOpen the run in the Actions tab and expand the step. The log ends with real, user, and sys lines. real is the wall-clock time, and that is the number to compare against later.
GitHub also shows the duration of each step next to its name, so you can read the number without time. The time output is useful when you want it copied into a pull request description or a comparison table.
When caching helps, and when it doesn't
Caching pays off when the time saved by restoring is greater than the time spent restoring and saving. The restore step has to download the cache archive from GitHub's storage and unpack it. The save step has to pack and upload it.
| Situation | Effect of caching |
|---|---|
| Large dependency tree, install takes 60 seconds or more | Large saving. Restore usually takes a few seconds. |
| Slow or rate-limited registry, or many native builds | Large saving, and fewer failures from network errors. |
| Small project, install takes 5 seconds | Little or no saving. The restore step may take as long as the install. |
| Lock file changes on nearly every commit | Frequent misses. You pay for saving a cache that is rarely reused. |
| Many parallel jobs, each with a different key | Each key must be filled once, so the first run is slower and storage grows. |
A useful rule is to cache when the install or build step is a noticeable share of the total job time, and when the inputs change less often than the code does.
Speed is not the only benefit
Time is the visible gain, but a cache also changes the following:
- Network dependence. Restoring from GitHub's own storage is usually faster and more stable than reaching a third-party registry. A registry outage can still break a cache miss, but hits keep working.
- Cost. On private repositories, minutes on GitHub-hosted runners count against your plan. Shorter jobs use fewer minutes.
- Feedback time. Developers wait for checks before merging. Cutting a four-minute job to two minutes shortens that wait on every pull request.
What a cache doesn't do
Intermediate users often confuse these points, so it helps to state the limits:
- A cache is not guaranteed to exist. GitHub can evict entries, so a workflow must work on a miss. The cache is an optimization, never a requirement. Eviction rules and size limits get their own chapter.
- A cache is not a way to pass files between jobs. Jobs in the same run may start on different machines, and cache entries are keyed for reuse over time, not for handing results from one job to the next. Use artifacts for that. A later chapter compares the two.
- A cache entry is not updated in place. Once a key is saved, its contents are fixed. To store new contents you need a new key. This is why keys are built from file hashes, which the chapter after next covers.
A preview of the mechanism
The next chapters explain each part of this workflow. For now, read it to see where the restore and save sit relative to the install step. The key decides which saved copy you get, and restore-keys provides a fallback.
name: CI
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/cache@v4
with:
path: ~/.npm
key: ${{ runner.os }}-npm-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-npm-
- run: npm ci
- run: npm testThe cache step runs before npm ci, so the install can use any files restored. The save happens automatically in a post step after the job's other steps finish, and only if the job succeeded.
Checklist before adding a cache
- Measure the current install or build time with
timeor the step duration. - Identify the directory that holds reusable files, such as the package manager's download cache.
- Confirm that the directory contains no secrets and is valid for the runner's operating system.
- Decide what input should invalidate the cache. For dependencies, this is usually the lock file.
- After adding the cache, run the workflow twice with no changes. Compare the second run's install time to the baseline.
If the second run is not clearly faster, the cache isn't helping, and you should investigate why or remove it. Reading hit and miss results is covered in a later chapter.
Exercise
A project's npm ci step takes 8 seconds. Restoring a cache of ~/.npm takes 6 seconds, and saving it takes 5 seconds on a miss. The lock file changes on about half of all commits. Is caching likely to help? Give two reasons.
Show answer
Probably not. First, the install is already short, so the best case saves only about 2 seconds (8 seconds minus a 6 second restore), and part of that is lost to the overhead of the extra step. Second, the lock file changes on half the commits, so those runs miss and pay the 5 second save cost with no benefit. The cache would add time on many runs and save little on the others. Measure both before and after to confirm.
Exercise
Why is caching ~/.npm usually better than caching node_modules when you install with npm ci?
Show answer
npm ci deletes node_modules before it installs, so a restored node_modules is removed and wasted. The ~/.npm directory holds downloaded package data that npm ci can read, so it avoids the network downloads while still producing a clean install that matches the lock file.