tokio feature trimming

Learn how Tokio feature flags work, which features an Axum server actually needs, and how to trim the rest to shrink compile time and binary size

Tokio feature trimming means choosing exactly which parts of Tokio get compiled into a project, instead of turning them all on with the full feature. Tokio is built as a set of optional modules, and each module is switched on by a feature flag in Cargo.toml. A server that only listens on a socket and answers requests does not need file handling, process spawning, or signal handling compiled in, so leaving those features off produces a smaller binary and a faster build.

Where This Fits

The previous pages built the release binary and looked at its size. The binary is small, but it still contains every Tokio module the full feature turns on, including several the server never calls. This page opens the Cargo.toml file and removes the parts that are not used, measuring the difference as it goes. Nothing about the server changes: the same routes answer the same way. Only the list of compiled-in Tokio pieces changes.

Think of the full feature like buying a whole toolbox when the job only needs a hammer and a screwdriver. The extra tools are not harmful, but they take up space in the bag and time to pack. Trimming is opening the toolbox, taking out the tools the job needs, and leaving the rest on the shelf.

The Smallest Working Version First

Start with the usual small server, first with the full feature and then with a trimmed list. The server code is identical in both cases.

src/main.rs
use axum::{routing::get, Router};

#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(|| async { "Hello, release world!" }));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

With the full feature, the dependency line looks like this:

Cargo.toml
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }

Build it and measure it:

cargo build --release
ls -l target/release/axum-ch22-scratch

On the machine used to check this page, with axum 0.8.9 and tokio 1.54.1 under Rust 1.100.0, the release binary was 1,866,800 bytes.

Now replace the full feature with the two features this server actually uses directly:

Cargo.toml
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }

Build it again and measure it:

cargo build --release
ls -l target/release/axum-ch22-scratch

The trimmed release binary on the same machine was 1,793,808 bytes, which is 72,992 bytes smaller. The server still runs, and curl http://127.0.0.1:3000/ still answers Hello, release world!. The saving is modest on a small project, because most of the binary is Axum, Hyper, and the Tokio pieces the server genuinely needs. The saving grows on larger projects, and the compile time saving is often the more noticeable win.

Trimming Worked:

If the trimmed build finishes, the binary exists, and curl returns the greeting, the trimmed feature list is enough for this server. Those three checks are the whole test: it compiles, it runs, and it answers.

What a Feature Flag Is

A feature flag is a named switch in a crate's Cargo.toml that turns a piece of that crate on or off. When a feature is off, the code behind it is not compiled at all. It does not sit unused in the binary, and its own dependencies are not downloaded or compiled either. When a feature is on, the code is compiled in and its dependencies come along with it.

Features are additive. If two crates in the same project ask for different features of Tokio, Cargo turns on the union of both lists. Turning a feature off in one place does not turn it off for the whole project if something else still asks for it. That rule is the single most important thing to understand about trimming, because it explains most of the surprises beginners meet when they try it.

Tokio ships with no features enabled by default. The default feature list is empty, which is unusual: most crates turn something on by default, but Tokio leaves the choice entirely to the project. The full feature is a convenience shortcut that turns on everything stable. The Tokio documentation recommends full for people who are new to Tokio, because it removes the whole question of which feature a given piece of code needs. Trimming is what a project does later, once it knows which pieces it uses.

The Tokio Feature List

The table below lists the features from the Tokio 1.54.1 crate manifest, with what each one enables. The features a beginner meets first are at the top. The last two rows are not part of full.

FeatureWhat it enables
fullEvery feature below except test-util and tracing
rtThe basic runtime, tokio::spawn, and the current-thread scheduler
rt-multi-threadThe multi-threaded work-stealing scheduler, needs rt
macros#[tokio::main], #[tokio::test], select!, join!, try_join!
nettokio::net, including TcpListener, TcpStream, and UdpSocket
timetokio::time, including sleep, interval, and timeout
synctokio::sync, including Mutex, mpsc, oneshot, and watch
fstokio::fs, including async file reading and writing
io-utilAsync I/O helper traits such as AsyncReadExt
io-stdAsync Stdin, Stdout, and Stderr
signaltokio::signal, including ctrl_c
processSpawning and managing child processes
parking_lotFaster locking primitives from the parking_lot crate
test-utilTesting helpers such as paused time, not in full
tracingIntegration with the tracing crate, not in full

Reading the table row by row gives a beginner the whole map. The runtime features (rt, rt-multi-thread) decide how tasks are scheduled. The macros feature decides whether the #[tokio::main] attribute exists. The I/O features (net, fs, io-util, io-std) decide which kinds of input and output exist. The rest (time, sync, signal, process) decide which utilities exist.

What Axum Turns On by Itself

The trimmed example above lists only two features, yet the server works, and it uses networking, timers, and synchronisation primitives that those two features do not provide. The reason is that Axum turns on Tokio features of its own, and Cargo takes the union of every request.

Axum 0.8.9, with its default tokio feature enabled, asks for tokio/net, tokio/rt, and tokio/macros, plus the hyper-util crate with its own tokio feature. That hyper-util feature in turn asks for tokio/rt and tokio/time, because Hyper needs timers to manage connections. Hyper itself asks for tokio/sync. So the real feature set of the trimmed project is larger than the two words written in its Cargo.toml. Running cargo tree -e features -i tokio shows the full picture: the tree lists every Tokio feature that ends up enabled and which crate asked for it.

The practical consequence is that trimming has a floor. No matter how short the project's own feature list is, Axum's needs set a minimum: a runtime, networking, the macros, timers, and synchronisation. Those pieces are not optional for an Axum server, because the server itself is built from them. Trimming removes what is above that floor, not what is below it.

The Floor Is Set by Axum:

A trimmed list of ["macros", "rt-multi-thread"] does not mean only two Tokio features are compiled. It means the project asks for two, and Axum, Hyper, and Hyper-Util ask for the rest of what a server needs. The compiled set is the union of all of those requests.

The Concept Behind Conditional Compilation

The mechanism that makes feature flags work is conditional compilation. The Tokio source code marks each module with the feature that gates it, and the compiler skips any module whose feature is off. The skipped code never becomes machine code, never reaches the linker, and never lands in the binary. The module also disappears from the public API, which is why using a gated piece of Tokio without its feature is a compile error rather than a runtime failure.

The mental model is a book with chapters that can be torn out before printing. The full feature prints the whole book. A trimmed list prints only the chapters the reader asked for. A reference to a torn-out chapter is caught at print time, not when someone tries to read it, because the chapter simply is not there.

Why Trimming Matters

Trimming matters for three reasons, and binary size is the smallest of them. The first is compile time: every feature compiles more code and pulls in more dependencies, and signal pulls in signal-hook-registry, net pulls in mio and socket2, and process pulls in bytes. A project that never uses those crates should not pay to compile them on every build. The second is the size of the dependency tree: fewer features means fewer crates to download, audit, and keep up to date, which matters when the project is built on a fresh machine or in a container. The third is binary size, which the measurement above shows is real but modest on a small server.

There is also a clarity benefit. A Cargo.toml that lists the features the project uses is a small piece of documentation. A reader can see at a glance that the server uses networking, timers, and file access, and that it does not spawn child processes. That list is honest in a way the word full is not.

Adding a Feature Back When the Code Needs It

Trimming is not a one-time decision. As the server grows, it will need features that the first list left out, and the fix is to add the feature name to the list. The three examples below each add one feature for one real need, and each one is a complete, runnable step.

Reading a file needs fs

A route that reads a file from disk needs tokio::fs, and that module only exists when the fs feature is on:

Cargo.toml
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["macros", "rt-multi-thread", "fs"] }
src/main.rs
use axum::{routing::get, Router};

#[tokio::main]
async fn main() {
    let app = Router::new().route("/note", get(read_note));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

async fn read_note() -> String {
    tokio::fs::read_to_string("note.txt")
        .await
        .unwrap_or_else(|_| "No note file found.".to_string())
}

Create a file called note.txt next to Cargo.toml with one line of text, then build and run the server. A request to /note returns the contents of the file, and a missing file returns the fallback message. The handler uses tokio::fs::read_to_string, which reads the file without blocking the runtime while the operating system fetches the bytes. Without the fs feature, this file does not compile, and the compiler says so plainly, as the mistakes section below shows.

Waiting needs time, and it is already there

A handler that pauses before answering needs tokio::time::sleep, and the time feature gates that function:

src/main.rs
use axum::{routing::get, Router};

#[tokio::main]
async fn main() {
    let app = Router::new().route("/slow", get(slow));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

async fn slow() -> &'static str {
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;
    "That took half a second."
}

A request to /slow takes about half a second and then returns the message. The interesting detail is that this code compiles even when time is not in the project's own feature list. The reason is the union rule from earlier: Hyper-Util already turns time on, because it needs timers for its own work, so the feature is present whether the project asks for it or not. Adding "time" to the list changes nothing about the build, but it does make the project's dependence on timers visible to the next person who reads Cargo.toml. That visibility is worth the one word.

Catching Ctrl+C needs signal

A server that shuts down cleanly on Ctrl+C needs tokio::signal::ctrl_c, and that function only exists when the signal feature is on:

Cargo.toml
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["macros", "rt-multi-thread", "signal"] }
src/main.rs
use axum::{routing::get, Router};

#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(|| async { "Hello, release world!" }));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app)
        .with_graceful_shutdown(shutdown_signal())
        .await
        .unwrap();
    println!("Server stopped cleanly.");
}

async fn shutdown_signal() {
    tokio::signal::ctrl_c()
        .await
        .expect("failed to install Ctrl+C handler");
}

Run the server, press Ctrl+C, and the final line prints before the process exits. The signal feature pulls in the signal-hook-registry crate on Unix systems, which is the machinery that turns an operating system signal into an async event the runtime can wait on. A server that never handles signals should leave the feature off and skip that dependency entirely.

Choosing Between the Two Runtimes

The rt feature provides the current-thread scheduler, which runs all tasks on a single thread, and rt-multi-thread provides the work-stealing scheduler, which spreads tasks across one thread per CPU core. The #[tokio::main] attribute uses the multi-threaded scheduler by default, which is why the trimmed list needs rt-multi-thread. A small server that will only ever handle a few connections at a time can use the single-threaded scheduler instead, by naming the flavour in the attribute:

src/main.rs
use axum::{routing::get, Router};

#[tokio::main(flavor = "current_thread")]
async fn main() {
    let app = Router::new().route("/", get(|| async { "Hello, release world!" }));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}
Cargo.toml
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["macros", "rt"] }

That combination compiles and runs, and it was checked on the machine used for this page. The single-threaded runtime uses fewer threads and less memory, and it is a reasonable choice for a tiny service or a test harness. The multi-threaded runtime is the better default for a real server, because it uses all the CPU cores and keeps one slow request from blocking the rest. The choice is made in two places at once, the feature list and the attribute, and the two places must agree: a multi-threaded attribute with only rt enabled does not compile.

Flavour and Features Must Agree:

The #[tokio::main] attribute and the feature list describe the same decision. If the attribute asks for the multi-threaded scheduler, the rt-multi-thread feature must be on. If the attribute names the current-thread flavour, rt alone is enough. Changing one without the other is the most common trimming mistake after the missing-module errors below.

How the Features Flow into the Binary

The path from a feature list to a finished binary has one extra step compared with an ordinary build:

Cargo.toml feature list
        |
        v
Cargo takes the union of every crate's requests
        |
        v
rustc compiles only the Tokio modules whose
features are on, plus their dependencies
        |
        v
linker joins the compiled modules into the binary
        |
        v
target/release/<name> contains only the enabled parts

The union step is where trimming is won or lost. A project can write the shortest possible list and still compile the time feature, because Hyper-Util asked for it. The cargo tree command is the tool that shows the union as it really is, rather than as the project's own Cargo.toml suggests.

Inspecting the Real Feature Set

The command below prints the feature tree for Tokio and shows which crate enabled each feature:

cargo tree -e features -i tokio

The output lists entries such as tokio feature "net" followed by the crates that asked for it. Reading it after trimming is the honest way to check the result: if a feature the project tried to remove still appears in the tree, some dependency in the tree still needs it, and removing it from the project's own list did not remove it from the build. That is not a failure of trimming. It is the union rule working as designed, and the feature stays because the server genuinely needs it through that dependency.

Testing a Trimmed Build

A trimmed build is tested the same way as any other build: compile it, run it, and ask every route for its response. The feature list changes what is compiled, not what the routes do, so the smoke test from the first page still applies:

cargo build --release
./target/release/axum-ch22-scratch
curl http://127.0.0.1:3000/

If the project has a test suite, run it under the trimmed features too:

cargo test

A test that uses a Tokio helper from a feature the project removed will fail to compile, which is the test suite catching the same mistake the server code would have caught. Fix it by adding the feature, not by going back to full, because each added feature names exactly what the project needs.

Common Beginner Mistakes

Using a module whose feature is off

// Wrong - fails to compile when the signal feature is off
async fn shutdown_signal() {
    tokio::signal::ctrl_c().await.unwrap();
}

The compiler rejects this with a precise error, and the error was reproduced on the machine used to check this page:

error[E0433]: cannot find `signal` in `tokio`
error: could not compile `axum-ch22-scratch` (bin "signal_demo") due to 1 previous error

The same error appears for tokio::fs when the fs feature is off:

error[E0433]: cannot find `fs` in `tokio`
error: could not compile `axum-ch22-scratch` (bin "fs_demo") due to 1 previous error

E0433 is the compiler's code for a failed path resolution, and here it means the module does not exist in this build because its feature is off. The fix is to add the feature name to the list in Cargo.toml. The error message names the missing module, so the fix is usually one word.

E0433 Means a Missing Feature:

When the compiler says cannot find signal in tokio or cannot find fs in tokio, the code is fine and the feature list is short. Add the named feature to the tokio dependency in Cargo.toml and rebuild. Do not rewrite the code to avoid the module, unless the project genuinely does not need it.

Removing a feature from the list and expecting it to vanish

Dropping "time" from the project's feature list does not remove the time feature from the build, because Hyper-Util enables it. The sleep example above compiles either way, which surprises beginners who expect the list in their own Cargo.toml to be the whole story. The list is only the project's own request. The build uses the union of every request in the dependency tree, and cargo tree -e features -i tokio shows that union. Check the tree before concluding that a feature is gone.

Using #[tokio::main] without rt-multi-thread

The default #[tokio::main] attribute builds a multi-threaded runtime, and that runtime does not exist without the rt-multi-thread feature. Listing only ["macros", "rt"] and keeping the plain attribute produces a compile error from the macro, reproduced on the machine used to check this page:

error: The default runtime flavor is `multi_thread`, but the `rt-multi-thread` feature is disabled.
error: could not compile `axum-ch22-scratch` (bin "nort") due to 1 previous error

The fix is either to add "rt-multi-thread" to the list or to switch the attribute to flavor = "current_thread". Either fix works, and the choice between them is the runtime choice described above.

Going back to full at the first error

The first E0433 error tempts beginners to restore features = ["full"] and never trim again. That fixes the build, but it throws away the documentation value of the trimmed list and the compile time saving. The better habit is to read the error, add the one named feature, and rebuild. After two or three such rounds, the list settles on exactly what the project uses, and it stays stable as the project grows, with one new feature added each time a new need appears.

Trimming features in a library crate

A library crate that depends on Tokio should enable only the features its own code uses, and leave the rest to the final binary. The reason is the union rule again: a library that asks for full forces every project that uses it to compile all of Tokio, even if the project itself needs only a little. A binary crate, such as an Axum server, is the place where the full list is decided, because the binary is the end of the dependency tree and nobody else inherits its choices.

A Richer Complete Example

A server that reads a file, waits, and shuts down cleanly needs four features beyond the floor Axum sets: fs for the file, signal for the shutdown, and the two the project always lists, macros and rt-multi-thread. The time feature is listed too, so the project's dependence on timers is visible even though Hyper-Util would turn it on anyway.

Cargo.toml
[package]
name = "axum-trimmed-demo"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["macros", "rt-multi-thread", "time", "fs", "signal"] }
src/main.rs
use axum::{routing::get, Router};

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(home))
        .route("/slow", get(slow))
        .route("/note", get(read_note));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app)
        .with_graceful_shutdown(shutdown_signal())
        .await
        .unwrap();
    println!("Server stopped cleanly.");
}

async fn home() -> &'static str {
    "Hello, release world!"
}

async fn slow() -> &'static str {
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;
    "That took half a second."
}

async fn read_note() -> String {
    tokio::fs::read_to_string("note.txt")
        .await
        .unwrap_or_else(|_| "No note file found.".to_string())
}

async fn shutdown_signal() {
    tokio::signal::ctrl_c()
        .await
        .expect("failed to install Ctrl+C handler");
}

Build it, run it, and check each route:

cargo build --release
./target/release/axum-trimmed-demo
curl http://127.0.0.1:3000/
curl http://127.0.0.1:3000/slow
curl http://127.0.0.1:3000/note

The home route answers at once, the slow route answers after half a second, and the note route answers with the contents of note.txt. Pressing Ctrl+C prints the clean shutdown line. Every feature in the list earns its place: remove fs and the note route stops compiling, remove signal and the shutdown function stops compiling, remove rt-multi-thread and the #[tokio::main] attribute stops compiling.

Final Complete Example

The smallest honest starting point for a new Axum server, with the trimmed list the rest of the page justifies:

Cargo.toml
[package]
name = "axum-trimmed-demo"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
src/main.rs
use axum::{routing::get, Router};

#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(|| async { "Hello, release world!" }));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

Build it, run it, and measure it:

cargo build --release
./target/release/axum-trimmed-demo
curl http://127.0.0.1:3000/

That list is the floor for an Axum server: the macros that start the runtime, the multi-threaded scheduler the default attribute builds, and everything Axum, Hyper, and Hyper-Util add on top. Add a feature when a new need appears, and check the result with cargo tree -e features -i tokio when a removal does not seem to take effect.

Summary

Feature trimming is a conversation between the project and its dependencies, not a list the project writes alone. The project asks for the features its own code uses, the dependencies ask for the features theirs uses, and Cargo compiles the union. The full feature skips that conversation by turning everything on, which is the right choice while learning, and the wrong choice once the project knows what it needs.

The decision framework follows from that picture. Start a new project with full and build the server first. When the routes work, replace full with the features the code actually touches, keeping macros and rt-multi-thread for the standard #[tokio::main] server, and let the compiler report what is missing. Each E0433 error names one feature to add back, and after a few rounds the list is exactly the project's needs plus the floor Axum sets. Check the real result with cargo tree -e features -i tokio, because the list in Cargo.toml is a request and the tree is the answer. That habit keeps the build honest: every feature in the list is there because some code in the project, or some crate the project depends on, genuinely uses it.