axum serve Explained

Learn how axum serve starts your HTTP server, what it does behind the scenes, and how it compares to using Hyper directly

The axum::serve function is the simplest way to turn an Axum application into a running web server. If you have already built a Router with routes and handlers, this one function bridges the gap between "a Rust program that defines routes" and "a process listening for HTTP requests on a port." Understanding serve means understanding the final step that makes your code reachable from a browser or curl.

The Core Job of axum::serve

When you write an Axum application, you normally build a Router by chaining .route() calls. That Router is not a server. It is a description of how to respond to requests - a mapping from HTTP methods and paths to handler functions. Something still has to sit on a network socket, accept incoming TCP connections, read raw bytes, parse them as HTTP requests, pass each request to your Router, and send back the response bytes. That "something" is what axum::serve sets up for you.

serve takes two things: a listener that knows how to accept network connections, and a service that knows how to answer one HTTP request. It returns a future. When you .await that future, the server runs forever (or until the process is stopped). While it runs, it accepts connections, handles requests concurrently, and keeps your application alive.

The Smallest Possible Server

The canonical Axum "Hello, World!" example uses serve to start listening:

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("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

Place this code in src/main.rs after adding axum and tokio to your Cargo.toml with appropriate features (the official docs note you need Tokio's macros and rt-multi-thread features, or simply full). Run cargo run, then open a browser to http://localhost:3000 or run curl http://localhost:3000. You will see Hello, World! printed. That is all it takes to have a running HTTP server.

There are three important pieces in that example:

  1. Router::new().route(...) builds the application logic. It knows that GET / should return the string "Hello, World!".
  2. tokio::net::TcpListener::bind("0.0.0.0:3000").await asks the operating system to listen for TCP connections on port 3000. The "0.0.0.0" address means "listen on all network interfaces, not just localhost."
  3. axum::serve(listener, app).await connects the listener and the application, then runs the server until the program is terminated.

That third line is where all the magic of serve happens. The next sections break down exactly what it does, what you can pass to it, and what happens when things go wrong.

The Signature Without the Jargon

Looking at the function signature from the official documentation might feel intimidating at first:

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,

You do not need to understand every part of that to use serve. But breaking it down conceptually helps you see what the function requires and why some things work while others do not.

  • listener is any type that implements the Listener trait. In everyday use, that is tokio::net::TcpListener. The Listener trait is Axum's abstraction over "something that can accept incoming connections and produce streams that speak HTTP." There is also a Listener implementation for Unix domain socket listeners (tokio::net::UnixListener), for services that only need to talk to other processes on the same machine.
  • make_service is a service factory. It is not the service that answers one request; it is a function (or a type that acts like one) that produces a fresh instance of the request handler for each new connection. In the starter example, we passed app directly. That works because Router implements the necessary trait to act as a make-service: it can clone itself to give each connection its own copy of the router. Internally, Axum clones the Router for every incoming TCP connection and then uses that clone to handle all requests on that connection.
  • S, the response type of make_service, is the actual service that handles a single Request and returns a Response. For a Router, that service is the router itself. It must be Clone + Send + 'static so Axum can safely share it across many connections and tasks. Its error type must be Infallible (meaning it never fails) because Axum's request handling layer already converts all application errors into proper HTTP responses before they reach this level.

The key takeaway is that serve is designed to work with Router, MethodRouter, and even a single handler function (with a small conversion). It is intentionally simple: you give it a listener and something that can answer requests, and it takes care of the rest.

What serve Actually Returns

Calling axum::serve(listener, app) does not start the server immediately. It returns a value of type Serve<L, M, S>, which is a future. A future is a value that represents work to be done later - in this case, running the server loop. Only when you .await that future does the server start accepting connections and handling requests.

In the starter example, we used axum::serve(...).await.unwrap(). The unwrap() is needed because the Serve future resolves to std::io::Result<()>. However, the official documentation makes an important point: although the future resolves to io::Result<()>, it will never actually complete or return an error under normal operation. Once you await it, it runs forever. It only stops if the process is killed (Ctrl+C, kill command, etc.) or if something catastrophic happens to the listener itself - and even then, the function handles many errors internally by sleeping for a second and trying again.

Because it never returns, you will usually see .await as the last line of main or inside a tokio::spawn call if you want to run other tasks alongside the server. For example, you might want to run a background job while the server runs:

use axum::{routing::get, Router};
use tokio::task;
#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(|| async { "Hello, World!" }));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    // Spawn a background task that prints a message every 5 seconds
    task::spawn(async {
        loop {
            println!("Background task is alive");
            tokio::time::sleep(std::time::Duration::from_secs(5)).await;
        }
    });
    // This runs forever, so the background task keeps running too
    axum::serve(listener, app).await.unwrap();
}

Here, the background task and the server run concurrently. The server future never completes, so the program stays alive and both tasks keep executing.

The await never returns:

Do not write code that expects axum::serve(...).await to return. It is not a function that completes after a few requests. It is the event loop of your server. Think of it as the "on" switch that stays on until you pull the plug.

Handling Low-Level Socket Errors

One of the nice things about axum::serve is that it shields you from the messy details of TCP socket errors. In a real network, connections can be reset, clients can disappear abruptly, and the operating system may occasionally refuse to accept a new connection temporarily (for example, when the accept queue is full). If you were writing the server loop yourself with Hyper, you would have to decide what to do in each of those cases.

axum::serve chooses a simple, sensible policy: when an error occurs while accepting a new TCP connection, it logs the error (if a tracing subscriber is set up) and then sleeps for one second before trying again. That prevents a tight error loop from burning CPU while still allowing the server to recover when the transient problem goes away. Errors that happen during request handling on an already-accepted connection are a different matter - those are handled by the service itself and converted into HTTP responses, not by the accept loop.

This behavior is why the future's return type is io::Result<()>: it could return an error if the listener itself fails in a way that cannot be recovered. But in practice, most socket errors are handled internally, and the future never completes.

Socket errors are not application errors:

Do not confuse errors from the TCP accept loop with errors your handlers might produce. If a handler returns an error, Axum converts it into whatever HTTP response that error type's IntoResponse implementation defines - often a 4xx or 5xx, not necessarily a 500. A panic in a handler does not become a 500 by default either - that needs tower_http::catch_panic::CatchPanicLayer. The serve function only deals with the lower-level problem of "can we accept a new connection right now?" - and it handles that by retrying.

Serving More Than Just a Router

The most common thing to pass to serve is a Router. That is the type you build with .route(), .nest(), .merge(), and other methods. But serve is more flexible than that. You can also pass a MethodRouter, which is a router for a single HTTP method without a path, or even a bare handler function with a small conversion.

Serving a MethodRouter

A MethodRouter is what you get from axum::routing::get(handler). It is a service that answers one request. You can serve it directly:

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("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, method_router).await.unwrap();
}

Now every request that arrives on port 3000, regardless of path or HTTP method, will be handled by that single handler. A MethodRouter responds only to its configured method (here, GET), so a POST request would get a 405 Method Not Allowed.

Serving a Single Handler Function

Sometimes you want to serve one function directly without building a Router. A handler function is not a service by itself; it needs to know how to extract request parts and produce a response. Axum provides a helper called into_make_service on the HandlerWithoutStateExt trait to wrap a handler into something serve can accept:

use axum::handler::HandlerWithoutStateExt;
async fn handler() -> &'static str {
    "Hello from a bare handler!"
}
#[tokio::main]
async fn main() {
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, handler.into_make_service()).await.unwrap();
}

This is rarely necessary in real applications because you almost always want routing. But it demonstrates that serve is not tied exclusively to Router. Any type that can act as a make-service (producing a service that answers requests) will work.

Serving with Connect Info

The serve function also has a sibling: Router::into_make_service_with_connect_info. That method lets you access information about the connection itself (like the peer's IP address) inside your handlers. It is an advanced feature, but it shows that serve is the basic building block, and Axum provides ways to layer on more information if needed.

Router is the standard choice:

For the vast majority of Axum applications, you will pass a Router to serve. The other options (MethodRouter, bare handler) exist for completeness and special cases, but Router is what you will use day to day.

Listening on Unix Domain Sockets

tokio::net::TcpListener is the most common listener, but axum::serve accepts any type that implements the Listener trait. Axum provides a Listener implementation for tokio::net::UnixListener, which allows you to serve HTTP over a Unix domain socket instead of a TCP port. This is sometimes used for local inter-process communication where network overhead is undesirable.

Here is a minimal example that serves over a Unix socket:

use axum::{routing::get, Router};
use tokio::net::UnixListener;
#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(|| async { "Hello over Unix socket!" }));
    let listener = UnixListener::bind("/tmp/my_server.sock").unwrap();
    axum::serve(listener, app).await.unwrap();
}

Clean up old socket files:

If the socket file /tmp/my_server.sock already exists, UnixListener::bind will fail. You need to remove it before binding (or use a unique path). Unlike TCP ports, Unix socket files are not automatically cleaned up when the process exits.

This flexibility is part of Axum's design: it does not hard-code TCP, but instead works with any listener that can produce streams of bytes. Hyper also has this flexibility, but Axum's serve function makes it particularly easy to use.

What serve Does Not Support

The official documentation states clearly: "This method of running a service is intentionally simple and doesn't support any configuration. Use hyper or hyper-util if you need configuration." That is a crucial sentence for understanding when to reach beyond axum::serve.

Configuration here means things like:

  • Setting a custom timeout for how long an idle connection stays open
  • Tuning the HTTP/2 window size or other protocol-level parameters
  • Customizing how connections are accepted (e.g., applying a handshake timeout)
  • Choosing a different connection task scheduler
  • Fine-grained HTTP connection knobs (idle timeouts, HTTP/2 window sizes, custom accept behavior)

axum::serve gives you a reasonable default setup: it enables HTTP/1, and HTTP/2 when the http2 feature is enabled on the axum dependency, uses sensible connection limits, and handles errors gracefully. Graceful shutdown is available on the returned Serve value via .with_graceful_shutdown(...). If your application needs deeper Hyper-level configuration beyond those defaults, you would instead use Hyper's server builder (or hyper-util's builder) and integrate your Axum Router as the service. That path requires more boilerplate but unlocks all the knobs Hyper provides.

In the context of "Axum vs Hyper," this is the clearest practical difference: Axum's serve is the easy, zero-configuration path; Hyper gives you the full control but makes you assemble more pieces yourself.

A Closer Look at the "Never Returns" Guarantee

Because axum::serve(listener, app).await runs until the process stops, you need a deliberate shutdown path in production: stop accepting new connections, finish in-flight requests, then exit. Axum supports that directly with Serve::with_graceful_shutdown. You pass any future that completes when shutdown should begin (Ctrl+C, a SIGTERM handler, or a channel message). When that signal future completes, the server stops accepting new connections and waits for active connections to finish before the serve future returns.

For example, to shut down when the user presses Ctrl+C:

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("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app)
        .with_graceful_shutdown(async {
            tokio::signal::ctrl_c().await.expect("failed to install Ctrl+C handler");
            println!("Shutdown signal received");
        })
        .await
        .unwrap();
}

Avoid racing serve against Ctrl+C with a bare tokio::select! and then dropping the server future. That stops accepting new connections but can cut off in-flight requests abruptly. Prefer .with_graceful_shutdown(...) so Axum can drain connections cleanly. You can still drop down to Hyper if you need connection-level knobs that serve does not expose.

Using unwrap on serve may mask shutdown errors:

The starter example uses unwrap() on the Serve future. That is fine for learning because the future almost never returns. But in production code, avoid unwrap() in general. If the future does return an error (for example, if the listener is closed unexpectedly), you want to log that error and exit cleanly, not panic. Replace unwrap() with proper error handling or a graceful shutdown path.

Common Beginner Mistakes with axum::serve

Several misunderstandings crop up repeatedly when people first use axum::serve. Being aware of them saves debugging time.

Mistake 1: Forgetting That serve Must Be Awaited

Because serve returns a future, it does nothing until you .await it. If you write this:

let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app); // no .await!

The program will compile, but the server never starts. The future is dropped immediately, and main may exit before any request arrives. The fix is always to .await it (or spawn it with tokio::spawn and await the join handle).

Unused future warning:

If you forget .await, the compiler might warn you about an unused Serve value that must be used. Pay attention to that warning - it is telling you the server is not running.

Mistake 2: Trying to Run Multiple Servers in the Same Main

You cannot simply call axum::serve twice and await both sequentially because the first one never returns. If you need to run multiple servers (e.g., one on HTTP and one on HTTPS, or two different applications on different ports), you must spawn each serve future as a separate task:

let listener1 = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
let listener2 = tokio::net::TcpListener::bind("0.0.0.0:3001").await.unwrap();
let server1 = axum::serve(listener1, app1);
let server2 = axum::serve(listener2, app2);
let (result1, result2) = tokio::join!(server1, server2);
result1.unwrap();
result2.unwrap();

Now both servers run concurrently, and main waits for both of them. If either server returns an error, you get both results back and can report them. Do not use bare tokio::spawn(server1); tokio::spawn(server2); followed by a sleep loop instead: dropping a JoinHandle silently discards any error the task produced, and nothing logs it - a failed server would look like it was still running.

Mistake 3: Assuming serve Handles TLS

axum::serve does not handle TLS (HTTPS) by itself. It accepts plain TCP connections and speaks HTTP. To serve HTTPS, you need to wrap the connection in a TLS layer before it reaches Axum. This is typically done with a crate like tokio-rustls and a custom listener or with Hyper's server builder. Axum's serve intentionally stays simple and leaves TLS to other layers.

HTTPS is a separate concern:

Many production Axum applications put a reverse proxy like nginx or Caddy in front of Axum. The proxy handles TLS termination and forwards plain HTTP to Axum on localhost. That way, axum::serve can remain simple and fast.

Mistake 4: Confusing serve with Router::into_make_service

You might see code examples that call Router::into_make_service() and then pass the result to Hyper directly. That is an alternative path for when you need Hyper's configuration options. But if you use axum::serve, you do not call into_make_service - you pass the Router directly. The function internally converts it to the right type.

Comparing axum::serve with Hyper's Server

Since this page sits in the "Axum vs Hyper" cluster, it is worth summarizing the relationship explicitly. Axum is built on top of Hyper. Under the hood, axum::serve creates a Hyper server (specifically, it uses hyper-util's auto::Builder, which picks HTTP/1 or HTTP/2 per connection) and configures it with defaults. It then feeds each accepted connection to a service that wraps your Router.

The main differences from using Hyper directly:

  • Convenience: axum::serve gives you a running server in one line. With Hyper, you need to set up the accept loop, choose connection builders, handle connection tasks, and wire up the service.
  • Configuration: Hyper exposes many knobs (timeouts, buffer sizes, HTTP/2 settings). Axum's serve hides all of that behind sensible defaults.
  • Error handling: Axum's serve implements a retry-on-error policy for accept errors and logs them. With Hyper, you write that logic yourself.
  • Shutdown: Axum's Serve exposes .with_graceful_shutdown(signal) so you can stop accepting and drain connections when a signal future completes. Hyper still offers lower-level connection helpers if you assemble the server yourself.
  • TLS: Neither handles TLS natively, but Hyper's builder is easier to integrate with custom TLS acceptors because you control the connection handoff.

For most Axum applications, axum::serve is the right choice because you do not need the extra configuration. When you do, you can still use Axum's Router as a service inside Hyper - the two libraries are designed to work together.

You are already using Hyper:

Every time you call axum::serve, you are indirectly using Hyper. Axum is not replacing Hyper; it is a layer on top that makes the common case dramatically simpler.

A Practical Example with Tracing

Because serve handles socket errors by sleeping and retrying, it is helpful to set up a logging system so you can see what is happening. Axum integrates with the tracing ecosystem. Add tracing and tracing-subscriber to your dependencies, then initialize a subscriber at the start of main:

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
tracing = "0.1"
tracing-subscriber = "0.3"
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
    tracing_subscriber::fmt::init();
    let app = Router::new().route("/", get(|| async { "Hello, World!" }));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

Now, if the accept loop hits an error, you will see a log line describing it instead of silence. This is invaluable in production when a transient network issue occurs and you need to know the server is still alive and retrying.

The Role of serve in the Bigger Picture

axum::serve is the last piece of the puzzle for building a web service with Axum. You define routes, extract data from requests, produce responses, and then serve connects all of that to the actual network. It embodies Axum's philosophy: provide simple, ergonomic defaults, but never hide the underlying stack. Because it sits on top of Hyper and Tokio, you can always drop down to those layers when the defaults are not enough.

For an absolute beginner, the most important thing to remember is this: after you have built your Router, the line axum::serve(listener, app).await.unwrap(); is what makes your application reachable from the outside world. It is the final command that turns your code into a server.

Summary

axum::serve is a convenience function that starts an HTTP server using a provided listener and service (usually a Router). It returns a future that never completes under normal operation, handling TCP accept errors by sleeping and retrying. The function supports HTTP/1, and HTTP/2 when the http2 feature is enabled, works with TCP and Unix domain socket listeners, and is designed to be simple with no configuration options.

When you need fine-grained Hyper-level control (custom connection timeouts, TLS acceptors, specialized executors, and so on), you can use Hyper directly and pass your Axum Router as a service. For graceful shutdown in the common case, stay on axum::serve and call .with_graceful_shutdown(...). For the vast majority of applications, axum::serve is the right starting point - it gets you from zero to a running server in a single line, with an optional graceful exit path when you need one.