Swatinem/rust-cache
Smart caching for cargo builds with sensible defaults, one step, no key wrangling.
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
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
with:
shared-key: ci
- run: cargo test --all-featuresInputs
| Input | Description | Default | Required |
|---|---|---|---|
prefix-key | The prefix cache key; change it to start a new cache manually. | v0-rust | No |
shared-key | A cache key used instead of the automatic job-based key, stable over multiple jobs. | - | No |
key | An additional cache key added alongside the automatic job-based key to further differentiate jobs. | - | No |
workspaces | Paths to multiple Cargo workspaces and their target directories, separated by newlines. | - | No |
cache-directories | Additional non-workspace directories to be cached, separated by newlines. | - | No |
cache-on-failure | Cache even if the build fails. | - | No |
cache-all-crates | If true, all crates are cached; otherwise only dependent crates. | false | No |
save-if | Whether the cache should be saved. If false, the cache is only restored. | true | No |
Outputs
| Output | Description |
|---|---|
cache-hit | Boolean 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-keyor bumpprefix-keyto 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?
cache-all-crates / cache-workspace-crates widen what is kept.