Skip to content
Latchkey

How to Cache Rust Dependencies and the Target Dir in GitHub Actions

The rust-cache action caches the cargo registry and target/ keyed on Cargo.lock, skipping unchanged compiles.

Use Swatinem/rust-cache after installing the toolchain. It caches ~/.cargo and target/ with a smart key, and prunes stale build artifacts automatically.

Cache the cargo home and target

The action keys on Cargo.lock and the toolchain, so only changed crates recompile.

.github/workflows/ci.yml
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: dtolnay/rust-toolchain@stable
      - uses: Swatinem/rust-cache@v2
        with:
          shared-key: ci
      - run: cargo build --release
      - run: cargo test

Gotchas

  • Caching the whole target/ naively bloats the cache; rust-cache prunes intermediate artifacts so it stays usable - prefer it over a raw actions/cache.
  • A shared-key lets multiple jobs share one cache; omit it and each job key diverges, lowering hit rate.
  • The cache is invalidated on toolchain or Cargo.lock changes - expect a full recompile after a dependency bump.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →