Sub topic 9
Split Large Crates into a Workspace
This chapter assumes you can build and test a Rust project with Cargo, read a Cargo.toml, and run cargo build --timings from the earlier chapters. It covers when splitting a crate speeds up builds, how to do it, and the mistakes that cancel the benefit.
Why crate boundaries matter for build time
The crate is the unit of compilation in Rust. Cargo passes one crate at a time to rustc, and rustc has to process the whole crate each time any of its source files change. Incremental compilation reduces that work, but a very large crate still pays for dependency tracking, type checking, and code generation scheduling.
Splitting a large crate into several smaller crates in one workspace gives Cargo two things to exploit:
- Parallelism. Crates that do not depend on each other compile at the same time on different cores.
- Selective rebuilds. When you edit a crate, Cargo rebuilds that crate and the crates that depend on it. Crates it does not depend on, and crates below it in the graph, are left alone.
A single crate gets neither. Within one crate, the front end is mostly serial (unless you use the nightly parallel front end, covered in a later chapter), and any edit recompiles the crate.
Reading the timings before you split
Do not split by feel. Run the timing report first:
cargo build --timingsOpen target/cargo-timings/cargo-timing.html. Look for these signs:
- One crate bar that is much longer than the others, with other crates waiting behind it. That crate is on the critical path, and splitting it can help.
- Many cores idle while a single crate compiles. This means the dependency graph is too narrow to use your hardware.
- A crate that is rebuilt on almost every change, because it contains code that changes often next to code that rarely changes.
If the report shows that time is spent in the linker or in a few third-party dependencies, splitting your own code will not help much. Fix those first.
What a workspace is
A workspace is a set of crates that share one Cargo.lock, one target directory, and optionally shared metadata and dependency versions. The root Cargo.toml declares the members:
# Cargo.toml (workspace root)
[workspace]
resolver = "2"
members = ["app", "core", "storage"]
[workspace.dependencies]
serde = { version = "1", default-features = false, features = ["derive"] }The resolver = "2" line selects the feature resolver that keeps features of build-only and dev-only dependencies from leaking into your normal build. (In edition 2021 packages it is the default for single crates, but a virtual workspace manifest like this one has no edition, so you must set it explicitly.)
The [workspace.dependencies] table declares each shared dependency once. A member then opts in with workspace = true:
# core/Cargo.toml
[package]
name = "core"
version = "0.1.0"
edition = "2021"
[dependencies]
serde = { workspace = true }This keeps versions and features identical across members, which avoids compiling the same dependency twice with different feature sets.
A concrete layout
Suppose a single crate named app contains domain types, a storage layer, and the binary entry point. A split might look like this:
.
├── Cargo.toml
├── Cargo.lock
├── app/ # binary, thin: argument parsing and wiring
├── core/ # domain types and logic, no I/O
└── storage/ # database access, depends on coreThe dependency graph is:
With this layout:
- Editing
apprebuilds onlyappand relinks the binary. - Editing
storagerebuildsstorageandapp. - Editing
corerebuilds all three, because everything depends on it.
The last case is the important one. The crate at the bottom of the graph is the most expensive to touch. Put stable, rarely changed code there, and keep volatile code near the top.
Rules for choosing where to cut
Good boundaries follow these rules:
- Cut along the dependency graph, not along folders. A module that many other modules use should become a low-level crate. A module used by one consumer can stay with that consumer.
- Separate fast-changing from slow-changing code. Business rules you edit daily should not share a crate with a large generated parser that you edit monthly.
- Keep the crate at the bottom small and stable. A shared
typesorcorecrate with few dependencies is cheap to rebuild and rarely invalidates anything. - Make the binary crate thin. The binary is always relinked. If it contains little code, relinking is the main cost, and your edit loop stays short.
- Isolate heavy dependencies. If one crate pulls in a large dependency (for example a web framework or a database driver), put that use behind one crate. Other crates then do not depend on it and do not wait for it.
Mistakes that cancel the benefit
A "god" crate at the bottom
If every crate depends on a large common crate, any change to common rebuilds everything. Splitting then adds overhead and gives no parallelism, because the graph is a chain. Check the timing chart: if crates still compile one after another, the graph is too serial.
Cyclic pressure
Cargo does not allow dependency cycles between crates. If two modules call each other, you cannot put them in separate crates directly. Common fixes are to move the shared types into a third crate that both depend on, or to define a trait in the lower crate and implement it in the upper one. Do not contort the design only for build time. If the cycle is real, keep those modules together.
Generics across crate boundaries
Generic functions are compiled in the crate that uses them, not the crate that defines them. A generic function in core called from app is instantiated in app. Splitting the code does not move that cost. Also, #[inline] and generic code force the defining crate to expose its function bodies, so a small edit to such a function invalidates every dependent crate. Prefer non-generic APIs at crate boundaries where possible (see the chapter on monomorphization).
Too many tiny crates
Each crate has fixed costs: metadata generation, a separate rustc process, and linking of its rlib. Dozens of crates with a few hundred lines each can be slower than a few mid-sized ones. A practical target is crates that take at least a few seconds to compile. Smaller than that, the overhead dominates.
Inconsistent features
If two members request the same dependency with different features, Cargo unifies them to the union in a single build, but building one member alone (cargo build -p storage) can produce a different feature set and a separate compilation of that dependency. Use [workspace.dependencies] so every member asks for the same thing.
Building only what you need
Workspaces let you scope commands to part of the graph:
# Check only the storage crate and what it depends on
cargo check -p storage
# Test only the core crate
cargo test -p core
# Build everything, run in parallel across crates
cargo build --workspaceDuring development, cargo check -p <crate> on the crate you are editing is often the fastest loop, since Cargo skips crates that are not in its dependency tree.
Be aware of one trap: running cargo build at the workspace root of a non-virtual workspace builds only the root package by default. Use --workspace when you want every member, and use default-members in the root manifest to choose what a bare cargo build covers:
[workspace]
resolver = "2"
members = ["app", "core", "storage"]
default-members = ["app"]Shared profile settings
Profiles are set only in the workspace root Cargo.toml. Profile sections in member manifests are ignored, and Cargo prints a warning. Put the settings from the earlier chapters in the root, and use per-package overrides to treat members differently:
# Cargo.toml (workspace root)
[profile.dev]
debug = "line-tables-only"
# Optimize a numeric-heavy member even in dev builds.
[profile.dev.package.core]
opt-level = 2Measuring the result
After the split, repeat the same measurements you took before:
- Run
cargo clean, thencargo build --timingsand compare the total time and core usage. - Touch a file in a leaf crate (
app), runcargo build, and note the time. - Touch a file in the bottom crate (
core), runcargo build, and note the time.
The leaf edit should be much faster than before. The bottom edit may be equal or slightly slower. If the bottom edit is the one you do most often, move that code upward in the graph.
Exercise
A workspace has crates app, domain, and common. Both app and domain depend on common, and domain also depends on app's helper functions. You edit common all day and find that every build recompiles the whole workspace. Name two problems with this layout and one change for each.
Show answer
First, domain depends on app, and app depends on domain's types, which is a dependency cycle that Cargo rejects. Move the shared helpers into a lower crate (for example common or a new helpers crate) that both can depend on. Second, common is at the bottom of the graph and changes often, so each edit rebuilds everything above it. Move the frequently edited code up into a crate nearer the top (such as domain or app), and keep only stable code in common.
Exercise
You split a project into 30 crates of about 200 lines each. A clean build gets slower, and cargo build --timings shows many short bars with gaps between them. What is the likely cause, and what do you do?
Show answer
The per-crate fixed costs (starting rustc, writing and reading metadata, linking rlib files) are larger than the compile work in each crate, and the dependency graph forces some crates to wait on others. Merge small crates that are always changed together or always used together into fewer, mid-sized crates, and verify with another cargo build --timings run.