Why is Rust CI so slow?

From the series Rust CI from first principles, part 3 of 3

Reading time
12–15 min
Level
Intermediate–advanced
Prerequisites
Cargo and Rust compilation

Introduction: The price of a clean build

We love Rust. Its compiler catches entire classes of bugs before our programs run. Its type system and ownership model provide unusually strong guarantees, and tools like Clippy make it easier to maintain high-quality code.

But anyone who has worked on a substantial Rust project will probably recognize another aspect of the development experience: sometimes, compilation takes longer than we’d like. This can be particularly frustrating in continuous integration. You change a handful of lines, push a commit, and open a pull request. Then you wait for your CI pipeline to finish checking, compiling, and testing the project.

Perhaps your local machine completed a similar operation in seconds. Why does CI seem to be doing so much more work? And if Cargo already supports caching and incremental compilation, why can’t it simply reuse everything that hasn’t changed? These are surprisingly interesting questions.

In our previous article, What actually happens during Rust CI?, we followed a Rust project through Cargo’s dependency resolution, compilation scheduling, freshness checks, and rustc’s compilation pipeline. Now we’ll use that understanding to investigate performance.

We’ll look at where Rust CI spends its time, why apparently small changes can trigger significant work, and why conventional caching doesn’t always solve the problem. We’ll also explore how to measure these costs rather than simply guessing where the bottlenecks are.

The central insight is that Rust CI performance isn’t determined solely by how fast the Rust compiler is. It’s determined by how much work the entire system performs, how that work is scheduled, and how much of it must be repeated.

1. Where does Rust CI time actually go?

When developers complain that Rust CI is slow, they’re often talking about the total time between pushing a commit and receiving a successful result. But that time includes much more than compilation. A typical CI job might involve:

  1. Start CI runner
  2. Checkout repository
  3. Prepare Rust toolchain
  4. Download dependencies
  5. Restore cached artifacts
  6. Compile required crates
  7. Link binaries and tests
  8. Execute tests
  9. Upload artifacts and report results
A typical CI job, from runner startup to a reported result.

Not every pipeline contains every stage, and some stages can overlap or run concurrently. Nevertheless, it’s useful to separate the time spent preparing the environment from the time spent actually compiling and testing Rust code.

For example, imagine a CI job that spends a considerable amount of time restoring cached artifacts before Cargo even starts. Improving compilation speed won’t eliminate that overhead.

Alternatively, suppose Cargo spends most of its time waiting for a particularly expensive dependency to compile. Making the CI runner start faster won’t solve that problem.

This leads to our first principle: Before optimizing Rust CI, establish which part of the pipeline is actually slow. There are several distinct categories of overhead worth investigating.

2. Cold builds versus warm builds

Let’s begin with one of the most important distinctions in Rust development. Consider running:

cargo build --workspace

Now run the same command again. Assuming nothing relevant has changed, the second invocation will usually be much faster. Why? Because Cargo can reuse compatible artifacts produced by the first build.

What is a cold build?

A cold build is one in which the relevant compilation artifacts aren’t already available. Cargo must compile the dependencies and workspace crates needed for the requested command. For a substantial project, that might involve hundreds of compiler invocations.

Some dependencies may themselves require build scripts, procedural macros, or native-code compilation. A cold build therefore represents a considerable amount of work.

What is a warm build?

A warm build starts with previously generated artifacts available. Cargo checks whether those artifacts remain valid for the requested compilation units. If they do, it can avoid repeating the corresponding compilation work. When everything is fresh, Cargo may have very little compilation to perform.

Why this matters in CI

The difference between cold and warm builds becomes especially important in cloud environments. For example, GitHub-hosted runners generally provide a fresh runner environment for each job. That means build artifacts aren’t automatically preserved between separate jobs or workflow runs. GitHub provides caching mechanisms to address this, but using them introduces additional considerations around what is stored, restored, and reused.

Locally, your target directory may contain the accumulated results of many previous builds. In CI, those results must either be recreated or restored from somewhere.

This creates an important distinction: A build can be fast because compilation itself is efficient, or because the necessary compilation has already happened. Those are different kinds of performance improvements. And they need to be measured separately.

3. Why compiling dependencies can be expensive

Let’s return to the small workspace from our previous article. We had two crates:

ci-app
    └── ci-core

Our application depends on our library. On a cold build, Cargo must produce the required library output before compiling the application that depends on it.

Now imagine we introduce several third-party libraries. A real dependency graph might contain dozens or hundreds of packages, many of which depend on other packages. Cargo needs to construct the necessary compilation units and schedule them according to their dependencies.

Dependencies impose an order

Suppose our application depends on crate D, and D depends on crates A and B. Meanwhile, the application also depends directly on crate C. The dependency relationships might look like this:

Crate dependencies and the compilation critical path Crates A and B feed crate D. Crate C and crate D feed the application. A, B and C may compile concurrently; D needs outputs from A and B. Crate A Crate B Crate C Crate D Application
Arrows run from each dependency to the crate that needs its output.

Cargo can potentially compile A, B, and C concurrently. But D cannot complete its compilation until the required outputs of A and B are available. And the application depends on D.

This gives our compilation graph a critical path: a chain of dependent operations that constrains the minimum completion time. Even with unlimited CPU cores, Cargo cannot simply ignore those dependencies.

Why more CPU cores aren’t always the answer

Adding CPU cores can help when there are independent compilation jobs ready to execute. But once the build reaches a stage where a single dependency or compilation unit determines progress, additional cores may offer little benefit. The actual bottleneck might be one expensive crate, a linking step, or a build script.

Memory also matters. Compilers can consume substantial amounts of memory, particularly when compiling large crates or performing intensive optimization. Allowing too many jobs to execute concurrently can create memory pressure, reduce performance, or even cause builds to fail.

The right level of parallelism depends on the project and the available hardware. This is why simply increasing Cargo’s --jobs setting isn’t a universal solution.

4. Why small changes can trigger substantial recompilation

Here’s one of the more surprising aspects of Rust compilation. Suppose our application depends on a library containing this function:

pub fn calculate(value: u64) -> u64 {
    value * 2
}

We modify the implementation:

pub fn calculate(value: u64) -> u64 {
    value + value
}

The public function signature hasn’t changed. From the perspective of ordinary callers, both implementations produce the same mathematical result for u64, including wrapping behaviour in release configurations where overflow checks are disabled. Why might Cargo still need to recompile code that depends on this library?

Cargo tracks compilation dependencies, not arbitrary semantic equivalence

As we explored in Article 2, Cargo uses fingerprints, dependency information, and filesystem metadata to determine whether compilation units are fresh. When a dependency is rebuilt, Cargo generally treats downstream units that depend on its compilation output as requiring recompilation.

This is deliberate. Cargo doesn’t attempt to prove that the new implementation is semantically equivalent to the previous one. Nor does it generally prove that every downstream compilation unit is unaffected by a dependency change. Instead, its freshness mechanism takes a conservative approach to deciding when previously generated artifacts can be reused.

Why isn’t the public API enough?

It’s tempting to assume that an unchanged public API should mean downstream compilation can always be skipped. But compilation dependencies are more complicated than function signatures.

For example, Rust supports generic functions that may be monomorphized in downstream crates. Inlining can also expose upstream implementation details to downstream code generation. Constants, macros, and other forms of compile-time information can affect compilation even when an apparently unrelated function signature remains unchanged.

Consequently, a simple comparison of public function signatures isn’t enough to determine whether every downstream compilation result remains valid. This doesn’t mean more precise reuse is theoretically impossible. It means that establishing safe reuse requires understanding exactly which information a compilation depends on. That’s a much more sophisticated problem than checking whether two versions of a library expose the same function names.

We’ll explore this in detail in a future article about Cargo freshness and recompilation. For now, the important takeaway is: The amount of recompilation triggered by a change can be much larger than the amount of source code that changed.

5. Rust’s compiler performs substantial analysis

So far, we’ve focused on deciding which crates need compilation. But what happens once rustc actually starts?

Rust’s compiler is doing considerably more than translating source code into machine instructions. It must parse the program, expand macros, resolve names, check types, enforce ownership and borrowing rules, and perform other semantic analysis. For a normal build, it may also need to monomorphize generic code, perform optimization, generate machine code, and link the resulting artifacts.

These operations provide much of the foundation for Rust’s safety guarantees and runtime performance. But they have computational costs. Let’s examine three particularly relevant areas.

Type checking and borrow checking

Rust performs sophisticated compile-time analysis. Its type checker verifies relationships between expressions, functions, traits, and other language constructs. Its borrow checker enforces ownership and borrowing constraints that help prevent memory-safety errors.

The benefits are substantial. Many problems that might otherwise appear during execution are rejected during compilation.

Importantly, however, this doesn’t mean type checking or borrow checking is necessarily the dominant cost of compiling a Rust project. The relative cost of different compiler stages depends on the source code, compilation settings, and requested output. To identify the real bottleneck, we need measurements.

Monomorphization

Rust generics enable reusable abstractions without necessarily introducing runtime dispatch. Consider:

fn identity<T>(value: T) -> T {
    value
}

The compiler may generate specialized code for the concrete types used by the program. This process is called monomorphization. It can produce highly efficient executables, but it can also increase the amount of code that needs to be generated. Projects that make extensive use of generics may therefore create significant code-generation workloads.

That doesn’t mean generics are inherently bad for compilation performance. Their impact depends on how they’re used and how much specialization is required.

Optimization and linking

Code generation is another potentially substantial source of compilation time. Rust commonly uses LLVM to optimize and generate machine code. Higher optimization levels can require additional work.

Linking can also be expensive, particularly for large binaries. Consider a release build:

cargo build --release

This command can take considerably longer than an ordinary development build. The default release profile uses stronger optimization settings than the development profile. It also disables incremental compilation by default, whereas the development profile enables it.

The compiler isn’t simply doing the same work more slowly. It’s being asked to produce a different kind of artifact, with different optimization priorities. This illustrates a fundamental trade-off: Compilation speed and runtime performance are related, but they aren’t the same optimization objective.

6. Build scripts and procedural macros add another dimension

Rust’s build process becomes even more interesting when we consider code that executes during compilation. Two important mechanisms are build scripts and procedural macros.

Build scripts

A Rust package can contain a build.rs file. Cargo compiles and executes that script before building the package. Build scripts can generate source code, inspect the build environment, compile native dependencies, or perform other preparation.

Some build scripts are trivial. Others perform substantial work. Cargo supports directives such as:

println!("cargo::rerun-if-changed=src/schema.proto");

This allows a build script to declare a file whose changes should trigger the script to run again. Without suitable change-tracking directives, Cargo may take a broader approach to detecting changes that require rerunning the script.

Procedural macros

Procedural macros are even more tightly integrated with compilation. They generate Rust code during macro expansion. To execute a procedural macro, rustc needs a compiled version of the macro implementation.

This means a project can require executable build-time components even when the requested Cargo command is cargo check. And procedural macros can themselves perform nontrivial computation.

Why these mechanisms complicate caching

Both mechanisms introduce additional inputs and dependencies. A build script might depend on files, environment variables, native libraries, or external tools. A procedural macro might generate different code depending on its input tokens or other information available during execution.

For reuse to be reliable, the relevant inputs and outputs need to be accounted for. This is one reason build-time execution makes compilation caching more complicated. It’s also an interesting area for future research, particularly as more development workflows run in ephemeral cloud environments.

7. Why cargo check, Clippy, build, and test can repeat work

Let’s return to the CI pipeline from our first article. It runs:

cargo check --workspace
cargo clippy --workspace --all-targets
cargo test --workspace
cargo build --workspace

At first glance, these appear to be four different checks. But they aren’t four completely independent workloads. All four commands interact with overlapping parts of the same compilation graph.

Check versus build

cargo check performs compiler analysis without normally generating final machine-code artifacts for the checked crates. cargo build needs those compiled artifacts. Consequently, a successful cargo check doesn’t mean that a subsequent cargo build has nothing left to do. Some artifacts may be reusable, but the two commands have different output requirements.

Clippy versus check

Clippy performs additional lint analysis using Rust’s compiler infrastructure. Much of the work resembles the analysis performed during cargo check. However, we shouldn’t assume that the results of the two commands are completely interchangeable. Their compilation units, flags, or analysis requirements may differ.

Test versus build

cargo test needs executable test targets. For unit tests, this can require compiling a crate with Rust’s test harness enabled. Integration tests are separate targets. Documentation tests introduce another execution path.

As a result, some library code may need to be compiled in different configurations. The Cargo documentation explicitly notes that a library can be compiled both as a normal dependency and as a unit-test target.

Does this mean we should remove checks?

Not necessarily. Each command establishes different properties.

Clippy provides analysis that a normal build doesn’t. Tests exercise runtime behaviour. A normal build can verify the production artifact that a check-only compilation doesn’t produce.

The right question isn’t simply how many commands we can eliminate. It’s how to obtain the required confidence while minimizing unnecessary work. That requires understanding both the project’s verification requirements and Cargo’s compilation behaviour.

For some projects, a separate cargo check step may provide little additional value once other checks are in place. For others, it may be an important fast-feedback stage. There isn’t a universally optimal command sequence.

8. Why caching doesn’t solve everything

At this point, you might reasonably ask: If compilation is expensive, why don’t we simply cache the results? Caching is indeed one of the most important techniques for accelerating Rust builds. But there are several different things we might cache.

Downloaded dependencies

Cargo downloads dependency source code from registries and other configured sources. Caching those downloads avoids repeated network transfers. This is useful, but it doesn’t eliminate the need to compile the dependencies.

Compiled artifacts

Cargo stores compiled outputs and intermediate artifacts in its build directories. The default location is generally the workspace’s target directory. Reusing compatible compiled artifacts can avoid substantial compilation work.

Incremental compiler state

Rustc can also preserve information used by incremental compilation. When a crate needs recompilation, some previous compiler results may still be reusable. This operates at a different level from Cargo’s decision to skip a fresh compilation unit altogether.

The compatibility problem

A cached artifact is only useful when it’s compatible with the work we need to perform. Changes to the toolchain, compilation settings, selected features, dependencies, or target architecture can affect whether previously generated outputs remain valid. This is particularly important in CI, where different jobs may use different environments.

The transfer problem

Caching also has a cost. Artifacts need to be stored somewhere. In a cloud CI system, they may need to be compressed, uploaded, downloaded, and extracted. That introduces network traffic, disk I/O, and additional elapsed time.

If restoring an artifact costs more than regenerating it, the cache has not improved performance. A useful optimization therefore needs to consider the entire process: How much work does a cache avoid, and how much does accessing that cache cost? This is why cache effectiveness should be measured, not assumed.

9. Understanding the limits of parallel compilation

Another common optimization is to provide more powerful hardware. That can help enormously, especially for cold builds containing many independent dependencies. But hardware alone doesn’t eliminate every bottleneck.

As we discussed earlier, Cargo’s compilation graph imposes dependencies between jobs. A crate that requires another crate’s output cannot complete before that dependency is available. This creates periods when some CPU cores may be idle even though compilation work remains. There may simply be no additional independent compilation units ready to execute.

Conversely, a build with many independent jobs can sometimes saturate its available CPUs and memory. The optimal configuration depends on the shape of the graph and the resource demands of individual jobs.

A practical way to investigate

Cargo provides a timing-report feature:

cargo build --workspace --timings

This generates an HTML report showing compilation-unit durations and concurrency over time. The report can help identify long-running compilation units and periods where the dependency graph limits available parallelism. It’s an excellent starting point for understanding a slow build.

But it doesn’t tell the entire story. Cargo’s timings describe compilation activity, not every part of the CI workflow. They also don’t provide a complete breakdown of every operation performed internally by rustc. For that, more specialized measurements may be necessary.

10. Measuring Rust CI performance properly

We’ve discussed a number of potential bottlenecks. Now let’s examine how to investigate them experimentally. The most important principle is to distinguish different build conditions. Measuring only one CI run tells us very little about why it took as long as it did.

Experiment 1: Measure a cold build

From the example workspace used in Article 2, run:

cargo clean
time cargo build --workspace --locked --timings

This removes the workspace’s existing build artifacts before compiling. Save any timing reports you want to keep first: cargo clean also deletes reports under target/. The --locked examples require an up-to-date Cargo.lock; generate and commit it as described in Article 2.

It leaves downloaded dependency sources in Cargo’s cache and does not clear a compiler cache such as sccache, so it isolates a different kind of cold start from a completely fresh CI environment. Record those cache states separately. Record the elapsed time and inspect the generated Cargo timing report.

For our small example workspace, the results may not be particularly dramatic. For a larger Rust project, the report can be much more informative.

Experiment 2: Measure an unchanged build

Without modifying the source code, run:

time cargo build --workspace --locked --timings

This gives us an indication of the overhead when Cargo can reuse existing outputs. Compare the results with the previous build. How much compilation work was avoided? How much time was spent checking freshness and performing other operations?

Experiment 3: Change only the application

Modify crates/app/src/main.rs. Then run:

time cargo build --workspace --locked --timings

Inspect which compilation units Cargo rebuilt. The library should generally remain reusable if its relevant inputs and configuration haven’t changed.

Experiment 4: Change the library

Now restore the previous application change and modify crates/core/src/lib.rs. Run the build again. Compare which compilation units were rebuilt. This demonstrates how changes to a dependency can affect downstream compilation.

Experiment 5: Compare different Cargo commands

On a clean build directory, investigate:

cargo check --workspace --locked --timings

Then:

cargo build --workspace --locked --timings

Then:

cargo test --workspace --locked --timings

Inspect the compilation jobs required by each command. Be careful when interpreting the results. Because the commands execute consecutively, later commands may benefit from artifacts generated by earlier commands.

If we want to measure each command’s cold-start cost independently, we’ll need to reset the build artifacts between experiments. If we want to measure their behaviour as a pipeline, we should preserve those artifacts. Both experiments are useful, but they answer different questions.

Record the environment

For reproducible measurements, record the Rust toolchain version, operating system, architecture, available CPUs and memory, build profile, Cargo options, and cache state. Run experiments multiple times where practical, and compare distributions rather than treating a single result as definitive. This is particularly important when testing on shared cloud infrastructure. The same project can produce different timings because of environmental variation rather than a meaningful change in compilation efficiency.

What should we measure?

I’d separate the measurements into several categories.

Measurement What it tells us
Total CI wall-clock time How long developers wait for a result
Environment preparation time Overhead before Cargo starts
Dependency download and cache restore time Cost of obtaining reusable inputs
Compilation wall-clock time Time spent satisfying the build request
Compilation-unit durations Which units take the longest
Build concurrency How much work can proceed simultaneously
Test execution time Time spent running tests rather than compiling them
Cache effectiveness How much work was avoided relative to cache overhead

Together, these measurements provide a much more useful picture than a single number labelled build time. We should measure the system developers experience, while retaining enough detail to identify where improvements are possible.

11. What can we actually do to make Rust CI faster?

We’ve now identified several sources of overhead. That suggests a number of possible improvements. At the simplest level, we can avoid running unnecessary commands, configure caching carefully, and use appropriate hardware.

We can also examine how projects are structured. For example, reducing unnecessary dependencies may lower cold compilation costs. Separating large crates may create opportunities for more targeted recompilation, although it can also introduce additional compilation overhead.

Build scripts can sometimes be made more precise about the inputs that trigger reruns. And CI workflows can be organized so that inexpensive checks provide feedback quickly, while more expensive verification continues as needed.

These are established techniques worth understanding. But there are also more fundamental questions.

Can we determine more precisely which compilation work is affected by a change? Can useful compiler artifacts be shared more effectively across different environments? Can we avoid repeating work across related CI jobs? And can we reduce the time between a developer or a coding agent making a change and receiving meaningful feedback?

These questions point toward a broader objective. It’s not simply about making rustc execute faster. It’s about making the entire development feedback loop more efficient, while preserving the correctness guarantees and verification coverage that make Rust attractive. That’s an especially interesting problem as development increasingly moves into the cloud and coding agents generate and validate changes autonomously.

12. The future of fast Rust CI

Rust provides an extraordinary set of tools for producing reliable, performant software. But the computational cost of those tools matters. As projects grow, CI systems can spend substantial time preparing environments, reconstructing compilation state, compiling dependencies, generating machine code, and executing tests.

Some of that work is unavoidable. Some is a consequence of conservative dependency tracking or incompatible build configurations. And some may be repeated simply because useful results from previous work aren’t available where they’re needed.

The opportunity is to understand those distinctions precisely. When we know which work is genuinely necessary, which work can be reused, and which work can execute concurrently, we can make much better decisions about how to design our CI systems.

For us at Sorus, this is a fascinating area of engineering. We love Rust’s commitment to correctness and performance, and we believe developers should be able to benefit from those strengths without spending unnecessary time waiting for feedback. But meaningful improvement starts with understanding the system we’re trying to improve. And that brings us to the next articles in this series.

Where to go next

In How Does Cargo Know What Needs Recompiling?, we’ll examine Cargo’s fingerprints, dependency tracking, and freshness decisions in considerably greater detail. We’ll investigate when changes trigger downstream recompilation and why determining whether previous work can be safely reused is a subtle problem.

Then, in Understanding Rust Build Caching, we’ll explore the different kinds of compilation artifacts, their compatibility requirements, and the challenges of reusing them across machines. Finally, How to Benchmark Rust CI Properly will develop the measurement techniques introduced here into a rigorous, reproducible methodology.

Because the first step toward faster Rust CI isn’t guessing which optimization might help. It’s understanding exactly where the time goes and why.


Rust CI from first principles is an educational series by Sorus, exploring Rust compilation, testing, continuous integration, and developer productivity.

Further reading