Caching and Artifacts

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Two features keep workflows fast and let jobs cooperate, and they are easy to confuse. A cache stores files that are expensive to recreate (downloaded dependencies, compiled output) so a later run can skip the work; it is a best-effort optimisation and a miss must never break the build. An artifact stores files that a run produces and that someone or something will consume (a test report, a built site, a binary); it is an output of the run and is guaranteed to be there until it expires. This page covers both, using this documentation site’s Antora build as the worked example. Versions (actions/cache@v6, actions/upload-artifact@v7, actions/download-artifact@v8) were verified on 2026-11-10; the official docs win on any discrepancy. The Docker image cache is covered on Docker CI/CD with GitHub Actions.

flowchart LR subgraph "Job build" R["Restore cache by key"] --> B["Build and test"] B --> S["Save cache if it was a miss"] B --> U["Upload artifact"] end subgraph "Job deploy" D["Download artifact"] --> P["Publish"] end U --> D

Dependency caching with actions/cache

- uses: actions/cache@v6
  id: npm-cache
  with:
    path: ~/.npm
    key: npm-${{ runner.os }}-${{ hashFiles('package-lock.json') }}
    restore-keys: |
      npm-${{ runner.os }}-
Input Meaning

path

One or more files, directories or globs to save and restore (multi-line list allowed). Use ~ for the runner home.

key

Exact key. If a cache with this key exists in scope, it is restored (an exact hit) and the post step does not save.

restore-keys

Ordered list of key prefixes tried when the exact key misses; the most recent match wins. The job still saves a new cache under key at the end.

enableCrossOsArchive

Allow a cache saved on one OS to be restored on another (Windows paths excepted).

fail-on-cache-miss, lookup-only

Fail when no entry is found, or only check for existence without downloading.

The action sets cache-hit to 'true' for an exact key match, and to 'false' when only a restore-keys prefix matched or nothing matched. Use it to skip install steps:

- run: npm ci
  if: steps.npm-cache.outputs.cache-hit != 'true'

Choosing keys

  • Put everything that invalidates the cache into the key: the OS, the toolchain version and a hash of the lock file. hashFiles('**/package-lock.json') returns a SHA-256 over the matching files, or an empty string when none match (a silent bug: the key then ends in a dash).

  • Cache the package manager’s download cache (~/.npm, ~/.m2/repository, ~/.gradle/caches, ~/.cache/pip), not node_modules: npm ci deletes node_modules anyway and a restored tree can hide a lock file mismatch.

  • Keep restore-keys prefixes ordered from most to least specific. A partial restore plus an incremental install is almost always faster than a cold one.

  • Caches are immutable: a key is written once. To refresh a cache, change the key (for example by including the week number or a manual v2 prefix).

Scope and branch isolation

A cache is available to a workflow run according to the branch it was created on:

Running on Can restore caches created on

A branch

That branch, then the default branch.

A pull request (pull_request)

The merge ref of the PR itself, the base branch, then the default branch.

A tag

Caches created for that tag ref, then the default branch.

Sibling branches never see each other’s caches, so a cache saved on feature/a cannot be read from feature/b. This is a security property as much as a performance one. The practical consequence is that the default branch should regularly produce warm caches (a nightly or push-to-main build), because every feature branch and PR falls back to them. See Branches for the branch model.

Eviction and limits

Each repository has a total cache budget; the default is 10 GB, and organisation or repository admins can raise it in settings. When the budget is exceeded, GitHub evicts the least recently used entries, and entries that have not been accessed for several days are removed as well. Because eviction is silent, never rely on a cache being present. List and delete entries with the CLI:

gh cache list --limit 20
gh cache delete npm-Linux-1a2b3c4d5e6f
gh cache delete --all

Built-in caching in the setup actions

The language setup actions can manage the cache for you, deriving the key from the OS, the toolchain and the lock file:

- uses: actions/setup-node@v7
  with:
    node-version: 24
    cache: npm                  # or yarn, pnpm; uses package-lock.json by default
    cache-dependency-path: package-lock.json

- uses: actions/setup-java@v6
  with:
    distribution: temurin
    java-version: 21
    cache: maven                # or gradle

- uses: actions/setup-python@v7
  with:
    python-version: '3.12'
    cache: pip                  # also pipenv and poetry
Action cache: values Hashes by default

setup-node

npm, yarn, pnpm

The lock file of that manager.

setup-java

maven, gradle, sbt

pom.xml, *.gradle* and wrapper properties files.

setup-python

pip, pipenv, poetry

requirements.txt (or the Pipfile or poetry lock file).

For Gradle builds prefer gradle/actions/setup-gradle@v6, which caches the Gradle User Home with a smarter policy (it saves from the default branch by default and restores read-only elsewhere) and publishes a build summary:

- uses: actions/setup-java@v6
  with: { distribution: temurin, java-version: 21 }
- uses: gradle/actions/setup-gradle@v6
- run: ./gradlew build

For Docker, use BuildKit’s GitHub cache backend with cache-from: type=gha and cache-to: type=gha,mode=max in docker/build-push-action; the details are on Docker CI/CD with GitHub Actions.

Restore and save as separate steps

actions/cache restores at the start and saves in a post step, but only when the job succeeds. Two sub-actions split the halves for finer control:

- id: restore
  uses: actions/cache/restore@v6
  with:
    path: .gradle-cache
    key: deps-${{ hashFiles('**/*.gradle*') }}
    restore-keys: deps-

- run: ./gradlew build

- uses: actions/cache/save@v6
  if: always() && steps.restore.outputs.cache-hit != 'true'
  with:
    path: .gradle-cache
    key: deps-${{ hashFiles('**/*.gradle*') }}

Typical uses: save even when the build or tests fail (if: always()), let only the default branch save while every branch restores, or restore in many matrix jobs and save from one.

Cache poisoning

A cache is an input to your build, so anyone who can write to it can influence what you build. Keep these rules:

  • Never restore a cache populated by untrusted code into a privileged job. Workflows triggered by pull_request_target or workflow_run run with write tokens and secrets; do not let them restore a cache that a fork’s pull request could have created.

  • Do not cache anything you would execute directly (compiled tools, node_modules/.bin) in release jobs; cache downloads that package managers verify against a lock file or checksums.

  • Release builds should build clean or use caches saved only from protected branches, as the setup-gradle default does.

  • Treat a cache key as public: do not include secrets in keys, and do not store credentials in cached paths.

More on these trust boundaries is on Security Hardening.

Artifacts

An artifact is a named archive uploaded at the end of a job and downloadable from the run page, the API, the CLI, or a later job.

- uses: actions/upload-artifact@v7
  with:
    name: docs-site
    path: build/site
    if-no-files-found: error
    retention-days: 7
    compression-level: 6

- uses: actions/download-artifact@v8
  with:
    name: docs-site
    path: site
Input Meaning

name

Artifact name, unique within the run (see below). Default is artifact.

path

File, directory or glob (multi-line); exclusions with a leading !.

retention-days

1 to 90 days, capped by the repository or organisation retention setting. Default comes from that setting (90 days unless changed).

if-no-files-found

warn (default), error or ignore.

include-hidden-files

Hidden files (names starting with a dot) are excluded unless set to true.

overwrite

Replace an existing artifact of the same name (it is deleted and recreated, not appended to).

compression-level

0 (none, for already compressed files) to 9.

Immutability and naming (v4 and later)

Since the v4 generation, artifacts are immutable: a given name can be uploaded once per workflow run, and two jobs uploading the same name make the second fail. Consequences:

  • Matrix jobs must use distinct names, for example name: test-results-${{ matrix.os }}.

  • To combine them later, download with a pattern and merge:

- uses: actions/download-artifact@v8
  with:
    pattern: test-results-*
    merge-multiple: true
    path: all-results
  • actions/upload-artifact/merge@v7 merges several artifacts into one new artifact.

  • overwrite: true is the only way to replace an artifact; it deletes the previous one first.

  • Download without name and the action downloads every artifact of the run, each into its own subdirectory unless merge-multiple is set. To download from another run, pass run-id and a github-token.

Passing build outputs between jobs

Jobs run on different machines, so the file system is not shared. Upload in the producer, download in the consumer, and use needs to order them:

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - run: ./build.sh
      - uses: actions/upload-artifact@v7
        with: { name: dist, path: dist/ }
  verify:
    needs: build
    runs-on: ubuntu-latest
    steps:
      - uses: actions/download-artifact@v8
        with: { name: dist, path: dist }
      - run: ./verify.sh dist

Small values (a version string, a path) belong in job outputs rather than artifacts; see Jobs, Steps and Matrix.

Storage, retention and the CLI

Artifacts count against your plan’s storage quota until they expire, so set retention-days deliberately: a day or two for scratch hand-offs between jobs, longer for release binaries you want to keep, or publish those as release assets instead. Artifacts are also available after the run:

gh run list --workflow publish.yml --limit 5
gh run download 1234567890 --name docs-site --dir ./site
gh run download 1234567890 --pattern 'test-results-*'
gh api repos/albertoirurueta/docs/actions/artifacts --jq '.artifacts[] | [.id, .name, .expired] | @tsv'

Artifact or cache?

Question Cache Artifact

Purpose

Speed up the next run by reusing downloads or intermediates.

Hand results to another job, a person, or a release.

Guaranteed to exist?

No; best effort, evictable.

Yes, until the retention period ends.

Mutable?

No; key written once, new key to update.

No; one upload per name per run (overwrite deletes and recreates).

Scope

By branch, readable from the base and default branches.

One workflow run (cross-run download needs run-id).

Visible in UI?

Settings, then Actions, then Caches.

Run summary page, downloadable by anyone with read access.

Lifetime

Evicted when unused or over budget.

Up to 90 days by default.

Example: the Antora docs site

The site’s publish workflow reinstalls Antora with npm i on every nightly run. Caching npm’s download cache and publishing the built site as an artifact would look like this (this is a proposal, not what the workflow does today):

name: publish
on:
  schedule:
    - cron: '0 3 * * *'
  workflow_dispatch:

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-node@v7
        with:
          node-version: 24
          cache: npm
      - run: npm ci
      - run: npx antora antora-playbook.yml
      - uses: actions/upload-artifact@v7
        with:
          name: docs-site
          path: build/site
          retention-days: 7

  deploy:
    needs: build
    runs-on: ubuntu-latest
    steps:
      - uses: actions/download-artifact@v8
        with:
          name: docs-site
          path: build/site
      - uses: crazy-max/ghaction-github-pages@v5
        with:
          target_branch: gh-pages
          build_dir: ./build/site
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

This presumes a package-lock.json is committed (today the workflow installs packages ad hoc, so there is nothing to hash). Splitting build and deploy also lets the deploy job use an environment with its own protection rules; see Environments and Deployments.

Common mistakes

  • Using hashFiles on a path that does not exist, producing a key that never changes.

  • Caching node_modules or build output instead of the package manager’s download cache.

  • Uploading the same artifact name from every matrix job (fails since v4); add the matrix value to the name.

  • Expecting a branch to read a sibling branch’s cache.

  • Treating a cache as authoritative: the build must work on a miss.

  • Forgetting that hidden files are skipped by upload-artifact unless include-hidden-files: true.

  • Leaving credentials or .env files inside an uploaded path; artifacts are readable by everyone with repository read access.