Sub topic 13
Caching Builds in CI
CI machines usually start from a clean checkout. Without a cache, every run downloads and compiles all dependencies again. For most Rust projects that is the largest part of CI time. This chapter covers what to cache, what to leave out, and the failure modes that make caches slow or wrong.
This chapter assumes you know how to build and test with Cargo, can read a CI workflow file, and have read the earlier chapters on profiles, incremental compilation, and sccache.
What a CI build spends its time on
A cold CI build does three kinds of work:
- Downloading the crate index and crate sources into Cargo's home directory.
- Compiling dependencies into the
targetdirectory. - Compiling your own workspace crates, then linking.
Dependencies change rarely, and your own code changes on every commit. A good cache keeps the first two items and accepts that the third is mostly rebuilt.
| Location | Contents | Worth caching? |
|---|---|---|
| `~/.cargo/registry` | Crate index and downloaded `.crate` files | Yes |
| `~/.cargo/git` | Git dependencies | Yes, if you use any |
| `target/` | Compiled artifacts | Yes, but trim it first |
| `~/.cargo/bin` | Tools from `cargo install` | Yes, if installing them is slow |
| `target/*/incremental` | Incremental compilation data | Usually no |
The caching model
CI caches are key-value stores. At the start of a job you ask for a cache by key. If it exists, it is restored. At the end of a job you save a new cache under a key. Most providers never overwrite an existing key, so the key must change when the contents should change.
The usual key combines three things:
- The operating system and architecture.
- The Rust toolchain version.
- A hash of
Cargo.lock.
When Cargo.lock changes, the exact key misses. A fallback prefix then restores the most recent older cache, so Cargo only rebuilds what changed.
Using a Rust-aware cache action
You can write the cache steps by hand. A purpose-built action is simpler and handles many details for you. On GitHub Actions, Swatinem/rust-cache is widely used. It computes a key from the toolchain, Cargo.lock, and manifest files. It caches the Cargo home and target. It also removes your own workspace crates' artifacts before saving, so the cache holds mostly third-party dependencies.
# .github/workflows/ci.yml
name: ci
on:
push:
branches: [main]
pull_request:
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- run: cargo build --locked --all-targets
- run: cargo test --lockedCheck the action's current documentation for the exact version tag and options before you copy this. Release tags and defaults change over time.
Why `CARGO_INCREMENTAL: 0`
Incremental compilation helps local edit loops. In CI it usually hurts. Each run starts from a commit that differs from the cached one, and the incremental data is large. It makes caches bigger and slower to upload and download, and it adds overhead during compilation. Setting CARGO_INCREMENTAL=0 turns it off. Rust-aware cache actions often set this for you, but setting it explicitly documents the choice.
Why `--locked`
--locked makes Cargo fail if Cargo.lock would need to change. This keeps the cache key honest, because the lock file then fully describes the dependency set. It also catches a forgotten lock file update before it reaches main.
Choosing what goes into `target`
The target directory is the large item. Three habits keep it manageable.
Cache dependencies, not your own crates
Your workspace crates change on nearly every commit, so cached artifacts for them are stale almost immediately. Saving them adds upload time and cache size for no benefit. Rust-aware actions strip them. If you cache by hand, you can delete them before saving:
# Remove artifacts for workspace crates, keep third-party ones.
# Adjust the crate names to match your workspace.
cargo clean --package app
cargo clean --package core
cargo clean --package storagecargo clean --package works per package name, so list each workspace member.
Keep one profile and one target set per cache
Debug and release builds produce separate artifacts. So do cargo check and cargo build, and so do builds with different feature sets. If a job runs cargo check, then cargo clippy, then cargo test, the cache can hold artifacts for all three. This grows the cache. Where it fits, run commands that share artifacts, or give each distinct job its own cache key.
Watch cache size
Providers set size limits. GitHub Actions, for example, caps total cache storage per repository and evicts the least recently used entries. A cache that is huge can take longer to download than the compile it saves. Measure both:
- Time spent restoring and saving the cache.
- Time the build takes with and without the cache.
If restoring takes close to as long as compiling, trim the cache or drop it.
Combining sccache with CI
sccache caches individual compiler invocations by hash, rather than whole directories. It fits CI in two cases: many jobs that compile the same crates, and changing Cargo.lock files where a directory cache would miss entirely.
# Excerpt: enabling sccache with the GitHub Actions cache backend
env:
RUSTC_WRAPPER: sccache
SCCACHE_GHA_ENABLED: "true"
steps:
- uses: mozilla-actions/[email protected]
- run: cargo build --locked
- run: sccache --show-statsThe --show-stats step is worth keeping. A low hit rate means sccache is adding overhead with little benefit.
Some compilations cannot be cached by sccache. Crates that produce executables, build scripts with side effects, and incremental builds are common examples. This is another reason to turn off incremental compilation in CI.
You can use sccache and a directory cache together. The directory cache restores ~/.cargo/registry, and sccache covers compiled output. Test the combination, since two caches storing similar data can double upload costs.
Reducing the work before caching
A cache cannot fix work that should not happen. Several changes cut CI time regardless of caching.
- Lower debug info in CI. Set
CARGO_PROFILE_DEV_DEBUG=0orline-tables-onlyin the job environment. Smaller artifacts mean faster builds and smaller caches. - Use a faster linker. The link step runs on every commit, and the cache cannot skip it. Install lld or mold in the job image.
- Share artifacts across steps. Run
cargo testand let it do the build, instead of runningcargo buildfollowed bycargo testwith different flags. - Split jobs by purpose. Lints, tests, and doc builds can run in parallel jobs. Each needs its own cache key, as discussed above.
- Use
cargo checkfor lints.cargo clippyshares check artifacts, so a lint-only job does not need a full code generation build.
Common failure modes
| Symptom | Likely cause | Fix |
|---|---|---|
| Cache never hits | Key includes something that changes every run, such as a commit SHA | Key on the toolchain and `Cargo.lock` hash only |
| Cache hits but the build recompiles everything | Different `RUSTFLAGS`, toolchain, or profile than when the cache was saved | Keep environment settings the same across runs, or include them in the key |
| Cache grows on every run | Saving incremental data or workspace artifacts | Disable incremental compilation, strip workspace crates |
| Restore step is slower than compiling | Cache too large for the saved work | Trim `target`, cache only dependencies |
| Pull requests do not benefit from the cache | Caches saved on a branch are not visible to unrelated branches or forks | Save the cache on the default branch, and restore it in pull request jobs |
| Stale behavior after a toolchain bump | Old artifacts built with a different compiler | Include the toolchain version in the key |
Cargo itself guards against reusing artifacts from a mismatched compiler. A mismatch causes a rebuild, not wrong output. The cost is wasted cache, not wrong binaries.
Cache scope on pull requests
Many providers restrict cache access by branch. On GitHub Actions, a pull request can read caches from its base branch but not from sibling branches. If only pull requests save caches, each one starts cold. The usual fix is to run the same workflow on pushes to main, which saves the cache that later pull requests restore. Some Rust cache actions can be set to save only on the default branch, so pull request jobs read the cache without writing new entries.
Caching tools and binaries
CI often runs cargo install for tools such as cargo-nextest or cargo-llvm-lines. Compiling these from source on every run is slow. Options, from simplest to most involved:
- Use a prebuilt-binary installer such as
cargo-binstall, or an action that downloads release binaries. - Cache
~/.cargo/binkeyed on the tool version. - Build a custom CI image with the tools already installed.
Pin tool versions in all three cases. An unpinned install makes runs differ in ways the cache key does not capture.
Containers and self-hosted runners
If you run your own runners, you can keep the target directory and Cargo home on disk between jobs. This avoids upload and download entirely. Two cautions apply:
- Concurrent jobs sharing one
targetdirectory block each other with Cargo's directory lock, and may mix up feature sets. Give each job slot its own directory withCARGO_TARGET_DIR. - Disks fill up. Schedule a periodic clean, or use a tool that prunes old artifacts, such as
cargo-sweep.
For container-based builds, order the Dockerfile so that dependency compilation lands in its own layer, which Docker caches until Cargo.toml or Cargo.lock changes. A common approach is to build with a stub main.rs first, then copy the real sources. Tools like cargo-chef automate this by generating a recipe file from the manifests.
FROM rust:1 AS planner
WORKDIR /app
RUN cargo install cargo-chef --locked
COPY . .
RUN cargo chef prepare --recipe-path recipe.json
FROM rust:1 AS builder
WORKDIR /app
RUN cargo install cargo-chef --locked
COPY --from=planner /app/recipe.json recipe.json
# This layer is cached until dependencies change.
RUN cargo chef cook --release --recipe-path recipe.json
COPY . .
RUN cargo build --releaseVerifying that the cache works
Do not assume a cache is helping. Check it on a real run:
- Read the cache step's log for "cache hit" or "restored from key".
- Run
cargo build --timingsin CI and uploadtarget/cargo-timingsas an artifact. Dependencies that appear in the report were recompiled. - Compare total job time for a cold run and a warm run. Rerun the same commit twice to get a clean comparison.
- Track cache size over several weeks. Steady growth means something unneeded is being saved.
Summary of decisions
- Cache the registry and third-party artifacts. Do not cache your own crates.
- Turn off incremental compilation in CI.
- Key on the OS, toolchain, and
Cargo.lockhash, with a prefix fallback. - Save caches from the default branch so pull requests can read them.
- Consider sccache when many jobs share compilations or the lock file changes often.
- Measure restore time against compile time, and re-check regularly.
Exercise
A project's CI cache key is build-${{ github.sha }}. Every run reports a cache miss and takes a full cold build. What is wrong, and what key would you use instead?
Show answer
The commit SHA is different on every run, so the exact key never matches and nothing is ever restored. Use a key built from stable inputs: the operating system, the Rust toolchain version, and a hash of Cargo.lock, for example build-linux-1.83-<hash of Cargo.lock>. Add a restore prefix such as build-linux-1.83- so that a changed lock file still restores the most recent older cache and only the changed dependencies are rebuilt.
Exercise
Your cache grows from 800 MB to 4 GB over a month, and restoring it now takes longer than compiling the dependencies. Name two likely causes and a fix for each.
Show answer
One cause is incremental compilation data being saved. Fix it by setting CARGO_INCREMENTAL=0 in CI. Another cause is workspace crate artifacts and artifacts from several profiles or commands (check, clippy, test, release) accumulating in one cache. Fix it by stripping workspace crates before saving, for example with a Rust-aware cache action or cargo clean --package, and by giving distinct jobs their own cache keys. Also measure the restore time against the compile time to decide whether the cache is worth keeping.