CodeBlanks Logo Icon CodeBlanks

cache

Learn to speed up with dependency caching.

Caching dependencies

Downloading external libraries on every CI run slows down pipeline execution significantly. The actions/cache action saves downloaded package directories on GitHub runners for subsequent runs. This allows workflows to complete in seconds rather than minutes.

- uses: actions/cache@v4
  with:
    path: ~/.npm
    key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}

On a cache hit, dependencies are restored from disk without downloading again.

Cache key and restore-keys

To keep the cache fresh, a checksum of the lockfile (hashFiles) is typically included in the key parameter. If a dependency changes, the hash updates and a new cache is generated. If an exact match isn't found, restore-keys restores the closest previous cache.

with:
  path: ~/.npm
  key: node-cache-${{ hashFiles('package-lock.json') }}
  restore-keys: |
    node-cache-

This structure minimizes full download overhead.

Practice Add cache step to workflow

Add the actions/cache@v4 step to the workflow with path: ~/.npm and key: npm-cache.

Starter code

terminal
cat << 'EOF' > .github/workflows/ci.yml
steps:
  - uses: actions/checkout@v4
  # onbellek adimini buraya ekle
EOF

cat .github/workflows/ci.yml

Sample solution

terminal
cat << 'EOF' > .github/workflows/ci.yml
steps:
  - uses: actions/checkout@v4
  - uses: actions/cache@v4
    with:
      path: ~/.npm
      key: npm-cache
EOF

cat .github/workflows/ci.yml

Expected output

steps:
  - uses: actions/checkout@v4
  - uses: actions/cache@v4
    with:
      path: ~/.npm
      key: npm-cache

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the main benefit of using actions/cache in CI workflows?

  • Automatically sharing secret keys with third parties
  • Eliminating dependency download time to speed up workflows Correct answer
  • Automatically marking failed tests as passed
  • Permanently reducing repo size on the server

Explanation: Caching saves packages and avoids re-downloading them, significantly reducing workflow execution time.

2 Invoke cache action

Question
      - uses: actions/____@v4
Answer
      - uses: actions/cache@v4

Explanation: The official actions/cache@v4 action is used to cache dependencies.

3 Cache parameters

Term Meaning
actions/cache Saves dependencies to speed up runs
key Unique identifier of the cache
restore-keys Fallback cache if no exact match
hashFiles Generates hash of lockfile

All lessons in Advanced