Guides / Cache dependencies
Cache dependencies
Every job starts on a fresh machine with nothing from earlier runs.
Downloading dependencies again each time is slow. The cache step
restores a saved directory at the start of a job and saves it again
when the job ends.
Prerequisites
Section titled “Prerequisites”- A job that downloads dependencies or builds files that can be
reused, such as
node_modules,~/.cargoortarget/. - A lockfile whose contents change when the dependencies change.
-
Choose a key
Section titled “Choose a key”The key names one saved copy. Build it from the lockfile’s hash, so a dependency change makes a new key:
npm-${{ hashFiles('package-lock.json') }}hashFileshashes the files matching its patterns on the machine. -
Add the cache step before the install
Section titled “Add the cache step before the install”.hatchrun/config.yml jobs:test:runs-on: ubuntu-lateststeps:- uses: actions/checkout@v5- cache:key: npm-${{ hashFiles('package-lock.json') }}restore-keys: [npm-]paths: [~/.npm]- run: npm ci- run: npm testkeyis the exact copy to restore, and the name it saves under.restore-keysare prefixes to fall back to, in order, when no copy has the exact key.npm-picks up the newest copy from any earlier lockfile.pathsare the directories to save and restore.
-
Validate
Section titled “Validate”Terminal window hatchrun validate
Expected result: the first run finds nothing and saves the cache when
the job ends. Later runs with the same lockfile restore it before
npm ci.
Examples for other tools
Section titled “Examples for other tools”jobs: rust: runs-on: ubuntu-26.04-4core steps: - uses: actions/checkout@v5 - cache: key: cargo-${{ hashFiles('Cargo.lock') }} restore-keys: [cargo-] paths: [~/.cargo/registry, ~/.cargo/git, target] - run: cargo test python: runs-on: ubuntu-latest steps: - uses: actions/checkout@v5 - cache: key: pip-${{ hashFiles('requirements*.txt') }} paths: [~/.cache/pip] - run: pip install -r requirements.txtcache or actions/cache
Section titled “cache or actions/cache”GitHub’s actions/cache is a uses: step and also appears in
converted configs. The built-in cache step is shorter and needs no
action download. Both are planned to work; pick one per job.
Good to know
Section titled “Good to know”- The
cachestep takeskey,restore-keysandpathsonly. It has noname,iforenv. - Keys and paths can hold expressions, such as
${{ matrix.node }}, so each matrix job keeps its own cache.