Understanding #[tokio::main]
Learn what the
When you write an Axum application, the very first thing you put on your main function is usually #[tokio::main]. If you have never seen this before, it can look like magic. This page explains exactly what that line does, why it must be there, and what happens if you get it wrong.
We start with the problem this macro solves. Then we walk through the simplest possible example, look inside how the macro works, show a manual alternative, and finish with the mistakes beginners make most often.
Why a Normal main Function Cannot Run Axum Code
Rust programs normally start with a main function that is synchronous. That means it runs from top to bottom without pausing. Axum handlers, on the other hand, are asynchronous functions. An async function does not run all at once; it returns a future that must be polled to completion.
A future is a value that represents work that will finish later. To actually execute that work, you need something that drives the future forward. That driver is called an async runtime.
Axum is built on top of Tokio, which is an async runtime for Rust. If you write a normal main and call an async function inside it without awaiting the result, nothing drives the future to completion - the async work simply never runs.
Here is an example that shows the problem:
// src/main.rs - this compiles, but say_hello never runs
async fn say_hello() {
println!("Hello");
}
fn main() {
say_hello(); // This creates a future and immediately drops it!
println!("Main finished");
}
When you run this, you will only see Main finished. The async function say_hello creates a future, but that future is never polled, so the println! inside it never runs. The compiler does warn you - unused implementer of 'Future' that must be used with the note futures do nothing unless you '.await' or poll them - but a warning is not an error, so the program still builds and runs. The key idea is: async code does not run by itself; something must actively drive it.
If you try to fix it by adding .await in a normal main, you hit a real compile error instead:
// src/main.rs - this will NOT compile
async fn say_hello() {
println!("Hello");
}
fn main() {
say_hello().await;
}
error[E0728]: `await` is only allowed inside `async` functions and blocks
A synchronous main cannot await anything, and there is no runtime to poll the future. Either way - dropped future or forbidden .await - the async code has nowhere to run.
Tokio provides that driver, and #[tokio::main] is the simplest way to connect your normal main function to Tokio's runtime.
What #[tokio::main] Does
#[tokio::main] is an attribute macro. Macros in Rust are code that writes other code. This particular macro takes your async fn main() and transforms it into a normal synchronous fn main() that creates a Tokio runtime and runs your async code on it.
Think of it as a bridge between the synchronous world that the operating system expects and the asynchronous world that Axum and Tokio live in. When you write:
#[tokio::main]
async fn main() {
// async code here
}
The macro expands to something like this (simplified):
fn main() {
tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.unwrap()
.block_on(async {
// your async code here
});
}
The important part is block_on. That method takes a future, runs it to completion, and waits for the result. So the runtime keeps polling your main future until it finishes, then the process exits normally.
In an Axum application, that future contains the server setup and the call to axum::serve, which never completes until the server is shut down. So block_on effectively keeps your program alive and serving requests.
Why an Attribute Macro?:
Attribute macros are a clean way to hide boilerplate. Without #[tokio::main], every Axum program would need the same 10 lines of runtime setup. The macro keeps your code short and focused on your actual application logic.
The Simplest Working Example
Let's start with the smallest possible program that uses #[tokio::main] and actually does something asynchronous. This example has no Axum yet - it just prints a message after waiting for one second. That small delay proves the async runtime is working.
// src/main.rs
use tokio::time::{sleep, Duration};
#[tokio::main]
async fn main() {
println!("Starting async work...");
sleep(Duration::from_secs(1)).await;
println!("One second has passed.");
}
Here is what happens step by step:
use tokio::time::{sleep, Duration};brings in Tokio's async sleep function and theDurationtype.#[tokio::main]tells Rust to replace themainfunction with a version that creates a Tokio runtime.async fn main()makesmainan async function, which means it returns a future.- Inside,
sleep(Duration::from_secs(1)).await;pauses execution for one second without blocking the whole program. The.awaittells the runtime "I'm waiting; go do other work if there is any." - After the pause, it prints the second line.
When you run this with cargo run, you will see both lines appear, with a noticeable one-second delay between them. That delay is the proof that the async runtime is actively driving the sleep future.
You Know It's Working:
If you see "Starting async work..." followed by "One second has passed." after a pause, then #[tokio::main] has correctly set up the Tokio runtime and executed your async code.
The Axum Hello World Example
Now let's apply #[tokio::main] to an actual Axum server. This is the standard "Hello, World!" that appears in the official Axum documentation.
// src/main.rs
use axum::{
routing::get,
Router,
};
#[tokio::main]
async fn main() {
// Build the application router
let app = Router::new().route("/", get(|| async { "Hello, World!" }));
// Bind to a local address
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
// Run the server
axum::serve(listener, app).await.unwrap();
}
Look at the first line inside main: let app = Router::new().route(...). This creates the Axum router and defines what happens when someone visits the root path. Then we bind a TCP listener to 127.0.0.1:3000. Binding is an async operation, so we use .await. Finally, axum::serve(listener, app).await starts the server and waits for it to finish.
All of these .await points would be impossible without an async runtime. #[tokio::main] sets up that runtime before any of this code runs, and it makes sure the runtime keeps running until the server stops.
Do Not Forget async on main:
If you write #[tokio::main] but then declare fn main() instead of async fn main(), the macro will fail to compile. The macro expects to find an async function to transform. Always make sure the function is async fn main().
How the Macro Works Internally
Understanding the internals is not required to use the macro, but it helps remove the "magic" feeling. Let's break down what the macro actually does under the hood.
When you write:
#[tokio::main]
async fn main() {
println!("Hello from async main");
}
The compiler, with the help of the macro, sees something equivalent to:
fn main() {
let rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(async {
println!("Hello from async main");
});
}
The Runtime::new() call creates a multi-threaded Tokio runtime by default. block_on takes the async block and runs it on that runtime until it completes. This is why your async code executes normally even though main itself is synchronous.
The macro does more than this, such as enabling all I/O and time drivers, but the core idea is the same. The macro hides the boilerplate of creating and starting a runtime, letting you focus on your application code.
A Mental Model for Beginners:
Imagine you want to bake a cake, but your kitchen only has a microwave. The Tokio runtime is like an oven. #[tokio::main] is the instruction that says "install an oven before you start reading the recipe." Without it, your async cake batter would never bake.
Choosing a Runtime Flavor
The Tokio runtime can operate in two main modes: multi-thread and current-thread. #[tokio::main] defaults to multi-thread, but you can explicitly choose the other mode.
Multi-thread runtime (default)
The multi-thread runtime uses a pool of worker threads to run async tasks in parallel. This is ideal for network servers like Axum because it can handle many connections at once across multiple CPU cores.
// default
#[tokio::main]
async fn main() {
// ...
}
You can also be explicit:
#[tokio::main(flavor = "multi_thread")]
async fn main() {
// ...
}
Current-thread runtime
The current-thread runtime runs all async tasks on the single thread that started the program. This uses less overhead and is fine for simple scripts, tests, or embedded environments where you don't need true parallelism.
#[tokio::main(flavor = "current_thread")]
async fn main() {
// ...
}
For a typical Axum web server, you should stick with the default multi-thread runtime. It lets the server handle multiple requests genuinely at the same time, which matters when one request is waiting for a database or file system.
Current-thread Can Block Everything:
If you use the current-thread runtime and then perform a blocking operation (like reading a large file with std::fs::read instead of tokio::fs::read), your entire server will freeze until that operation finishes. Multi-thread is safer for servers, though you should still avoid blocking calls in async code.
Manual Runtime Setup as an Alternative
To truly understand what #[tokio::main] saves you from, it helps to see the manual version. Here is the same Axum hello world without using the macro:
// src/main.rs
use axum::{
routing::get,
Router,
};
fn main() {
let rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(async {
let app = Router::new().route("/", get(|| async { "Hello, World!" }));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
});
}
This code does exactly the same thing as the macro version. It creates a Runtime, then calls block_on with an async block containing the server setup. When you run it, you get the same server on 127.0.0.1:3000.
So why do almost all tutorials use #[tokio::main] instead? Because it is cleaner, shorter, and less error-prone. The manual version also requires you to remember to call block_on and to create the runtime with all the right features enabled. The macro handles all of that for you.
Manual Setup Requires Extra Care:
If you choose manual runtime setup, you must ensure the runtime has the rt-multi-thread feature enabled in your Cargo.toml. Without it, Runtime::new() does not exist at all and your code fails to compile with no associated function or constant named 'new' found for struct 'Runtime'. The macro also requires this feature, but it gives you a clearer compile error if the feature is missing (The default runtime flavor is 'multi_thread', but the 'rt-multi-thread' feature is disabled), which is easier to fix.
Common Mistakes and How to Fix Them
Beginners often hit the same four problems when using #[tokio::main]. Here they are with the exact error you might see and the solution.
Mistake 1: Missing tokio features
By default, Tokio does not include all its functionality. To use #[tokio::main], you need at least the macros and rt-multi-thread features. If you added tokio to your Cargo.toml with cargo add tokio but no features, you will get an error like:
error[E0433]: cannot find `main` in `tokio`
That error means the macros feature is off, so the tokio::main macro does not exist. If instead the macro exists but the rt-multi-thread feature is missing, you will see a different compile error:
error: The default runtime flavor is `multi_thread`, but the `rt-multi-thread` feature is disabled.
The fix is to enable the features. The easiest way is to use the full feature, which enables everything:
# Cargo.toml
[dependencies]
tokio = { version = "1", features = ["full"] }
axum = "0.8"
Or, if you want only what you need:
# Cargo.toml
[dependencies]
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
axum = "0.8"
For an Axum project, full is the simplest choice and avoids hunting for missing features later.
Feature Missing Is a Compile Error, Not a Runtime Error:
The missing feature problem appears when you compile, not when you run. That is actually good: you catch it early. Always check your Cargo.toml if you see "cannot find main in tokio".
Mistake 2: Forgetting to make main async
You might write:
#[tokio::main]
fn main() {
// ...
}
The macro expects an async function. You will get an error like:
error: the async keyword is missing from the function declaration
Fix it by adding async:
#[tokio::main]
async fn main() {
// ...
}
Mistake 3: Thinking #[tokio::main] only works on main
The macro is normally used on main, but it is not restricted to it. You can put it on any async function, like this:
#[tokio::main]
async fn my_helper() {
// ...
}
That compiles and runs: calling my_helper() behaves like a synchronous function, because the macro builds a fresh runtime and blocks on the async body each time it is called. That is convenient for small scripts and tests, but do not call such a function from code that is already running on a Tokio runtime - starting (and blocking on) a second runtime from inside async code panics, as described in Mistake 4. In an Axum application, keep #[tokio::main] on main itself.
Mistake 4: Nesting runtimes
If you try to call #[tokio::main] twice, for example by having one async function that internally tries to create another runtime, you will get a runtime panic: "Cannot start a runtime from within a runtime." Beginners rarely hit this in a simple Axum project, but it's good to know that you should not try to manually create a Tokio runtime inside code that is already running on one.
What You See When It Works
After fixing any mistakes, running your Axum program with cargo run should produce output similar to this:
Compiling my-axum-app v0.1.0
Finished dev [unoptimized + debuginfo] target(s) in 0.85s
Running `target/debug/my-axum-app`
And then nothing else. The server is now running and waiting for requests. There is no "Server started" line unless you add one yourself with println!. To confirm it works, open a web browser and go to http://127.0.0.1:3000. You should see:
Hello, World!
Or use curl:
curl http://127.0.0.1:3000
You will see the same text. The fact that the program did not exit immediately is the runtime at work. The axum::serve(...).await future never completes on its own; it waits for incoming connections. The #[tokio::main] macro has set up the runtime, and block_on is holding the program in that waiting state.
Your Program Stays Alive:
The server staying alive and responding is the clearest sign that #[tokio::main] is doing its job. If the program exited immediately, the runtime would have nothing to block on and would shut down before serving anything.
The Relationship Between #[tokio::main] and Async Handlers
Now that you understand the macro, it's worth connecting it to the rest of your Axum code. Handlers in Axum are also async functions. They are not decorated with #[tokio::main] because they do not start the program; they run inside the runtime that #[tokio::main] created.
For example, your handler might look like this:
async fn hello() -> &'static str {
"Hello"
}
This function returns a future. Axum knows how to poll that future because the runtime is already active. Without #[tokio::main] at the top of main, there would be no runtime, and Axum would have no way to execute your handler.
So #[tokio::main] is the single entry point that lights up the entire async ecosystem inside your Axum application.
Summary
The #[tokio::main] attribute macro is small but essential. It turns a normal synchronous main function into one that starts a Tokio async runtime, runs your async main function to completion, and keeps the process alive as long as your server future is pending.
You should remember three things:
- Always place
#[tokio::main]on yourasync fn main()in the crate root. - Ensure your
Cargo.tomlincludes thetokiofeatures needed (fullis easiest). - Prefer the default multi-thread runtime for Axum web servers.
Once you internalize those points, you can focus on building routes and handlers without worrying about the runtime plumbing that makes them work. The macro is a small piece of syntax that unlocks the entire asynchronous world Axum depends on, and understanding it gives you a solid foundation for everything that follows in your Axum journey.