AI Hints
Home›CI/CD with GitHub Actions Tutorial›Matrix Options and Caching
CI/CD with GitHub Actions · Lesson 51 of 138

Caching Dependencies

Faster installs.

⏱ 2 min read▶ Video at 57:42🎓 Free
Watch this lesson in the CI/CD with GitHub Actions courseWatch on YouTube ↗Full CI/CD with GitHub Actions course

Every run starts on a clean machine, so it downloads all your dependencies again. For a big project, that can take minutes, every time. A cache saves the downloaded files, and restores them in the next run.

Caching Dependencies
From the video: Caching Dependencies
  • Clean machines download everything
  • Minutes every run
  • A cache restores them

actions/cache

The cache action needs a path, the folder to save, and a key, its name. The key includes hash files of the requirements file. If the requirements change, the hash changes, so a fresh cache is made. Restore keys allow a near match, if there's no exact one.

cache.ymlyaml
- uses: actions/cache@v4
  with:
    path: ~/.cache/pip
    key: pip-${{ runner.os }}-${{ hashFiles('requirements.txt') }}
    restore-keys: |
      pip-${{ runner.os }}-

Why the key uses a hash

Hash files works like the s h a two five six sum command. Here's the fingerprint of requirements dot txt. Add one package, and the fingerprint is completely different. So the cache key changes exactly when the dependencies change, and never otherwise.

Terminal
sha256sum requirements.txt | cut -c1-16
8173d01f246381b6
echo requests >> requirements.txt && sha256sum requirements.txt | cut -c1-16
8524debf21b28108

Summary

Caching saves dependency downloads between runs. The key uses a hash of the requirements, so it changes only when they change. Next, saving files from a run, with artifacts.

Key takeaways
  • actions/cache
  • key with hashFiles()
  • restore-keys
Next up: Artifacts — files from a run