The tokio main Macro in Axum Projects

Understand the

Axum applications are built on top of Tokio, an asynchronous runtime for Rust. The #[tokio::main] macro sits at the top of your main function and is the entry point that connects your async Axum code to the Tokio runtime. This page revisits the macro in depth, explains what it actually does, and shows the different ways you can configure it to fit your project.

What Is the tokio::main Macro?

In Rust, the main function is special. By default, it must be a synchronous function returning (). You cannot write async fn main() in a normal Rust program without some extra setup, because the language itself does not have a built-in asynchronous executor. The #[tokio::main] macro solves this problem.

The macro is an attribute you place directly above your main function. It transforms your async fn main() into a regular synchronous main that creates a Tokio runtime and runs your async code inside it. This is the standard way to start an Axum server because the entire Axum stack, from TcpListener::bind().await to axum::serve().await, relies on async operations.

You have already seen this macro in the minimal main.rs file. Here is a refresher:

// src/main.rs
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
    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();
}

The #[tokio::main] line is not just a comment or an annotation for documentation; it actively rewrites your code during compilation. Without it, the compiler would complain that await cannot be used in a non-async function, or that main must return () and cannot be async.

Tokio Is the Runtime:

Tokio is an asynchronous runtime, which means it is a library that provides the scheduler and executor needed to run async functions. Rust's standard library has no executor built in, so you must bring one yourself. The #[tokio::main] macro is the most convenient way to set up that executor for the lifetime of your program.

Why Axum Needs an Async Runtime

Axum is built on top of the hyper HTTP library, which uses asynchronous I/O. When you call axum::serve(listener, app).await, you are asking the server to accept incoming TCP connections, parse HTTP requests, route them to handlers, and send responses - all without blocking the thread. This is possible only if the code runs inside an async runtime that can manage many tasks concurrently.

A normal synchronous main cannot execute await expressions. Trying to write this:

fn main() {
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
}

produces a compile error:

error[E0728]: `await` is only allowed inside `async` functions and blocks

Even if you make main async:

async fn main() {
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
}

you'll get another error because the Rust language specification says main must be a synchronous function with return type () (or Result in some cases, but still not async).

The #[tokio::main] macro bridges this gap. It takes your async main body, wraps it in a call to block_on on a newly created Tokio runtime, and exposes the result as a normal synchronous main. That way, the operating system sees a normal entry point, and your code gets to use await freely.

The Basic Usage: A Complete Example

Let's start with the smallest possible Axum project that uses the macro. We assume you already have a Cargo project named my-axum-app, and you have added axum and tokio to Cargo.toml.

The Cargo.toml should contain at least:

[package]
name = "my-axum-app"
version = "0.1.0"
edition = "2024"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }

Then src/main.rs looks like this:

use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(|| async { "Hello, 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();
}

When you run cargo run, the program starts, the macro sets up the Tokio runtime, and then the async body of main runs. It binds a TCP listener, prints a message, and calls axum::serve, which blocks (in an async sense) until the server is shut down. Pressing Ctrl-C will terminate the process.

It Works:

If you see the line Server running at http://127.0.0.1:3000 and the program does not immediately exit, the macro and the runtime have been set up correctly. You can open a browser to http://127.0.0.1:3000 and see "Hello, World!".

What the Macro Expands To (Conceptual)

You don't need to know the exact code the macro generates to use it, but understanding the shape helps you debug unexpected behavior.

Conceptually, the macro transforms this:

#[tokio::main]
async fn main() {
    // your async code
}

into something like this:

fn main() {
    let runtime = tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()
        .unwrap();
    runtime.block_on(async {
        // your async code
    });
}

The block_on method takes a future and runs it to completion on the runtime. The future is the body of your original async main. While that future is running, all other async tasks spawned inside it (for example, by axum::serve) are also scheduled and executed by the same runtime.

The actual expansion is more complex because the macro has to support different flavors, return types, and configuration attributes, but the core idea is exactly that: build a runtime, then block the current thread until the main future finishes.

Enabling the Required Tokio Features

The #[tokio::main] macro is not available unless the Tokio crate has the macros feature enabled. Additionally, the default multi-threaded runtime requires the rt-multi-thread feature. If you want to use the current_thread flavor, you also need the rt feature, but rt-multi-thread is not necessary for that.

The easiest way is to enable the full feature, which turns on everything:

tokio = { version = "1", features = ["full"] }

If you prefer to be more precise, you can list only what you need:

tokio = { version = "1", features = ["macros", "rt-multi-thread"] }

For a current-thread runtime only:

tokio = { version = "1", features = ["macros", "rt"] }

Missing Features Cause Confusing Errors:

If you forget to enable the macros feature, you'll get errors like error[E0433]: cannot find 'main' in 'tokio' and error[E0752]: 'main' function is not allowed to be 'async'. In an Axum project this rarely bites, because axum itself enables tokio's macros feature for the project, so #[tokio::main] resolves even if your own tokio line lists only rt-multi-thread. If you forget rt-multi-thread while using the default multi-thread flavor, the macro itself reports the problem at compile time: The default runtime flavor is 'multi_thread', but the 'rt-multi-thread' feature is disabled. Always double-check your Cargo.toml when you see these.

Choosing a Runtime Flavor

The macro can accept parameters that change how the runtime is built. The two main flavors are:

  • Multi-thread (default): uses multiple worker threads to execute async tasks. This is best for server applications like Axum, where you want to handle many requests in parallel across CPU cores.
  • Current-thread: runs all tasks on the current thread (the one that called block_on). This is lighter weight and useful for testing, small utilities, or when your application does very little CPU-heavy work.

You can specify the flavor using the flavor attribute:

#[tokio::main(flavor = "current_thread")]
async fn main() {
    // ...
}

You can also set the number of worker threads for the multi-thread runtime:

#[tokio::main(flavor = "multi_thread", worker_threads = 4)]
async fn main() {
    // ...
}

Let's look at complete examples for each flavor. We'll use a minimal Axum server for each.

// src/main.rs - default multi-threaded runtime
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(|| async { "Hello from multi-thread" }));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Each of these examples compiles and runs the same way. The difference is in how Tokio schedules tasks. A blocking call in a handler stalls one worker thread of the multi-thread runtime, so the other workers keep serving requests, while the current-thread runtime has only one thread, so a blocking call freezes the whole server. For an Axum server that will handle real traffic, the default multi-thread runtime is almost always the right choice.

Current-thread and Blocking Code:

If you use flavor = "current_thread" and then call a blocking operation (like std::thread::sleep or a synchronous database driver) inside a handler, the entire server will freeze because there is only one thread to run all tasks. The multi-thread runtime can offload blocking tasks to a separate blocking pool if you use tokio::task::spawn_blocking, but even then you need to use it correctly. For beginners, stick with the default multi-thread runtime.

Manual Runtime Setup (Without the Macro)

Although the macro is the standard approach, you can achieve the same result by manually creating a runtime inside a regular fn main. This is useful when you need fine-grained control over the runtime builder, or when you want to create the runtime once and reuse it later in the program.

Here is the equivalent of #[tokio::main]:

// src/main.rs - manual runtime setup
use axum::{routing::get, Router};
fn main() {
    let runtime = tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()
        .unwrap();
    runtime.block_on(async {
        let app = Router::new().route("/", get(|| async { "Hello from manual runtime" }));
        let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
            .await
            .unwrap();
        axum::serve(listener, app).await.unwrap();
    });
}

The enable_all() method turns on the I/O driver and the time driver, which are required for networking and timers. If you forget .enable_all(), the program panics as soon as it tries to use networking, with a message like A Tokio 1.x context was found, but IO is disabled. Call 'enable_io' on the runtime builder to enable IO.

You can also store the runtime in a variable and use it later, but for a simple server the macro is cleaner. The manual approach becomes relevant when you want to run multiple separate runtimes, or when you need to create the runtime with custom settings that the macro does not expose directly.

Returning Results from async main

In real applications, you often want to use the ? operator inside main to propagate errors. The macro supports an async main that returns a Result. For example:

// src/main.rs - async main returning Result
use axum::{routing::get, Router};
use std::error::Error;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let app = Router::new().route("/", get(|| async { "Hello, World!" }));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await?;
    axum::serve(listener, app).await?;
    Ok(())
}

Now you can use ? on any fallible async operation inside main. If an error occurs, the runtime is shut down and the error is returned to the operating system as the program's exit code. This is a common pattern in production Axum code.

Why Box<dyn Error>?:

Using Box<dyn Error> as the error type allows you to return any error type without specifying a single concrete type. This is convenient for a quick application, but in a larger project you may want to define your own error enum. For now, this keeps the example simple.

Common Mistakes and How to Avoid Them

Here are the most frequent errors beginners encounter with #[tokio::main]:

Forgetting the macro entirely

If you write an async main without the macro, you'll get:

error[E0752]: `main` function is not allowed to be `async`

Solution: add #[tokio::main] above main.

Using the macro on a non-async function

If you put the macro on a synchronous fn main(), you'll see:

error: the `async` keyword is missing from the function declaration

The macro expects an async function. Make sure main is declared with async fn.

Missing Tokio features

As mentioned earlier, if macros or the required runtime features are missing, you'll get confusing errors. Always verify your Cargo.toml.

Trying to call block_on inside an async context

The macro already runs your async code inside a runtime. If you try to create another runtime and call block_on inside an async handler, you will likely get a panic:

Cannot start a runtime from within a runtime. This happens because a function (like `block_on`) attempted to block the current thread while the thread is being used to drive asynchronous tasks.

This is a common mistake when combining multiple async libraries. In Axum, you never need to call block_on manually; the runtime is already there.

Assuming the runtime is single-threaded

By default, the macro uses a multi-thread runtime. If you have global mutable state that is not thread-safe (like static mut or a RefCell shared across tasks), you may encounter data races or compile errors if you try to use them across threads. Use Mutex, RwLock, or Arc to share state safely.

Do Not Use std::sync::Mutex Across Await Points:

If you hold a standard std::sync::MutexGuard across an .await, what goes wrong depends on where the code runs. In main, the code compiles, but the thread running your task stays blocked on the lock while the task is paused, so another task waiting for the same lock cannot make progress. In a spawned task or an Axum handler, the code does not compile at all: the guard is not Send, so the future cannot be sent between threads, and the compiler reports error E0277. Either way, the fix is the same. Drop the guard before the .await, or use tokio::sync::Mutex instead, whose guard is designed to be held across .await. This is not specific to the macro, but it is a common problem in async Axum code.

How to Think About the tokio::main Macro

A helpful mental model is to compare the macro to the ignition system of a car. The engine (Tokio runtime) does the actual work, but you need a starter motor to get the engine running and keep it idling while you drive. #[tokio::main] is that starter motor: it builds the engine, turns the key (calls block_on), and the engine runs until your async main returns or the program exits.

When you write async fn main() { ... }, you are describing what should happen once the engine is running. The macro handles the tricky part of turning the engine on and making sure it keeps running until your work is done. Without it, the engine is just a collection of parts sitting in the engine bay.

This mental model also explains why you can't use await outside of an async function: you're trying to drive the car without starting the engine.

Practical Usage in Axum Applications

In every Axum project, the runtime the macro builds starts before any of your async code runs. As your application grows, you may start to see the macro configured with different flavors or worker thread counts based on performance requirements. For example, a small utility that runs a one-off migration might use current_thread to reduce overhead, while a high-traffic API server uses the default multi-thread runtime. You can also set a fixed worker count with a literal, like #[tokio::main(flavor = "multi_thread", worker_threads = 4)] - note that the value must be a number written directly in the attribute, not a variable or expression.

The key takeaway is that #[tokio::main] is not magic. It is a convenient wrapper around a normal synchronous main that sets up an async runtime and runs your async code. Understanding this helps you troubleshoot errors, choose the right runtime flavor, and integrate your Axum server with other async libraries that also rely on Tokio.

Summary

The #[tokio::main] macro is the bridge between Rust's synchronous main requirement and the async world of Axum. It constructs a Tokio runtime, calls block_on with your async main body, and ensures that all async tasks, including the Axum server, are executed properly.

You can configure the macro to use a multi-threaded or current-thread runtime, and you can set the number of worker threads. You can also bypass the macro entirely by manually creating a runtime in a normal main function, which gives you more control when you need it.

The most common mistakes are forgetting the macro, missing Tokio features, or misunderstanding that the runtime is already running when you're inside an async function. Once you internalize that the macro is just a startup helper, you can use it with confidence in every Axum project you build.