✦ For everyone, free.

Practical knowledge for real and everyday life

Home

13.1.3.3 Pipeline Cache Keys

A focused guide to Pipeline Cache Keys, connecting core concepts with practical Docker and container operations.

Pipeline cache keys determine exactly when a CI platform's native caching mechanism considers a stored cache still valid versus needing to be regenerated, typically derived from a hash of relevant input files so the cache automatically invalidates whenever those specific inputs actually change.

Deriving a Cache Key From Relevant Input Files

A cache key incorporating a hash of dependency lockfiles ensures the cache is reused when dependencies haven't changed, but correctly invalidated when they have.

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

This key changes automatically whenever package-lock.json changes, ensuring a stale dependency cache is never incorrectly reused after a genuine dependency change.

Using Restore Keys for Partial Cache Matches

A restore-keys fallback allows a close, though not exact, cache match to still provide some benefit even when the precise key doesn't match.

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

If no exact match for the current lockfile hash exists, this falls back to the most recent cache matching just the npm- prefix, providing a useful starting point even if not a perfect match.

Why Overly Broad Cache Keys Risk Incorrect Cache Reuse

A cache key that doesn't actually reflect what affects the cached content's validity risks reusing a cache that no longer accurately reflects the current state of relevant inputs.

key: npm-cache

A static key like this would never invalidate, even after a genuine dependency change, risking an incorrect, stale cache being reused indefinitely.

Verifying Cache Hits and Misses

CI logs typically indicate whether a given run's cache lookup found an exact match, a partial match, or no match at all, useful for confirming caching is behaving as intended.

Cache restored from key: npm-a1b2c3d4
Why Pipeline Cache Keys Matter

Correctly deriving cache keys from the actual inputs that determine cache validity is essential for caching to provide genuine speed benefit without risking incorrect, stale cache reuse after a relevant change.