Skip to content
Latchkey

How to Cache the Rust target Directory in GitHub Actions

Rust compiles are slow, and a cold target directory means recompiling every dependency on every run.

Cache ~/.cargo/registry, ~/.cargo/git, and target/, keyed on Cargo.lock. The community Swatinem/rust-cache action wires this up with sensible defaults.

Steps

  • Check out the repo and install the toolchain.
  • Add Swatinem/rust-cache (or a manual actions/cache covering the cargo dirs and target/).
  • Let the action key on Cargo.lock and the compiler version automatically.
  • Run your cargo build or cargo test after the cache restores.

Workflow

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

Gotchas

  • A huge target/ can blow the 10 GB per-repo cache budget; cache only the workspace you test.
  • Changing the toolchain version should bust the cache, which rust-cache handles for you.
  • Latchkey persists the target directory between runs so Rust pipelines start warm and recover from flakes automatically.

Related guides

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