Skip to content
Latchkey

Swatinem/rust-cache

Smart caching for cargo builds with sensible defaults, one step, no key wrangling.

Community actionCategory: CachingLatest v2View on GitHub

What it does

Swatinem/rust-cache caches ~/.cargo (registry, git deps) and the workspace target directory, keying automatically on the job, rustc version, Cargo.lock/Cargo.toml hashes, and relevant env vars.

It prunes stale dependencies on save, so caches stay useful instead of growing without bound like a naive actions/cache setup.

Usage

workflow (.yml)
steps:
  - uses: actions/checkout@v4
  - uses: dtolnay/rust-toolchain@stable
  - uses: Swatinem/rust-cache@v2
    with:
      shared-key: ci
  - run: cargo test --all-features

Inputs

InputDescriptionDefaultRequired
prefix-keyThe prefix cache key; change it to start a new cache manually.v0-rustNo
shared-keyA cache key used instead of the automatic job-based key, stable over multiple jobs.-No
keyAn additional cache key added alongside the automatic job-based key to further differentiate jobs.-No
workspacesPaths to multiple Cargo workspaces and their target directories, separated by newlines.-No
cache-directoriesAdditional non-workspace directories to be cached, separated by newlines.-No
cache-on-failureCache even if the build fails.-No
cache-all-cratesIf true, all crates are cached; otherwise only dependent crates.falseNo
save-ifWhether the cache should be saved. If false, the cache is only restored.trueNo

Outputs

OutputDescription
cache-hitBoolean indicating an exact cache-key match was found.

Notes

Install the Rust toolchain before this step, the cache key includes the rustc version, so running it first keys against the wrong toolchain.

Use shared-key to share one cache across jobs (e.g. test + clippy) instead of building separate caches per job.

Set save-if: ${{ github.ref == 'refs/heads/main' }} to restore on PRs but only write the cache from main, avoiding cache-quota churn.

Common errors

  • Constant cache misses usually mean the toolchain step runs after rust-cache, or a file hashed into the key (Cargo.lock, rust-toolchain) changes every run.
  • Hitting the repository 10 GB cache quota causes GitHub to evict older entries; reduce parallel per-job caches with shared-key or bump prefix-key to reset.

Security and pinning

  • Pin to a commit SHA, the action runs in every job and handles your build directories.
  • Caches are restorable across branches from the default branch; do not bake secrets into cached directories.

Alternatives and related

Frequently asked questions

Why does rust-cache not speed up my own crate compilation?
By design it caches dependencies, not your workspace crates, those recompile on every change anyway. cache-all-crates / cache-workspace-crates widen what is kept.
Running Swatinem/rust-cache? Run it on Latchkey managed runners - self-healing and caching included. Start free → 30-day trial · No credit card