The serve Function in Axum
Learn how axum serve starts your web server, accepts connections, and handles requests with a Router or handler, including graceful shutdown.
When you build a web server with Axum, all the route definitions and handlers you write are just data until you tell the program to start listening for incoming HTTP requests and responding to them. The function that does that final step is axum::serve.
serve is the bridge between the listener you already bound to a port and the Router (or handler) you built earlier. It takes those two pieces, starts an infinite loop that accepts TCP connections, reads HTTP requests from those connections, passes each request to your Router, and sends the response back over the socket. Once you call serve and await it, your program runs until the process is killed or a graceful shutdown completes it. Pressing Ctrl-C kills the process outright - it does not shut the server down cleanly - so a clean stop needs the graceful shutdown setup described below.
You have already used serve in the minimal main.rs, but now we will understand exactly what it does, why it is shaped the way it is, and what options you have when using it.
A Future That Never Completes Normally:
The expression axum::serve(listener, router) returns a future. That future, when awaited, never returns Ok(()) under normal circumstances. It runs until the process is killed or a shutdown signal stops it cleanly through graceful shutdown. If you forget to await it, the future is created and then dropped without ever running, so the server never starts at all.
Why serve Exists
Before Axum 0.7, you would typically run a server with axum::Server::bind(&addr).serve(app.into_make_service()). That older API was replaced by the simpler axum::serve(listener, service) function. The reason for the change is that the new function separates two concerns cleanly:
- How you bind to a network address - this is done by
tokio::net::TcpListener::bind. - How you turn a Router into a service that can handle individual requests - this is done internally by
serve.
By requiring a listener object that implements the Listener trait instead of just an address, serve can work with different kinds of listeners (TCP, Unix domain sockets, TLS-wrapped listeners, etc.) without needing its own configuration. That keeps the function small and flexible.
The function also supports HTTP/1 by default, and HTTP/2 when you enable Axum's http2 feature. For most beginners, the default features are enough.
The Simplest Possible Use
The most common way to call serve is shown in the official hello-world example. You already have a Router and a listener from previous steps. The entire program looks like this:
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
let router = Router::new().route("/", get(|| async { "Hello, World!" }));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, router).await.unwrap();
}
The last line is the critical one. axum::serve(listener, router) creates a future. The .await tells the async runtime to drive that future until it completes - which, as we said, it never does under normal operation. The .unwrap() after the await handles the Result the future resolves to: it only resolves to Ok(()) when the server is shut down gracefully, in which case unwrap passes harmlessly, or to Err if the listener fails catastrophically, in which case unwrap panics. Under normal operation the future never resolves at all, so neither case happens.
When you run this program, your terminal will block at that line. If you open a browser to http://127.0.0.1:3000, you should see Hello, World! displayed. That single line is your entire running server.
If you see the message, everything is working:
After running cargo run, your terminal will not print anything else by default. The absence of error messages, combined with the browser displaying your handler's response, means serve is working correctly. If you want a visible confirmation, add a println! before calling serve.
What Are the Parameters?
The function signature from the official docs looks intimidating, but you do not need to understand every generic bound to use it. Here is the signature with the type parameters simplified:
pub fn serve<L, M, S>(listener: L, make_service: M) -> Serve<L, M, S>
where
L: Listener,
M: for<'a> Service<IncomingStream<'a, L>, Error = Infallible, Response = S>,
S: Service<Request, Response = Response, Error = Infallible> + Clone + Send + 'static,
S::Future: Send,
In plain words:
listeneris something that can accept incoming network connections. For almost all beginners, this is atokio::net::TcpListenerthat you got fromTcpListener::bind(...).await.make_serviceis something that can turn an incoming connection into a service that handles individual HTTP requests. For almost all beginners, this is yourRouter. The Router implements the required trait, so you can pass it directly.- The return value is a
Servestruct, which is itself a future. You await that future to run the server.
The reason there is both a make_service and a S type is that some services need per-connection state. A Router is a Cloneable service, so Axum can use one copy per connection. You do not need to worry about this unless you start writing custom listeners or services.
Serving Different Kinds of Axum Services
The second parameter to serve does not have to be a full Router. Axum is flexible: you can pass a Router, a MethodRouter, or even a single handler function directly (after calling .into_make_service() on it). Each choice is appropriate in different situations.
Serving a Router
This is the standard setup for any application with multiple routes. You build a Router with all your routes and pass it to serve:
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(home))
.route("/about", get(about));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn home() -> &'static str {
"Home page"
}
async fn about() -> &'static str {
"About page"
}
Here app is a Router. The serve call takes ownership of the Router (it moves it), which is fine because we won't need it again.
Serving a MethodRouter Directly
A MethodRouter is what you get when you use get, post, put, etc., without attaching it to a path via Router::route. For example:
use axum::routing::get;
#[tokio::main]
async fn main() {
let method_router = get(|| async { "Hello from a method router" });
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, method_router).await.unwrap();
}
This works because a MethodRouter also implements the service trait. However, this approach is rare. A MethodRouter without a path does not do any path matching at all: it runs its handler for every path, as long as the HTTP method matches. A GET request to /, /foo, or any other path would all receive the same response, and a POST request would get a 405 Method Not Allowed. You would normally combine multiple method routers into a full Router with .route(...). Still, it is useful to know that it is possible, especially if you are prototyping a tiny service that only handles one method.
Serving a Single Handler Directly
If you have exactly one async function that you want to handle every request regardless of path or method, you can serve that handler directly. This requires calling .into_make_service() on the handler, which converts the handler into a service that can be passed to serve.
use axum::handler::HandlerWithoutStateExt;
#[tokio::main]
async fn main() {
let handler = || async { "Hello from a bare handler" };
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, handler.into_make_service())
.await
.unwrap();
}
The handler here is a closure that returns an async block - that is what makes it a handler. A bare async block on its own (async { "Hello" }) is a future, not a handler, so calling .into_make_service() on it does not compile. The HandlerWithoutStateExt trait must be imported for .into_make_service() to be available. This trait is implemented for any handler function that does not require application state. If your handler does use state, you will need HandlerWithStateExt instead. But for this page, the key point is that serve can accept a handler if you convert it appropriately.
The standard choice for any application with more than one route. Build the Router and pass it directly.
Which one you use depends on your needs. For a real web app, you will almost always use a Router.
What Happens When You Call serve
Understanding the internal flow helps you debug problems later. Here is a simplified step-by-step description of what the Serve future does once you start awaiting it:
- The
Servefuture starts an accept loop on the listener. Each time a new TCP connection arrives, the listener produces anIncomingStream. - For each incoming stream,
serveclones your Router (or uses the suppliedmake_serviceto create a new service instance) and starts a new task that will handle all requests on that connection. - Inside each connection task, the HTTP protocol is parsed (either HTTP/1 or HTTP/2 depending on the connection and features). Each HTTP request is passed to the Router, which matches the path and method to a handler, executes the handler, and returns a response.
- The response is serialized back onto the TCP socket, and the connection may be kept alive for subsequent requests (HTTP keep-alive) or closed, depending on the headers.
All of this happens concurrently. Multiple connections are handled in parallel, and requests on one connection are handled one at a time. The Tokio runtime manages the scheduling of these tasks across threads.
Because serve does all of this, you never need to write your own accept loop or HTTP parsing code. That is the entire point of using a web framework.
Graceful Shutdown
The Serve future returned by axum::serve does not have a built-in way to stop gracefully. If you press Ctrl-C in the terminal, the process is killed immediately, and any in-flight requests may be cut off. For development, that is often acceptable. For production, you want the server to stop accepting new connections, finish processing the requests it already has, and then exit. That is called graceful shutdown.
The Serve struct has a method with_graceful_shutdown that lets you attach a future that, when it completes, triggers the graceful shutdown process.
use axum::{routing::get, Router};
use tokio::signal;
#[tokio::main]
async fn main() {
let app = Router::new().route("/", get(|| async { "Hello" }));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app)
.with_graceful_shutdown(shutdown_signal())
.await
.unwrap();
}
async fn shutdown_signal() {
let ctrl_c = async {
signal::ctrl_c()
.await
.expect("failed to install Ctrl+C handler");
};
#[cfg(unix)]
let terminate = async {
signal::unix::signal(signal::unix::SignalKind::terminate())
.expect("failed to install signal handler")
.recv()
.await;
};
#[cfg(not(unix))]
let terminate = std::future::pending::<()>();
tokio::select! {
_ = ctrl_c => {},
_ = terminate => {},
}
}
In this example, shutdown_signal waits for either Ctrl-C or a Unix SIGTERM signal. When one of them arrives, the future resolves, and the with_graceful_shutdown method begins the shutdown sequence. The server stops accepting new connections, waits for all existing connection tasks to finish, and then the serve future completes with Ok(()).
This example uses tokio::signal, which lives behind Tokio's signal feature. If your Cargo.toml enables the full feature for tokio, you already have it. With a minimal feature list, add "signal" alongside "macros" and "rt-multi-thread", or the tokio::signal import will not compile.
This pattern is so common that Axum's official examples include it.
Without graceful shutdown, requests can be dropped:
If you run the basic axum::serve(listener, app).await.unwrap() and then kill the process with Ctrl-C, any request that is currently being processed is abruptly terminated. For a development server this is usually fine, but for production you should always include graceful shutdown to avoid losing data or causing client errors.
Common Mistakes and How to Avoid Them
Forgetting to Await the Future
The most common beginner mistake is to write:
axum::serve(listener, app);
without the .await. In Rust, a future does nothing until it is awaited. If you omit .await, the Serve future is created and then immediately dropped. The server starts up for a tiny fraction of a second and then stops. Your program may exit successfully, but no server is actually running. The compiler will often warn you about an unused future, but not always if you have other things going on.
Dropping the future stops the server:
Always write axum::serve(listener, app).await. The .await is not optional. Without it, the server future is dropped and no connections are ever accepted.
Passing the Wrong Thing as the Listener
The first argument must be a listener, not an address. Some beginners try to write:
axum::serve("127.0.0.1:3000", app).await
That will not compile because a string is not a Listener. You must first bind a TcpListener:
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
Trying to Bind a Port That Is Already in Use
If another process is already listening on the same port (for example, you forgot to stop a previous run of your server), TcpListener::bind will return an error. The .unwrap() will panic and the program will crash with an error message like Address already in use. This is not a problem with serve itself, but it happens right before serve and often confuses beginners. To fix it, close the other process or choose a different port.
Missing the Import for into_make_service
If you want to serve a bare handler and you write:
axum::serve(listener, handler.into_make_service()).await
without importing HandlerWithoutStateExt, the compiler will tell you that into_make_service is not found. You must add:
use axum::handler::HandlerWithoutStateExt;
Expecting serve to Print Something
axum::serve does not print anything. Many beginners expect to see "Server started on port 3000" in the terminal. That is not the case. If you want a message, you must add a println! before the serve call:
println!("Server listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
A Complete Step-by-Step Setup Using serve
Let's walk through creating a minimal server from scratch, step by step, to reinforce how everything fits together.
Step 1: Create a new binary project
Open a terminal and run:
cargo new my-axum-app
cd my-axum-app
Step 2: Add Axum and Tokio dependencies
Edit Cargo.toml to include:
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
Then run cargo build to download the crates.
Step 3: Write the server code
Replace the contents of src/main.rs with:
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
let app = Router::new().route("/", get(hello));
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 hello() -> &'static str {
"Hello, Axum!"
}
Step 4: Run the server
Run:
cargo run
You should see the printed message in your terminal.
Step 5: Test it
In another terminal, run:
curl http://127.0.0.1:3000
You should receive Hello, Axum!. That response is produced by your handler and sent back by serve.
After you verify that it works, you can stop the server by pressing Ctrl-C in the terminal where it is running.
What serve Does Not Do
To avoid confusion, it is worth stating clearly what serve is not responsible for:
- Routing - the Router handles matching paths and methods.
servejust forwards requests to the Router. - Handler execution - your handlers run inside the tasks spawned by
serve, butserveitself does not know what they do. - Serialization - converting Rust values into HTTP response bodies is done by the
IntoResponseimplementations, not byserve. - Middleware - layers you add to the Router are applied within the Router, not inside
serve. - Configuration -
servehas no configuration options. If you need to set timeouts, connection limits, or other HTTP server settings, you will eventually need to usehyperorhyper-utildirectly. For most Axum applications, the defaults are sufficient.
Understanding these boundaries helps you debug issues: if a route is not found, the problem is in your Router configuration, not in serve. If a response is malformed, the issue is in your handler or IntoResponse implementation. serve is only the engine that keeps everything running.
The Return Value and Error Handling
The future returned by serve has the type Serve<L, M, S>. When awaited, it resolves to std::io::Result<()>. As mentioned, under normal operation this future never completes. If the listener encounters a fatal error (such as the underlying file descriptor being closed), the future may resolve with an Err. However, according to the official documentation, errors on the TCP socket are handled internally by sleeping for a short while (currently one second) and then retrying. So even if a connection fails, serve will not return an error for that single failure. Only catastrophic errors that prevent the accept loop from continuing will cause the future to complete with Err.
Because the future never completes normally, you will often see .unwrap() after the await. This is safe because the Ok case only happens when the server is shut down gracefully, and the Err case is extremely rare in a development context. In production code, you might want to log the error instead of unwrapping.
Comparing serve to the Older Server::bind API
If you come across older Axum tutorials, you may see code like this:
// Old Axum 0.6 style (do not use in 0.8)
let server = axum::Server::bind(&addr)
.serve(app.into_make_service());
server.await.unwrap();
In Axum 0.7 and later, Server::bind was deprecated and eventually removed. The new axum::serve(listener, app) function is the replacement. The two main differences:
- You must create the listener yourself using
tokio::net::TcpListener::bindand await it. - You pass the listener directly, not an address.
This change gives you more control over how the listener is configured (e.g., setting socket options, using a custom listener) and removes the need for a separate Server type. All new code should use axum::serve.
Real-World Usage Patterns
In a real application, your main function will look similar to the examples above, but with a few additions:
- You will bind to
0.0.0.0instead of127.0.0.1when deploying to a server, so that the server is reachable from outside the machine. - You will often read the port from an environment variable (like
PORT) to allow the deployment platform to choose the port. - You will add graceful shutdown handling.
- You might add tracing or logging before and after
serve.
Here is a more realistic main function that incorporates these patterns:
use axum::{routing::get, Router};
use std::net::SocketAddr;
use tokio::signal;
#[tokio::main]
async fn main() {
// Initialize tracing if you have it
// tracing_subscriber::fmt::init();
let app = Router::new().route("/health", get(|| async { "OK" }));
let port = std::env::var("PORT")
.unwrap_or_else(|_| "3000".to_string())
.parse::<u16>()
.expect("PORT must be a number");
let addr = SocketAddr::from(([0, 0, 0, 0], port));
let listener = tokio::net::TcpListener::bind(addr)
.await
.expect("failed to bind");
println!("Listening on {}", addr);
axum::serve(listener, app)
.with_graceful_shutdown(shutdown_signal())
.await
.unwrap();
}
async fn shutdown_signal() {
let ctrl_c = async {
signal::ctrl_c()
.await
.expect("failed to install Ctrl+C handler");
};
#[cfg(unix)]
let terminate = async {
signal::unix::signal(signal::unix::SignalKind::terminate())
.expect("failed to install signal handler")
.recv()
.await;
};
#[cfg(not(unix))]
let terminate = std::future::pending::<()>();
tokio::select! {
_ = ctrl_c => {},
_ = terminate => {},
}
}
This pattern is used in production Axum applications. The health check route responds to load balancer probes, the port is configurable, and the server shuts down gracefully when the platform sends SIGTERM.
Summary
axum::serve is the final piece that turns your Axum Router into a running web server. It takes a bound listener and a service (usually a Router) and runs an accept loop that handles incoming HTTP requests for as long as the program lives. The function is intentionally simple: it has no configuration options, but it supports graceful shutdown through the returned Serve future's with_graceful_shutdown method. The most important things to remember are to always await the future, to pass a listener (not an address), and to use graceful shutdown in production. Once you understand serve, you have completed the entire flow from creating a project to serving your first Axum application.