Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 44 ยท GitHub Actions Basics

Caching and Artifacts

Speed up workflows with actions/cache keys and restore-keys, setup-* caching and hashFiles, and pass build output between jobs with upload and download artifacts.

Every job starts on a clean machine, so every run downloads the same dependencies again and throws away the same build output when it ends. Two features fix this, and they solve different problems. A cache saves files you can rebuild (dependencies, compiled objects) to make future runs faster. An artifact saves files you want to keep or hand over (a built package, a test report) so that other jobs, or you can use them.

This lesson shows how cache keys work, why hashFiles is the standard trick, how the setup-* actions cache for you, and how to upload and download artifacts. The workflow snippets are read-only because they depend on GitHub's cache service. The runnable example is a stand-in: a small key-value store that copies the lookup rules, including the prefix fallback. The real service differs in storage, scopes and eviction, but the key logic is the same idea.

Cache or artifact?

Cache Artifact
Purpose Make later runs faster Keep or transfer results
Content Anything reproducible, such as node_modules downloads Build output, reports, logs
Who reads it Future runs of the same repository Later jobs of the same run, or people downloading it
If missing Workflow still works, only slower Workflow may break
Lifetime Evicted when unused for about a week or when the repository limit is reached Retention period, 90 days by default

A good test: if the file disappeared, would the job still be correct? If yes, it is a cache. If no, it is an artifact.

flowchart LR
  subgraph Run1["Run 1"]
    A1["install deps"] --> S1["save cache"]
  end
  subgraph Run2["Run 2 (later)"]
    R2["restore cache"] --> A2["install deps (fast)"]
  end
  S1 -.-> R2
  subgraph Run3["Same run"]
    B1["build job"] --> U["upload artifact"] --> D["download artifact"] --> B2["deploy job"]
  end

Caches connect different runs over time; artifacts connect jobs inside a run.

actions/cache: keys

The official actions/cache action takes a path to save, a key, and optional restore-keys:

YAML
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

How the lookup works:

  1. GitHub looks for a cache whose key is exactly key. If found, it is restored and the action's cache-hit output is true.
  2. If there is no exact match, GitHub tries each line of restore-keys in order, looking for a cache whose key starts with that prefix. If several match, the most recently created one wins. This is a partial hit: files are restored, but cache-hit is false.
  3. If nothing matches, nothing is restored (a miss).
  4. At the end of a successful job, a hidden post step saves the path under key, but only if there was no exact hit. Caches are immutable: a key is written once and never changed.

Because of rule 4, the key should change whenever the content should change. That is the job of hashFiles('**/package-lock.json'): it computes one hash from all matching files, so the key changes exactly when your lock file changes. After you add a dependency, the exact key misses, the prefix in restore-keys restores the previous cache (most packages are still valid), npm ci installs only the difference, and the new cache is saved under the new key.

Put the operating system (runner.os) in the key, plus anything else that changes the content, such as the language version or a matrix value. A cache built on Windows is useless on Linux, and two matrix jobs sharing one key can overwrite each other's work.

Where a cache can be read

A workflow can restore caches created on its own branch, and on its base branch or the default branch as a fallback. A pull request can use the default branch's caches, but two unrelated branches cannot read each other's. This stops one branch from poisoning another. Caches that nobody reads for about seven days are removed, and the repository has a total size limit (10 GB by default), after which the oldest caches go first.

Letting setup actions cache for you

For common ecosystems you rarely need actions/cache directly. The setup-* actions can cache the package manager's download folder and choose the key from the lock file:

YAML
- uses: actions/setup-node@v4
  with:
    node-version: 22
    cache: npm

- uses: actions/setup-python@v5
  with:
    python-version: "3.12"
    cache: pip

- uses: actions/setup-java@v4
  with:
    distribution: temurin
    java-version: 21
    cache: maven

This is shorter and hard to get wrong, so use it first. Reach for actions/cache when you need to cache something the setup action does not know about, such as a build directory, a compiler cache or downloaded test data. The Node and Python variants are used in CI for Node and Python Projects.

Artifacts: upload and download

An artifact is a named bundle of files stored with the run:

YAML
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: npm ci && npm run build
      - uses: actions/upload-artifact@v4
        with:
          name: site-dist
          path: dist/
          retention-days: 7
          if-no-files-found: error

  deploy:
    needs: build
    runs-on: ubuntu-latest
    steps:
      - uses: actions/download-artifact@v4
        with:
          name: site-dist
          path: dist/
      - run: ls dist

Things to know:

  • name identifies the artifact. In the v4 generation of these actions, an artifact name must be unique within a run and an uploaded artifact cannot be changed. In a matrix, put the matrix values in the name (coverage-${{ matrix.os }}) and merge them later if you need one bundle.
  • retention-days overrides the default retention (90 days unless the repository or organization sets another value). Short retention saves storage for large files.
  • if-no-files-found can be warn (default), error or ignore. Use error when an empty upload would mean a broken build.
  • A job that fails still has an artifact if you upload it with if: always() or if: failure(), which is how you keep logs and screenshots from failed tests.
  • A downloaded artifact comes back as plain files; you can also download any artifact from the run page in the browser.
  • Do not upload secrets or .env files. Anyone who can read the repository's runs may be able to download artifacts.

Check the current major version of each action when you copy a workflow: the numbers above were current when this lesson was written, and they move on.

Stand-in: cache lookup with prefix fallback

The model below keeps a list of saved caches, each with a key and a creation order. restore applies the same three rules (exact match, then restore-keys prefixes with the newest match winning, otherwise a miss) and save refuses to overwrite an existing key. The "lock file hash" is a toy checksum, only used to make the key change when the file content changes.

JS Cache keys and restore-keys

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Run 3 shows why restore-keys exists: the exact key is new, yet the cache from run 1 is restored as a starting point, so the install only has to fetch the difference.

Stand-in: choosing a good key

Two keys can both be correct yet behave very differently. A key with no hash never changes, so after the first save it is never updated; a key with a hash that covers too many files changes constantly. The next example counts how many cache saves each strategy causes over a week of commits.

JS How often does a key change?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Hashing only the lock file is the sweet spot: the key changes exactly when the dependencies change, here in two of six commits.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A downloaded build output is needed by a later job in the same run. What should you use?

    Artifacts move files between jobs of a run. A cache is only an optimisation and may be missing, so the job cannot depend on it.
  2. 2. Which cache key changes exactly when package-lock.json changes?

    hashFiles produces a hash of the matching files, so the key stays the same until the lock file content changes.
  3. 3. There is no exact match for key, but a cache named Linux-npm-OLD exists and restore-keys lists Linux-npm-. What happens?

    restore-keys are prefixes tried in order. A partial match restores files but the exact key was not found, so cache-hit is false and the new key is saved afterwards.
  4. 4. What happens when the exact key already exists at the end of a job?

    A key is written once. To update a cache you must produce a new key, which is why the key should include a hash of what defines the contents.
  5. 5. In a matrix, three jobs upload an artifact named coverage. What is the problem?

    Use unique names such as coverage-${{ matrix.os }} and combine the results later if needed.

Summary

  • A cache speeds up future runs with reproducible files; an artifact carries results between jobs or to people. If losing the file breaks correctness, it is not a cache.
  • actions/cache looks for an exact key, then tries restore-keys prefixes (newest match wins), and saves only when there was no exact hit.
  • Build keys from the runner OS and hashFiles of the lock file so they change when, and only when, the contents should.
  • Prefer the built-in cache: option of setup-node, setup-python and setup-java for package managers.
  • upload-artifact and download-artifact use unique names per run; set retention-days and if-no-files-found deliberately and never upload secrets.

Next: Secrets, Variables and Environment Variables