Sub topic 4
Building Cache Keys with hashFiles
A cache key is the name actions/cache uses to look up a saved cache. If the key is too stable, jobs restore stale dependencies. If it changes on every run, jobs never get a hit. hashFiles lets you build a key that changes exactly when your dependency inputs change.
Prerequisites
This chapter assumes you can read a workflow file and have used actions/cache once, as in the previous chapter. You should also know how expressions such as ${{ runner.os }} work, and what a lock file is in npm, pip, or Cargo.
What a key has to do
On a cache step, the action compares your key with the keys of stored caches. If one matches exactly, it restores that cache and reports a hit. If none matches, the step does nothing, and a post-job step saves the path contents under that key when the job succeeds.
Dependency caches should therefore follow a simple rule:
- The same dependency inputs should produce the same key, so the cache is reused.
- Different dependency inputs should produce a different key, so a stale cache is not reused.
The lock file describes your dependency inputs, so a hash of the lock file does both jobs.
The standard key
This is the pattern used in most dependency caches.
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') }}
- run: npm ci
- run: npm testThe key has three parts:
${{ runner.os }}isLinux,Windows, ormacOS. Native modules and cache paths differ by system, so caches should not cross operating systems.npmis a literal prefix naming the tool. It keeps this cache apart from other caches in the same repository.hashFiles('**/package-lock.json')is a hash of the lock file's contents.
A resulting key looks like Linux-npm-3f1c9a..., where the hash is 64 hexadecimal characters. Editing the lock file, for example by upgrading a package, yields a new hash. The next run then misses, installs fresh, and saves a new cache.
The step order matters. The cache step must come after actions/checkout. Otherwise the lock file is not on the runner yet and the hash is computed over nothing.
How hashFiles works
hashFiles is a built-in function that is available in workflow expressions. It does the following:
- It takes one or more glob patterns, separated by commas.
- It resolves the patterns relative to the workspace directory (
GITHUB_WORKSPACE), which is where checkout places your repository. - It computes a SHA-256 hash of each matching file, then a combined hash of those results.
- It returns an empty string when nothing matches.
The empty-string case is the most common trap. If the pattern is wrong, the key silently becomes Linux-npm-. Every run then uses the same key, the first saved cache is never replaced, and dependencies drift out of date.
Hashing the right files
Choose files that fully determine what gets downloaded. Prefer lock files over manifests, because a manifest such as package.json can stay unchanged while resolved versions change.
| Ecosystem | Cached path | Files to hash |
|---|---|---|
| npm | `~/.npm` | `**/package-lock.json` |
| pip | `~/.cache/pip` | `**/requirements*.txt` |
| Cargo | `~/.cargo/registry` | `**/Cargo.lock` |
| Gradle | `~/.gradle/caches` | `**/*.gradle*`, `**/gradle-wrapper.properties` |
The ** prefix finds the file in any subdirectory, which suits monorepos with several lock files. If you have only one lock file in the repository root, package-lock.json is faster and more precise.
Several files in one key
List extra patterns as separate arguments. A change to any one file changes the key.
name: Python CI
on: [push]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/cache@v4
with:
path: ~/.cache/pip
key: ${{ runner.os }}-pip-${{ hashFiles('requirements.txt', 'requirements-dev.txt') }}
- run: pip install -r requirements.txt -r requirements-dev.txt
- run: python --versionIf a listed file is missing, hashFiles hashes only those that exist. If none exist, you get the empty string.
Excluding paths
A broad pattern such as **/package-lock.json can also match files inside node_modules, because installed packages sometimes ship their own lock files. The hash then changes depending on whether node_modules exists. Exclude those paths with a leading !.
key: ${{ runner.os }}-npm-${{ hashFiles('**/package-lock.json', '!**/node_modules/**') }}Broad patterns are also slow on large trees. hashFiles fails if it runs for more than 120 seconds, so narrow the pattern when a repository is big.
Checking the hash
Add a temporary step to print what the expression resolves to.
- name: Show cache key inputs
run: |
echo "os=${{ runner.os }}"
echo "hash=${{ hashFiles('**/package-lock.json') }}"If hash= is empty, the glob did not match. Check the file name, its case (patterns are case-sensitive on Linux runners), and whether checkout ran earlier.
Controlling the key by hand
Sometimes you need to throw away caches without changing any lock file, for example when a cache holds corrupt data. Because the key is just a string, add a version segment and bump it.
name: CI
on: [push]
env:
CACHE_VERSION: v1
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/cache@v4
with:
path: ~/.npm
key: ${{ env.CACHE_VERSION }}-${{ runner.os }}-npm-${{ hashFiles('**/package-lock.json') }}
- run: npm ciChanging v1 to v2 makes every key new, so the next run misses and writes fresh caches.
Common key mistakes
- Using
github.shain the key. The commit SHA is unique per commit, so each run gets a new key and never hits. Use it only when you really want one cache per commit. - Hashing source code. Source files change on almost every commit. Hash only what controls dependencies.
- Leaving out the operating system. A cache built on Linux may hold paths or binaries that fail on Windows.
- Forgetting that caches are immutable. A saved cache cannot be overwritten. When the key already exists, the save is skipped, so a key that does not change keeps its first contents forever.
- Exceeding limits. A key can be at most 512 characters and cannot contain commas.
Summary of the pattern
Build the key from stable, human-readable parts followed by a content hash: environment (runner.os), purpose (npm), and the hash of the files that define your dependencies. Verify the hash is not empty, narrow the glob when needed, and add a version segment as a manual reset.
Exercise
A workflow caches ~/.npm with the key ${{ runner.os }}-npm-${{ hashFiles('package-lock.jsn') }}. Runs always report a cache hit, but the installed packages are out of date after the team upgrades a dependency. What is wrong, and how do you fix it?
Show answer
The file name is misspelled (.jsn), so no file matches and hashFiles returns an empty string. The key is always Linux-npm-. After the first run saves a cache under that key, every later run hits it, and because caches are immutable the cache is never updated. Fix the pattern to package-lock.json (or **/package-lock.json). Then print hashFiles(...) in a debug step to confirm it is non-empty. The new key will miss once, install fresh, and save a correct cache.