Tips and Tricks #109: Cache Dependencies in GitHub Actions

Speed up CI builds by caching package manager dependencies between runs.

Code Snippet

# .github/workflows/ci.yml
name: CI
on: [push, pull_request]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      
      - name: Cache node modules
        uses: actions/cache@v4
        with:
          path: ~/.npm
          key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
          restore-keys: |
            ${{ runner.os }}-node-
      
      - name: Install dependencies
        run: npm ci
      
      - name: Run tests
        run: npm test

Why This Helps

  • Reduces build time by 50-80%
  • Saves CI minutes and costs
  • Faster feedback loop for developers

How to Test

  • Compare build times with and without cache
  • Check cache hit rate in Actions logs

When to Use

Any CI pipeline with package dependencies. Works for npm, pip, Maven, Gradle, etc.

Performance/Security Notes

Use hashFiles() to invalidate cache when lockfile changes. Set appropriate restore-keys for partial matches.

References


Try this tip in your next project and share your results in the comments!


Discover more from Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.