Sub topic 6
Trim dependencies and features
This chapter assumes you can read a Cargo.toml, run cargo build and cargo tree, and know that crates can expose optional features. It covers how dependencies add to build time and how to remove what you don't need.
Why dependencies dominate clean builds
Every crate in your dependency graph is compiled from source on a clean build. A project with 20 direct dependencies often has 200 or more crates in total. Most of the build time on a fresh checkout or a CI runner without a cache goes to code you did not write.
Dependencies cost you in three ways:
- Compile time. Each crate goes through rustc and LLVM. Large crates with heavy generics or macros cost more.
- Graph shape. Cargo can compile independent crates in parallel, but a long chain of dependent crates forces serial work. One slow crate near the root of the graph delays everything that depends on it.
- Link time and binary size. More code reaches the linker, even if you never call it.
Incremental builds usually recompile only your own crates, so dependency trimming helps most on clean builds, in CI, and when you change a Cargo.toml or the toolchain.
Find out what you depend on
Start with the tree. It shows every crate and why it is there.
# Full tree of crates
cargo tree
# Crates that appear more than once, usually at different versions
cargo tree --duplicates
# Who depends on a given crate? Shows the paths that pull it in.
cargo tree --invert syn
# Which features are enabled on each crate
cargo tree -e featurescargo tree --invert <crate> is the most useful of these when you ask "why is this in my build?". It lists each path from your crate to the one you asked about, so you can see which direct dependency to change.
Use cargo build --timings from the earlier chapter to rank crates by compile time. Then use cargo tree to decide which of the slow ones you can remove or slim down. Measuring first stops you from spending an afternoon removing a crate that takes 0.3 seconds.
Trim features
A feature is a compile-time switch. Enabling a feature compiles extra code and often pulls in extra dependencies. Many crates enable a large set of features by default, so a plain serde = "1" or tokio = "1" line may compile more than you need.
The usual pattern is to turn off default features and list only the ones you use:
[dependencies]
# Before: tokio = { version = "1", features = ["full"] }
tokio = { version = "1", default-features = false, features = ["rt-multi-thread", "macros", "net"] }
# Only the derive support, no std-only extras your code never calls
serde = { version = "1", default-features = false, features = ["derive", "std"] }To see what a feature actually enables, read the [features] table in the crate's own Cargo.toml, which you can open on docs.rs or in ~/.cargo/registry/src. Features are additive, so enabling one never removes code that another enabled.
Features unify across the graph
Cargo builds each crate once per package graph with the union of all features requested by everything that depends on it. This is called feature unification. If your crate asks for serde without std, but another dependency asks for serde with std, the build uses std.
Two consequences follow:
- Trimming a feature in your
Cargo.tomlhas no effect if another crate in the graph still requests it. Check withcargo tree -e features --invert <crate>to see who asks for what. - Features enabled by one workspace member can leak into another when you build the whole workspace. The
resolver = "2"setting (the default for edition 2021 and later) keeps build-only and dev-only features separate from normal ones, and avoids unifying features across different target platforms.
Keep workspace features consistent
In a workspace, declare shared dependencies once. Members then inherit the same version and feature set, which stops two members from requesting slightly different features and causing extra variants.
# Cargo.toml (workspace root)
[workspace]
resolver = "2"
members = ["app", "core", "storage"]
[workspace.dependencies]
serde = { version = "1", default-features = false, features = ["derive"] }# app/Cargo.toml
[dependencies]
serde = { workspace = true }A member can add features on top of the shared declaration with serde = { workspace = true, features = ["std"] }. It cannot remove features or turn on default-features again once the workspace set them off, so keep the shared set minimal and let members add what they need.
Remove unused dependencies
Over time, code changes and dependencies stay. An unused crate still compiles. Tools can find them:
# Static check, works on stable (cargo install cargo-machete)
cargo machete
# More accurate, uses the compiler, needs nightly (cargo install cargo-udeps)
cargo +nightly udeps --all-targetscargo machete searches source text for crate names. It is fast but can report false positives, for example when a crate is used only by a macro or a build script. cargo udeps asks the compiler which crates were really used and is more reliable, but it needs a nightly toolchain. Treat both as suggestions: remove the dependency, run cargo build --all-targets, and put it back if something breaks.
Also check [dev-dependencies] and [build-dependencies]. A dev-dependency is only compiled for tests, examples and benchmarks, so it does not slow cargo build, but it does slow cargo test. Dev-only crates that are used in one test file are good candidates for removal.
Deal with duplicate versions
cargo tree --duplicates lists crates that appear at more than one version. Cargo allows this when two dependencies need incompatible semver ranges, for example rand 0.7 and rand 0.8. Each version is compiled separately, so you pay twice.
Fixes, from easiest to hardest:
- Run
cargo updateto let Cargo pick newer compatible versions that may now agree. - Update your direct dependencies so their transitive requirements converge.
- Use
cargo update -p <crate>@<old-version> --precise <version>to move one entry in the lockfile. - If a dependency is stuck on an old version, open an issue upstream or replace it.
Not every duplicate is worth fixing. A small crate such as bitflags compiled twice costs little. Concentrate on large duplicates such as syn, tokio, hyper or windows-sys.
Weigh the cost of a new dependency
Before you add a crate, ask what it brings with it.
| Question | What to check |
|---|---|
| How many crates does it add? | `cargo tree -p <crate>` after adding it, or on crates.io under "Dependencies" |
| Does it need proc macros? | Look for `syn`, `quote` or `proc-macro2` in its tree |
| Can you turn features off? | Read its `[features]` table |
| How much of it will you use? | A one-function helper may be 10 lines of your own code |
| Is it already in the graph? | `cargo tree --invert <crate>` |
A dependency that is already in your tree through another crate costs almost nothing extra. A new dependency that brings its own copy of syn can add several seconds to every clean build.
A worked example
Suppose cargo build --timings shows reqwest and its dependencies taking 40 seconds. You only make plain HTTPS GET requests with JSON responses.
- Run
cargo tree -p reqwest --depth 1to see what it pulls in. - Read reqwest's
[features]table. The defaults include things such as cookie support and compression that you don't use. - Change the declaration:
[dependencies]
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }- Run
cargo cleanandcargo build --timingsagain and compare the totals. - Run
cargo tree --duplicatesto confirm you did not introduce a second TLS stack.
The exact gain depends on the crate version and your other dependencies. The workflow is the point: measure, change one thing, measure again.
Common mistakes
- Trimming features that another crate re-enables. The build looks unchanged because of feature unification. Check the inverted feature tree first.
- Removing a crate flagged by
cargo machetethat a macro needs. Always rebuild all targets. - Optimizing a crate that was never slow. Look at the timings chart before you edit.
- Forgetting
Cargo.lock. For applications, commit it so everyone builds the same graph. Changes to the lockfile can add or remove duplicate versions.
Exercise
Your Cargo.toml sets default-features = false on serde, but cargo tree -e features still shows serde's std feature enabled. What is the most likely reason, and which command helps you find the cause?
Show answer
Feature unification. Another crate in the dependency graph requests serde with std, and Cargo compiles serde once with the union of all requested features. Run cargo tree -e features --invert serde to see which crate enables the feature, then change or update that dependency, or accept the feature if it cannot be avoided.
Exercise
cargo tree --duplicates shows syn 1.x and syn 2.x both in your build. Name two steps you can take to reduce this, and explain why it matters for build time.
Show answer
Run cargo tree --invert syn@1 to find which dependencies still use syn 1, then update those crates to versions that use syn 2 (with cargo update or by raising version requirements), or replace them. It matters because each version is compiled separately, and syn is a large crate that sits early in the graph, so compiling it twice adds time to every clean build.