Sub topic 12
sccache and shared target directories
This chapter covers two ways to avoid compiling the same code twice: a compiler cache (sccache) and a shared Cargo target directory. It assumes you can read Cargo.toml and .cargo/config.toml, and that you know what cargo build --timings shows. It also assumes you know that incremental compilation reuses work between rebuilds of the same crate. Both techniques here work at a different level. They reuse work between projects, branches, and machines.
What problem these tools solve
Incremental compilation only helps one workspace member in one target directory. It does nothing in these common situations:
- You run
cargo cleanor deletetarget/. - You switch between Git branches and Cargo rebuilds dependencies it already built last week.
- You work on several projects that depend on the same crates, such as
serde,tokio, orsyn. - A CI runner starts from an empty disk.
In all of these, the compiler is asked to build a crate it has already built with the same inputs. A cache can answer from stored results.
How sccache works
sccache is a compiler wrapper from Mozilla. Cargo normally runs rustc directly. With a wrapper configured, Cargo runs sccache rustc ... instead. For each invocation sccache does the following:
- It hashes the inputs: the compiler version, the command-line flags, relevant environment variables, and the contents of the source files.
- It looks that hash up in its storage.
- On a hit, it returns the stored output files and skips
rustc. - On a miss, it runs
rustc, stores the output, and returns it.
The result is exact. A hit means the same inputs were compiled before, so the output is the same. The cost of a miss is small: hashing plus writing the output to storage.
Install and enable sccache
Install it with Cargo, or with your system package manager:
cargo install sccache --locked
sccache --versionThen tell Cargo to use it. You can set an environment variable for one shell:
export RUSTC_WRAPPER=sccache
cargo buildOr make it permanent for your user in ~/.cargo/config.toml:
# ~/.cargo/config.toml
[build]
rustc-wrapper = "sccache"Putting it in the user-level config avoids forcing sccache on teammates who haven't installed it. If you put it in a project's .cargo/config.toml, every builder needs sccache on their PATH, or the build fails.
Check that it works
Build the project twice with a clean target directory in between, then read the statistics:
sccache --zero-stats
cargo build
cargo clean
cargo build
sccache --show-statsThe second build should show many cache hits, and it should finish much faster than the first. If the hit count stays at zero, see the section on common problems below.
Other commands you will use:
sccache --stop-server # stop the background server, for example to change settings
sccache --start-server # start it again with the current environmentsccache runs a background server process. It reads its environment variables when it starts, not on each build. After changing a variable such as SCCACHE_DIR, stop the server so the new value takes effect.
Where the cache is stored
By default sccache uses a local directory on disk. Useful settings:
| Variable | Purpose |
|---|---|
| `SCCACHE_DIR` | Location of the local disk cache |
| `SCCACHE_CACHE_SIZE` | Maximum local cache size, for example `20G` (the default is 10 GB) |
| `SCCACHE_BUCKET`, `SCCACHE_REGION` | Use an Amazon S3 bucket as storage |
| `SCCACHE_GCS_BUCKET` | Use a Google Cloud Storage bucket |
| `SCCACHE_REDIS` | Use a Redis server |
A local cache helps one machine. A remote backend such as S3 lets a team and a CI system share results: one developer or one CI job compiles a dependency, and everyone else downloads the result. The trade-off is network time. Downloading a small crate's output can be slower than compiling it, so a remote cache pays off mainly for large dependencies and clean builds. Remote credentials must be handled like any other secret. Pass them through your CI secret store, not through files in the repository.
What sccache cannot cache
sccache is not a universal speedup. Know these limits before you rely on it.
- Incremental builds are skipped. When rustc is called with incremental compilation enabled, sccache does not cache the result. Cargo turns incremental compilation on only for workspace members in the dev profile. Registry dependencies are never built incrementally. So with the default settings, your dependencies are cached and your own crates compile incrementally. That is usually the best of both. In CI, where you start clean, set
CARGO_INCREMENTAL=0so your own crates are cacheable too. - Linking is not cached. Crates that need a final link step are compiled directly. Binaries, and procedural macro crates in particular, are not cacheable. The link step still takes the same time on every build, so combine sccache with a faster linker (see the linking chapter).
- Build scripts run every time they are invalidated. sccache caches compiler calls. It does not cache what a
build.rsdoes, such as compiling C code through another compiler or probing the system. - Absolute paths can affect the hash. Rust embeds paths in debug info and panic messages. If two checkouts live in different directories, their keys may differ and you get misses. Consider remapping the path prefix so equal code produces equal hashes:
# .cargo/config.toml
[build]
rustflags = ["--remap-path-prefix", "/home/alice/work=/src"]Each developer then uses their own prefix before the =, or a CI job uses its own checkout path. Setting this in a shared file requires everyone to use the same directory layout, so for a mixed team prefer a per-user config.
Shared target directories
Cargo puts build output in target/ inside each workspace. You can move it somewhere shared with CARGO_TARGET_DIR, or with a setting in ~/.cargo/config.toml:
# ~/.cargo/config.toml
[build]
target-dir = "/home/alice/.cache/cargo-target"Every project you build now writes to the same directory. Cargo names each artifact with a hash of its package, version, features, profile, and compiler flags. Two projects that depend on the same version of serde with the same features and flags produce the same artifact name, so the second project reuses the first project's build.
This gives you some of the benefit of sccache with no extra tool. It also has costs:
- A single lock. Cargo locks the target directory during a build. Two builds on different projects wait for each other. This also happens between
cargo buildin a terminal and rust-analyzer in your editor. A common fix is to give the editor its own directory with therust-analyzer.cargo.targetDirsetting. - Reuse is fragile. A different feature set, a different
RUSTFLAGS, or a different toolchain changes the hash and gives a separate artifact. The directory then collects variants of the same crate and grows. - Cleaning is all or nothing.
cargo cleanin one project removes only that project's package artifacts (with-p) or everything in the shared directory (without it). Check which one you intend. - Output paths change. Scripts that expect
./target/release/myappbreak. Ask Cargo for the path withcargo metadataor use--artifact-dirwhere it is available on your toolchain. - Path dependencies and workspace members are not shared in practice. Their artifacts are keyed to their location, so only registry and Git dependencies reuse well.
Choosing between them
| Situation | Better choice |
|---|---|
| Many projects on one laptop sharing dependencies | Shared target directory or local sccache |
| Frequent branch switching in one project | sccache (a hit restores output even after the target directory changed) |
| CI with an empty disk on every run | sccache with a remote backend, or a cached `target/` (next chapter) |
| Editing one crate repeatedly | Neither. Incremental compilation and `cargo check` handle this |
| Final link is the slow part | Neither. Use a faster linker |
You can use both together, but there is little extra gain. A shared target directory already reuses dependencies, and sccache then mostly helps when that directory is cleaned or when a compile differs by something cheap.
Common problems
- Zero hits after a rebuild. Run
sccache --show-statsand look at the "non-cacheable" and "cache miss" counts. The usual causes are incremental compilation on your own crates, different absolute paths, or a changedRUSTFLAGS. Environment variables passed to rustc are part of the key. - "sccache: error: failed to execute compile". The server can't start or is stuck. Run
sccache --stop-server, then retry. - A teammate's build fails with "no such file or directory" for
sccache. The wrapper is set in a shared config but is not installed on their machine. - The disk fills up. Set
SCCACHE_CACHE_SIZEand check the size of a shared target directory withdu -sh. Old toolchains leave artifacts behind that nothing reuses.
Exercise
You enable sccache and run cargo build on a clean checkout of a project. The second build, after cargo clean, shows that all dependencies hit the cache, but your own workspace crates are listed as non-cacheable and are recompiled. The project is built with the default dev profile. Why does this happen, and what should you change for a CI job that always starts clean?
Show answer
Cargo enables incremental compilation for workspace members in the dev profile, and sccache does not cache rustc calls that use incremental compilation. Registry dependencies are not built incrementally, so they are cached. In a CI job that starts clean there is no incremental state to reuse, so set CARGO_INCREMENTAL=0 (or [build] incremental = false). Your own crates then become cacheable. On a developer machine keep the default, because incremental compilation is faster for repeated edits.
Exercise
Two terminals use the same shared target directory. One runs cargo build for project A, and the other runs cargo test for project B. The second command prints "Blocking waiting for file lock on build directory". Why, and what is one way to avoid it?
Show answer
Cargo takes a lock on the target directory while it builds, so only one build at a time can use a shared directory. Avoid the wait by giving one of the tools its own directory, for example setting CARGO_TARGET_DIR differently for project B, or giving rust-analyzer a separate rust-analyzer.cargo.targetDir. Alternatively use sccache, which shares compiled results between separate target directories without a shared lock.