Thin main.rs
Learn why and how to keep your Axum main.rs entry point small and focused on server startup only.
When you first create an Axum application, all your code usually lives in one file: src/main.rs. This file starts the server, defines routes, writes handlers, sets up state, and handles errors - everything in one place. That works for tiny examples, but as your app grows, that file becomes long and hard to manage.
The idea of a "thin main.rs" is to shrink that file down to only what it absolutely must do: start the async runtime, initialize any logging or configuration, create the application (or receive it from elsewhere), bind to a network address, and serve requests. Everything else moves out into separate modules or a library crate.
This page covers why you want a thin main.rs and what exactly belongs in it. It does not show how to build the replacement modules. Here we focus on the entry point itself and the discipline of keeping it small.
The Monolithic Starting Point
Before you can appreciate a thin main.rs, it helps to see the opposite. A simple Axum app from an earlier chapter might look like this in its entirety:
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
// Build the application with one route
let app = Router::new()
.route("/", get(|| async { "Hello, world!" }));
// Bind to all network interfaces on port 3000
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
// Start serving
axum::serve(listener, app).await.unwrap();
}
This file is short, but it already mixes two distinct responsibilities: building the application (the Router and its routes) and running the server (binding and serving). For a single route, that mixing is harmless. However, as you add more routes, extractors, state, middleware, and error types, the main function balloons.
Imagine a real API with users, posts, authentication, and database connections. You would quickly end up with hundreds of lines inside main, making it hard to read, test, or reuse.
The Thin main.rs - Minimal Version
The thinnest possible main.rs does only these things:
- Marks the function as the async entry point with
#[tokio::main]. - (Optionally) initializes logging or tracing.
- Gets an application
Routerfrom somewhere else - for now, we will use a placeholder function. - Binds a network listener.
- Serves the app and awaits completion.
Here is what that looks like:
use axum::Router;
#[tokio::main]
async fn main() {
// Initialize logging
tracing_subscriber::fmt::init();
// Get the application from the app function below
let app = app();
// Bind to all network interfaces on port 3000
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
// Start the server
axum::serve(listener, app).await.unwrap();
}
// This is a placeholder. In a later step, it will live in a separate module
// and return a fully configured Router.
fn app() -> Router {
use axum::routing::get;
Router::new().route("/", get(|| async { "Hello from thin main!" }))
}
The main function is now only about server lifecycle. The route definition still exists in the same file, but it is tucked inside the app() function, not inside main. That single change already makes the purpose of main much clearer.
You're on the right track:
If your main function only calls bind, serve, and maybe a logging initializer, you have successfully thinned it. The actual route building should live somewhere else - even if that "somewhere else" is still in the same file for now.
What Belongs in a Thin main.rs
A thin entry point is not empty; it contains the essential startup steps. Here is a breakdown of what normally stays:
1. Async runtime annotation
Rust itself does not know what async means unless a runtime drives it. The #[tokio::main] attribute transforms your async fn main into a regular fn main that starts a Tokio runtime and runs your async code inside it. This line is mandatory for any Axum app.
#[tokio::main]
async fn main() {
// ...
}
You cannot remove the attribute or make main synchronous and still use await inside.
2. Logging / tracing initialization
Most real applications want to see what the server is doing. The tracing_subscriber::fmt::init() call sets up a default logger that prints events to standard output. This is usually done at the very top of main.
tracing_subscriber::fmt::init();
This call needs the tracing-subscriber crate in your project. Add it to Cargo.toml before you use it:
[dependencies]
tracing-subscriber = "0.3"
Without that line, the compiler reports that it cannot find the tracing_subscriber crate. Keep this in main because logging should be configured before any part of the app starts.
3. Obtaining the application
The application is the Router that Axum will serve. In a thin main, you call a function to get that Router, rather than building it inline.
let app = app();
The app function may live in the same file (as a placeholder), in another module, or - most commonly - in a separate library crate. That separation is the core of the split entry point pattern.
4. Binding a network listener
The listener waits for incoming TCP connections. You create it with TcpListener::bind, passing an address string like "0.0.0.0:3000" or a SocketAddr value.
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
The bind call returns a future (because it may need to do I/O), so you must await it.
5. Serving the app
Finally, you hand the listener and the app to axum::serve, which runs forever until the process is stopped.
axum::serve(listener, app).await.unwrap();
That is the complete lifecycle: start runtime, set up logging, get app, bind, serve. Nothing else belongs in main.
What Should Move Out of main.rs
If you see any of the following inside main, that is a sign it is not thin enough:
- Route definitions like
.route("/users", get(list_users))- these belong in a function that returns aRouter. - Handler functions - the async functions that process requests should live in a
handlersmodule, not inmain. - Application state creation - building a database pool, loading configuration, or setting up shared data should happen in a dedicated function or module.
- Error handling logic - mapping errors to HTTP responses should be defined outside
main. - Middleware setup - adding layers like
TraceLayerorCorsLayerbelongs in the app-building function, not in the server startup code.
The reason is simple: main should be the last thing to run, not the place where the whole program is assembled. Keeping all construction logic out of main makes it possible to test the application without starting a real server and to reuse the same app() function in different contexts (e.g., unit tests).
Don't confuse 'thin' with 'empty':
A thin main.rs is not an empty main.rs. It still does essential startup work. The goal is to make that work the only thing it does, not to remove everything.
Variations of a Thin main.rs
There is more than one valid way to write a thin main. The differences are mostly about error handling and how you bind the address. Below are three common patterns.
The simplest approach calls .unwrap() on the fallible operations. If something fails, the program panics and exits immediately. That is acceptable for small tools and examples, but not ideal for production.
use axum::Router;
#[tokio::main]
async fn main() {
tracing_subscriber::fmt::init();
let app = app();
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
fn app() -> Router {
use axum::routing::get;
Router::new().route("/", get(|| async { "Hello" }))
}
All three versions have the same shape: initialize, get app, bind, serve. The only difference is how they handle potential failures at bind and serve time.
Choose based on your project's size:
For a quick script, .unwrap() is fine. For anything that will be deployed, prefer anyhow::Result and SocketAddr for clearer errors and safer address handling.
Step-by-Step Thought Process for Thinning main.rs
You do not need to rewrite everything at once. Here is a sequence of mental steps you can follow when looking at a monolithic main and deciding how to slim it down.
Step 1: Identify what main currently does
Open your src/main.rs and list every responsibility you see. Typical items: building a router, defining handlers, creating state, binding a listener, serving. Circle the ones that are server startup and the ones that are application construction.
Step 2: Move application construction out of main
Create a separate function (even just below main in the same file for now) that builds and returns the Router. Move all route definitions, state, and middleware into that function. Leave main with only a call to it.
fn app() -> Router {
// all routes go here
Router::new()
.route("/", get(|| async { "Hello" }))
}
Step 3: Keep only startup logic in main
Now main should contain only: #[tokio::main], tracing_subscriber::fmt::init(), let app = app();, TcpListener::bind, and axum::serve. If you see anything else, move it to the app() function or a helper.
Step 4: Verify the app still runs
Run cargo run and test your routes with curl or a browser. The behavior must be unchanged. A thin main should not alter what the server does, only where the code lives.
This process is iterative. The same mental model applies when the app() function moves out of main.rs entirely and into a library crate: main starts the server, everything else builds the server.
Common Mistakes and How to Avoid Them
Beginners often fall into a few traps when first trying to write a thin main.rs.
Mistake 1: Forgetting #[tokio::main]
If you write async fn main() without the attribute, the compiler will complain that main is not allowed to be async. Always include #[tokio::main] above the function.
// WRONG
async fn main() {
// ...
}
// CORRECT
#[tokio::main]
async fn main() {
// ...
}
Compiler error you will see:
Without #[tokio::main], Rust reports: main function is not allowed to be async. This is because standard Rust has no async runtime. The attribute provides one.
Mistake 2: Still building routes directly in main
Even after moving some code out, you might leave one or two routes inside main "because they are small." That defeats the purpose. All routes belong in the app-building function.
// WRONG: route in main
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(|| async { "Hello" })); // still here
// ...
}
// CORRECT: route moved to app()
fn app() -> Router {
Router::new()
.route("/", get(|| async { "Hello" }))
}
Mistake 3: Overcomplicating error handling in main
The entry point should not contain custom error mapping logic. That belongs in the app or a dedicated error module. In main, using .unwrap() or ? with anyhow::Result is usually enough. If you need graceful error reporting, use a simple match or let the runtime handle it, but avoid converting errors to HTTP responses here.
Mistake 4: Reading too much configuration in main
Loading environment variables, parsing config files, and building complex state should happen in a separate function (often called config::load() or state::init()). main just calls that function and passes the result to app().
#[tokio::main]
async fn main() {
tracing_subscriber::fmt::init();
let config = config::load(); // not defined here
let state = state::init(&config); // not defined here
let app = app(state); // pass state to app builder
let listener = tokio::net::TcpListener::bind(&config.addr).await.unwrap();
axum::serve(listener, app).await.unwrap();
}
This is a sketch, not a complete file: config and state are placeholder modules that do not exist yet, and app here takes the state as an argument, unlike the no-argument app() used earlier in this page. Both shapes are valid. The point of the sketch is only to show where configuration loading belongs. When you write the real version, the modules that provide config and state must exist, and the app function must accept whatever main passes to it.
Keep config and state out of main:
It is tempting to read a port number from an environment variable directly in main, but doing so scatters configuration logic across files. Let a dedicated module own it and hand the result to main.
When Is Your main.rs Thin Enough?
You can use a simple checklist to decide if your main.rs is thin enough:
- Can you explain the entire
mainfunction in one sentence? Example: "It starts logging, gets the app, binds to port 3000, and serves." If you need more than one sentence, it might still be too fat. - Is the
mainfunction shorter than about 30 lines, excluding comments and blank lines? - Are there no route definitions, no handler functions, no state structs, and no error enums inside
main.rs? They should all live elsewhere. - Can you imagine calling the app-building function from a test without starting a real server? If not, that function is too tightly coupled to the server startup code.
If you answer "yes" to all four, congratulations - you have achieved a thin entry point.
A sign of good design:
A thin main.rs is often the first sign of a well-structured Axum project. It shows that the developer separated concerns: one part builds the application, another part runs it.
Summary
The journey from a monolithic Axum file to a modular project starts with one simple idea: make main.rs as small as possible. The entry point should only start the async runtime, initialize logging or configuration, obtain a fully constructed Router from a function, bind a network listener, and serve requests. Everything else - routes, handlers, state, middleware, error handling - belongs in separate modules or a library crate.
This page showed you what a thin main looks like and several valid variations. It also walked through the mental steps to refactor a monolithic main into a thin one without changing behavior. The next step is to move the app-building function out of main.rs entirely and into a dedicated lib.rs, which makes the application reusable and testable.