Optimizing GitHub Actions Speed with Deterministic Dependency Caching
Use `actions/cache` with a deterministic key based on lock file hashes to drastically speed up GitHub Actions workflows by reusing dependencies.
18 Mar 2026, 13:33 UTC

Accelerate Workflow Runs by Caching Dependencies
The primary way to significantly reduce GitHub Actions execution time is by using the actions/cache action to reuse downloaded dependencies (like npm modules or Maven packages) across workflow runs. This avoids redundant download and installation steps.
Implementing Cache Restoration
Cache restoration must occur before any step that installs dependencies within the job. A deterministic cache key is crucial; it must change only when the dependencies themselves change (e.g., when a lock file hash changes).
# .github/workflows/build.yml
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/cache@v4
with:
path: ~/.npm # Example path for npm dependencies
key: ${{ runner.os }}-npm-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-npm-
- run: npm ci # Use 'ci' for clean, reproducible installsCache Key Determinism and Limits
The key must incorporate a hash of the dependency lock file (e.g., package-lock.json). If this hash remains the same, the cache is reused. If the lock file changes, a new key is generated, forcing a fresh download. The restore-keys provide fallback options if the exact primary key doesn't match.
Practical Verification
Run the workflow twice. Check the logs for the actions/cache step; the second run should indicate a cache hit, and the overall job duration should be measurably shorter than the first run.
Common Pitfalls
- Incorrect Order: Placing dependency installation before cache restoration forces redundant downloads.
- Non-Deterministic Keys: Using only the OS or environment variables without locking file hashes leads to cache misses even when dependencies haven't changed.
- Artifact vs. Cache: Remember that
actions/cacheis for dependencies (speeding up setup), whileactions/upload-artifactis for outputs (sharing build results between jobs).
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.