Axum Built on Hyper
Understand how Axum uses Hyper as its underlying HTTP engine, what each layer does, and why this design gives you a fast, reliable, and ergonomic web framework.
When you start a web server with Axum, you are not writing raw networking code. You are building on top of a carefully layered stack that handles the messy parts of HTTP for you. The bottom of that stack is a library called Hyper, and Axum sits directly on top of it. This page explains what that means, why Axum was designed this way, and how the two pieces fit together.
What Hyper Does
Hyper is a low-level HTTP implementation for Rust. It knows how to speak the HTTP protocol over a network socket. It can read an incoming HTTP request - like GET /users HTTP/1.1 with headers and a body - and turn those bytes into structured Rust types. It can also take a structured HTTP response and write it back to the client. Hyper handles connection management, keep-alive, HTTP/1.1 and HTTP/2, and the correct parsing of all the little details of the HTTP specification.
What Hyper does not do is tell you how to organize your application. It does not have a router to decide which function should handle which path. It does not have extractors that automatically parse JSON bodies or path parameters. It does not have a middleware system for logging, compression, or authentication. Those things are your job to build if you use Hyper directly.
Imagine Hyper as the engine and steering system of a car. It makes the car move and turn, but it does not give you a dashboard, a comfortable seat, or a navigation system. You can drive the car, but it is hard work and you must pay attention to every mechanical detail.
Axum adds the rest of the car.
What Axum Adds on Top
Axum is an HTTP routing and request-handling library. It provides a clean API for defining routes, extracting data from requests, returning responses, and applying middleware. Axum does not implement the HTTP protocol itself. Instead, Axum takes the structured request that Hyper has already parsed, and then passes it through your application logic. When your handler returns a response, Axum gives that response back to Hyper, which writes the raw bytes to the network.
This division of labor is the key to understanding Axum:
- Hyper handles the protocol and the network I/O.
- Axum handles your application logic, routing, and ergonomics.
Because Hyper already does the hard low-level work correctly, Axum can stay small and focused. Axum is often described as a thin layer over Hyper. It adds convenience without duplicating the low-level implementation.
The Full Stack: Tokio, Hyper, Tower, Axum
To see the whole picture, let's look at the layers from bottom to top:
- Tokio - the async runtime. It schedules tasks and provides the
TcpListenerthat accepts connections. - Hyper - the HTTP engine. It reads and writes HTTP messages over those connections.
- Tower - a service abstraction. It defines a common interface (
Service) for request-response components. Hyper and Axum both use Tower'sServicetrait, which allows middleware to be shared. - Axum - the routing and handling layer. It turns a
Routerinto a TowerService, so Hyper can call it.
The flow for each incoming request looks like this:
- Accept the connection. Tokio's
TcpListeneraccepts a new TCP connection from the network. - Parse the HTTP request. Hyper reads the raw bytes from the connection and parses them into a structured HTTP request (method, path, headers, body).
- Call the Axum service. Hyper passes that structured request to the Axum
Router, which implements Tower'sServicetrait. - Run your handler. Axum matches the request path to a route, runs the handler with any extractors, and produces a response value.
- Convert to HTTP response. Axum converts the handler's return value into an HTTP response struct.
- Write the response. Hyper takes that response and writes the raw bytes back over the connection.
This sequence is hidden from you when you use Axum. You only write the handler step; everything else is automatic.
A Minimal Hyper Server (To See the Low Level)
To appreciate what Axum does for you, it helps to see a tiny server written with just Hyper. The code below uses Hyper directly to respond with "Hello, World!" to every request.
First, add these dependencies to your Cargo.toml:
[dependencies]
hyper = { version = "1", features = ["full"] }
tokio = { version = "1", features = ["full"] }
http-body-util = "0.1"
hyper-util = { version = "0.1", features = ["full"] }
Now the server code:
use std::convert::Infallible;
use http_body_util::Full;
use hyper::body::{Bytes, Incoming};
use hyper::service::service_fn;
use hyper::{Request, Response};
use hyper_util::rt::TokioIo;
use tokio::net::TcpListener;
// A hyper 1.x service returns Response<B> where B implements http_body::Body.
// `String` does not - the canonical simple body is Full<Bytes>.
async fn handle_request(
_req: Request<Incoming>,
) -> Result<Response<Full<Bytes>>, Infallible> {
Ok(Response::new(Full::new(Bytes::from("Hello, World!"))))
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let listener = TcpListener::bind("127.0.0.1:3000").await?;
println!("Listening on http://127.0.0.1:3000");
loop {
let (stream, _) = listener.accept().await?;
let io = TokioIo::new(stream);
tokio::task::spawn(async move {
let service = service_fn(handle_request);
if let Err(err) = hyper::server::conn::http1::Builder::new()
.serve_connection(io, service)
.await
{
eprintln!("Error serving connection: {:?}", err);
}
});
}
}
This is a lot of ceremony for just "Hello, World!". You must manually accept connections, wrap the stream for Hyper, create a service function, and spawn a task for each connection. There is no routing, no extractors, and no middleware. If you wanted to handle different paths, you would have to inspect req.uri().path() yourself and write match statements. If you wanted to parse a JSON body, you would have to read the body and deserialize it manually.
Hyper gives you the raw building blocks, but it is not ergonomic for building an application.
The Same Server with Axum
Now compare the Axum version. Add these dependencies:
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
And the code:
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!("Listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
That is the entire server. Axum hides all of Hyper's connection handling, service creation, and task spawning behind axum::serve. Under the hood, axum::serve does exactly what the Hyper example does - it accepts connections, creates Hyper services, and serves connections. But you never have to see that code.
Notice that you do not import hyper directly. Axum brings it in as a dependency, but you interact only with Axum's high-level API. The listener is still a Tokio TcpListener, which shows that Axum is designed to run on Tokio.
Everything is working:
If you run this code and open http://127.0.0.1:3000 in a browser, you should see "Hello, World!" displayed. The fact that you did not write any Hyper code is the whole point: Axum is using Hyper for you.
How axum::serve Uses Hyper Internally
The function axum::serve(listener, app) is the bridge between Axum and Hyper. Its implementation does the following:
- Takes a listener - usually a
tokio::net::TcpListener, or any type implementingaxum::serve::Listener. - Builds a Hyper server using that listener.
- Wraps your Axum
Routerso that Hyper can call it as a service. - Starts serving connections, spawning a new task for each one.
This is why axum::serve requires the tokio runtime to be running. The #[tokio::main] attribute on main starts that runtime.
axum::serve is intentionally simple and does not support configuration - the Serve future it returns has no http2_enable or timeout methods (those do not exist). If you need that kind of control, you use Hyper or hyper-util directly. The options Serve does offer are small and explicit:
use axum::{routing::get, Router};
use std::time::Duration;
use tower_http::timeout::TimeoutLayer;
#[tokio::main]
async fn main() {
// HTTP/2 comes from the `http2` feature flag, not a method call:
// axum = { version = "0.8", features = ["http2"] }
// Timeouts come from a layer, not from Serve:
let app = Router::new()
.route("/", get(|| async { "Hello" }))
.layer(TimeoutLayer::with_status_code(
axum::http::StatusCode::REQUEST_TIMEOUT,
Duration::from_secs(30),
));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
// Graceful shutdown is the one serving option Serve does have:
axum::serve(listener, app)
.with_graceful_shutdown(shutdown_signal())
.await
.unwrap();
}
async fn shutdown_signal() {
tokio::signal::ctrl_c().await.unwrap();
}
So: HTTP/2 is enabled with the http2 Cargo feature, timeouts are a Tower layer, and graceful shutdown is Serve::with_graceful_shutdown. If you need anything beyond that - custom HTTP/2 settings, connection-level tuning - use Hyper or hyper-util directly instead of axum::serve.
Two body types: Hyper's Incoming and Axum's Body
One detail of the handoff is worth knowing, because it explains why handler code never mentions Hyper's body type. When Hyper parses a request, the body it produces is hyper::body::Incoming - a streaming body that reads bytes off the connection as they arrive. But Axum handlers and extractors work with a different type, axum::body::Body, which is Axum's own body type. Before the request reaches your Router, axum::serve converts the one into the other: it takes the Request<Incoming> Hyper built and maps its body into Body::new(...).
That conversion is also why the minimal Hyper server above uses Full<Bytes> as its response body while Axum handlers just return a String or a Json<T>. In raw Hyper, the response body must be a type that implements the http_body::Body trait, and Full<Bytes> is the simple choice for a complete body. In Axum, the handler's return value is converted into an Axum Body for you, so you never pick a body type yourself. If you ever write custom middleware that touches the request body, you will meet axum::body::Body - and now you know where it comes from.
The Role of Tower in the Relationship
A crucial part of why Axum is built on Hyper is the Tower service abstraction. Tower defines a trait called Service that represents an asynchronous function from a request to a response. Both Hyper and Axum speak this trait.
- Hyper's server expects a
Serviceto handle each connection. - Axum's
RouterimplementsServicefor HTTP requests.
Because both sides use Tower's Service, Axum can plug directly into Hyper without any adapter glue. It also means that middleware written for Tower works with both Hyper and Axum. For example, you can use tower_http::trace::TraceLayer to add logging to an Axum app:
use axum::{routing::get, Router};
use tower_http::trace::TraceLayer;
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(|| async { "Hello, World!" }))
.layer(TraceLayer::new_for_http());
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
That TraceLayer is not part of Axum; it is from the Tower ecosystem. Because Axum uses Tower's service model, the middleware fits perfectly. The same TraceLayer could be used with a raw Hyper server, or with a Tonic gRPC server. This is a major benefit of the architecture.
What This Design Means for You
The fact that Axum is a thin layer over Hyper has practical consequences:
- Performance - Axum adds very little overhead on top of Hyper. Its performance is comparable to Hyper itself, which is known to be fast.
- Stability - Hyper is maintained by the same Tokio team and is used in production across the Rust ecosystem. Axum inherits that battle-tested reliability.
- Ecosystem - Because Axum uses Tower and Hyper, you can reuse middleware and utilities from the broader Rust async ecosystem instead of learning a custom system.
- Safety - Axum uses
#![forbid(unsafe_code)], meaning the entire crate is written in safe Rust. This is possible partly because Hyper and Tokio already handle the unsafe low-level details.
You almost never need to use Hyper directly when building an Axum application. But understanding that Hyper is underneath helps you debug issues, read error messages, and appreciate why certain APIs look the way they do.
Common Misconceptions and Mistakes
Axum is not a separate framework from Hyper:
A common beginner mistake is to think of Axum as a completely separate web framework that replaces Hyper. In reality, Axum is an abstraction layer on top of Hyper. When you run an Axum app, Hyper is always running too. You just don't see it.
Forgetting the Tokio runtime:
Because axum::serve uses Hyper, which requires an async runtime, you must run your main function with #[tokio::main] or manually start a Tokio runtime. If you try to call axum::serve without a runtime, you will get a panic. This is a very common error for newcomers.
You can still use Hyper directly in rare cases:
Axum lets you escape to raw Hyper if you need to, for example by mounting a Hyper service as a route with Router::route_service or Router::nest_service, or by serving a fallback service with Router::fallback_service. But for the vast majority of web applications, you will never need to do this.
The design is working if you never see Hyper:
If you build an Axum app and never import hyper directly, that is a sign you are using the library as intended. Axum is supposed to hide Hyper's complexity. You are still benefiting from Hyper, but you don't have to manage it.
A Real-World Perspective
Production web services built with Axum often run behind a reverse proxy like Nginx or Caddy. The proxy handles TLS termination, load balancing, and static file serving, and then forwards HTTP requests to your Axum server. In that setup, your Axum server talks HTTP over a local TCP connection. Hyper handles that HTTP conversation, and Axum handles your application logic.
Teams choose Axum over raw Hyper because Axum drastically reduces the amount of code they need to write and maintain, while still delivering the performance and reliability of the underlying stack. The fact that Axum is "just a thin layer" is considered a feature, not a limitation - it means you get the best of both worlds: a friendly API and a proven engine.
Summary
Axum is built on Hyper in a deliberate, layered way. Hyper provides the low-level HTTP protocol implementation and network I/O. Axum provides routing, extractors, responses, and middleware via Tower's service abstraction. This architecture keeps Axum small and fast while reusing a mature, battle-tested HTTP engine. You never need to write Hyper code to use Axum, but knowing that Hyper is underneath helps you understand where your requests go and why Axum's ecosystem integration is so seamless. With this foundation, you can now appreciate why Axum's middleware system works the way it does, and why the error handling model feels so predictable.