Actix-web vs Axum Tower Service Model
A beginner-friendly comparison of how Actix-web and Axum structure their request handling with the service model they now share, including code examples and common mistakes
Both Actix-web and Axum let you build web servers in Rust, but they organize their request handling with two different service models under the hood. Axum is built around Tower's Service trait, while Actix-web 4.x is built around its own Service and Transform traits from the actix-service crate. The two models look alike - both wrap a service inside another service - but they use different traits, so middleware written for one does not plug into the other. To use either framework well - and to understand why their middleware, routing, and handler code look different - you need to see what these two models actually mean and how they shape the code you write.
Actix-web used to be actor-based - that changed in version 4:
Actix-web 1-3 were built on the actix actor framework, and older tutorials still describe it that way. Actix-web 4.x (current: 4.19.0, November 2026) is not actor-based: handlers are plain async functions, and request handling runs through actix-service/actix-rt with a Tower-like service/layer model. The actor framework still exists as a separate crate, and you can opt into it for stateful pieces such as WebSocket connection actors (actix-web-actors), but it is no longer the framework's core. This page describes Actix-web 4.x as it works today.
Both frameworks are described on this page from scratch, so we will define the important terms here before diving into examples.
What the Tower Service Model Is
Tower is a Rust library that defines a single, uniform way to think about an asynchronous operation. That uniform idea is called a Service. A Service takes a request, does some asynchronous work, and returns a response. It is deliberately abstract: the request could be an HTTP request, a database query, or something else entirely, and the response can likewise be any type.
The core of Tower is the Service trait. In plain words, a Service is anything that can say: "give me a request, and I will eventually give you back a response or an error." The word "eventually" matters because this is async Rust - the Service might need to wait for I/O, a timer, another service, or some other asynchronous operation before it can produce the response.
// A simplified look at what Tower's Service trait expresses.
// This is not the exact Tower source, but it captures the idea.
use std::future::Future;
trait Service<Request> {
type Response;
type Error;
type Future: Future<Output = Result<Self::Response, Self::Error>>;
fn call(&self, req: Request) -> Self::Future;
}
A Service wraps a call method. That method receives a request and returns a Future. When the Future completes, you get either the response or an error. This single pattern - request in, future out, response or error later - is the foundation of everything in Tower.
Why Tower Exists:
Before Tower, async Rust libraries often invented their own middleware and request-handling abstractions. That made it hard to reuse a timeout, rate limiter, or tracing wrapper across different projects. Tower standardizes those wrappers so a middleware written for one Tower-based system can work with another Tower-based system.
How Services Compose
A Service by itself is not very exciting. The real power comes from wrapping one Service inside another. That is what middleware does in the Tower model.
Imagine you have a Service that takes an HTTP request and returns an HTTP response. Now imagine you want to add a timeout: if the inner Service takes longer than two seconds, you want to return an error instead of waiting forever. Tower lets you build a Timeout layer that wraps your Service. When a request arrives, the Timeout layer starts a timer and then passes the request to the inner Service. If the inner Service does not finish in time, the Timeout layer returns an error on its own.
This wrapping pattern is called layering. Each wrapper is a Service itself, so each wrapper has the same shape: request in, future out. Because every layer has that shape, you can stack as many as you want.
Request
|
v
+----------------------+
| Timeout Service |
| (outer layer) |
+----------------------+
|
| calls inner service
v
+----------------------+
| Tracing Service |
| (middle layer) |
+----------------------+
|
| calls inner service
v
+----------------------+
| Your handler logic |
| (inner service) |
+----------------------+
|
v
Response
The request flows from the outermost layer to the innermost. The response flows back out through the same stack. Because each layer is a Service, a layer does not need to know what the next layer does - it only needs to know that the next layer is also a Service.
From Tower Service to Axum Router
Axum does not ask you to manually implement the Tower Service trait for every handler. Instead, Axum gives you a high-level Router type and ordinary async functions called handlers. Under the hood, Axum converts your Router and your handlers into Services. That conversion is what allows Axum to accept Tower middleware so easily.
When you write this in Axum:
use axum::{routing::get, Router};
async fn hello() -> &'static str {
"Hello, world!"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(hello));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
println!("Listening on http://localhost:3000");
axum::serve(listener, app).await.unwrap();
}
...the app value is a Router. axum::serve takes that Router and runs it on a Tokio listener. The Router behaves as a Service at the outermost level: it takes HTTP requests and returns HTTP responses. Inside, your hello function has been wrapped into a Service as well.
That means when you add Tower middleware to an Axum app, you are not learning a separate Axum-specific middleware system. You are using the same Service wrapping concept that Tower defines once and shares everywhere.
What Actix-web's Service Model Is
Actix-web 4.x does not use Tower's Service trait as its main extension point. Instead, it has its own pair of traits from the actix-service crate: Transform and Service. They play the same roles as Tower's Layer and Service, but they are Actix-specific types. A Transform takes an inner service and returns a new service that wraps it - that is how Actix-web middleware is built. The wrapped service's call method receives a ServiceRequest, does its work, calls the inner service, and returns a ServiceResponse.
Actix-web runs on actix-rt, a small runtime built on Tokio that runs one single-threaded executor per worker thread. HttpServer spawns one worker per CPU core and distributes connections across them. That worker model is a leftover of the framework's actor heritage - isolated workers that do not share memory - but the workers are not actors, and you never write actor code to handle a request.
Actors still exist - as an opt-in, not the core:
The actix actor framework is a separate crate that Actix-web 4.x does not depend on for request handling. You can still use it when you want it: the actix-web-actors crate lets you manage stateful WebSocket connections as actors, and the actix crate can run background tasks. For a normal JSON API, you will never touch it - handlers are plain async functions, just like in Axum.
Services and Transforms
To understand why Actix-web code looks different, consider what its middleware trait looks like in miniature. A Transform is a factory: given an inner service, it produces a wrapped service. The wrapped service intercepts call, exactly like a Tower layer does.
use actix_service::{Service, Transform};
use actix_web::{dev::{ServiceRequest, ServiceResponse}, Error};
use std::future::{ready, Ready};
// A Transform takes an inner service `S` and produces a new service.
// (Simplified sketch - real middleware also declares associated types
// for the response, error, and the future `new_transform` returns.)
struct LogTransform;
impl<S, B> Transform<S, ServiceRequest> for LogTransform
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
S::Future: 'static,
B: 'static,
{
type Response = ServiceResponse<B>;
type Error = Error;
type Transform = LogService<S>;
type InitError = ();
type Future = Ready<Result<Self::Transform, Self::InitError>>;
fn new_transform(&self, service: S) -> Self::Future {
ready(Ok(LogService { service }))
}
}
struct LogService<S> {
service: S,
}
Here LogTransform is the middleware, and LogService is the service it produces. The middleware wraps the inner service, runs code before and after self.service.call(req), and returns the response. That is the same wrapping idea as Tower - the difference is only the trait names and the request/response types (ServiceRequest/ServiceResponse instead of http::Request/http::Response).
This is the service model: isolated services plus wrapping. In a web framework, the "service" might be your handler, a logger, or a compressor. The "wrapping" is how middleware composes.
The Key Architectural Difference
Now we can put the two models side by side.
Axum's model says: everything is a Service. A Service is a function-shaped thing that takes a request and returns a response future. Middleware wraps Services. Handlers become Services. The Router becomes a Service. Extension is achieved by writing more Services or wrapping existing ones.
Actix-web 4.x's model says the same thing, but with its own traits: everything is an actix-service Service, and middleware is a Transform that wraps one service into another. Handlers are plain async functions that the framework turns into services. Extension is achieved by adding Actix-web-specific middleware, handlers, and other components.
So the real difference is not "services vs actors" - both frameworks are service-based today. The difference is which service traits they use: Tower's shared, generic Service/Layer (usable with hyper, tonic, and anything else in the Tokio ecosystem) versus Actix-web's own Transform/Service (usable only inside Actix-web). That is why a Tower layer cannot be plugged into Actix-web, and an Actix-web middleware cannot be plugged into Axum.
Tower Middleware Does Not Work in Actix-web:
A Tower middleware crate - like a Tower timeout or Tower rate limiter - cannot be plugged directly into Actix-web. Actix-web has its own middleware trait system that is not Tower-compatible. This is one of the biggest practical consequences of the architectural split.
The Axum approach benefits from reusing the broad Tower and tower-http ecosystem. If someone writes a Tower middleware for another Rust async project, there is a good chance it works with Axum with minimal effort.
The Actix-web approach benefits from having its own integrated, mature middleware and utility ecosystem that is designed specifically for Actix-web. The pieces fit together tightly, but they are not interchangeable with Tower-based tools.
How This Affects Your Handler Code
The architectural difference shows up in the code you write for each framework. Let's compare a simple handler that reads a query string.
First, in Axum:
use axum::{extract::Query, routing::get, Router};
use serde::Deserialize;
#[derive(Deserialize)]
struct Pagination {
page: Option<u32>,
}
async fn list_items(
Query(params): Query<Pagination>,
) -> String {
let page = params.page.unwrap_or(1);
format!("Showing page {page}")
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/items", get(list_items));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
The handler is an ordinary async function. The Query extractor pulls the query string out of the request and deserializes it into the Pagination struct. There are no attributes, no macros on the function, and no framework-specific wrapper types beyond the extractors. The function body looks like regular Rust async code.
Now the same idea in Actix-web:
use actix_web::{get, web, App, HttpServer, Responder};
use serde::Deserialize;
#[derive(Deserialize)]
struct Pagination {
page: Option<u32>,
}
#[get("/items")]
async fn list_items(
query: web::Query<Pagination>,
) -> impl Responder {
let page = query.page.unwrap_or(1);
format!("Showing page {page}")
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.service(list_items)
})
.bind(("0.0.0.0", 3000))?
.run()
.await
}
Here the handler has a #[get("/items")] attribute that binds the route. The web::Query extractor is Actix-web's own extractor. The function returns impl Responder, which is Actix-web's response abstraction. The server is built with HttpServer::new and App::new, which are Actix-web's own runtime and routing types.
Neither approach is objectively better in isolation. They reflect the different service traits underneath. Axum's handler is a plain async function that fits the Tower Service world. Actix-web's handler is a plain async function too - decorated with Actix-web attributes and types that fit its own actix-service world, not an actor world.
Middleware in Each Model
The difference becomes even clearer with middleware. Middleware is code that runs before or after your main handler logic. It can inspect requests, modify responses, enforce authentication, add logging, and so on.
Axum Middleware Uses Tower
In Axum, you can use any Tower layer. Here is an example using tower-http to add request tracing:
use axum::{routing::get, Router};
use tower_http::trace::TraceLayer;
async fn hello() -> &'static str {
"Hello, world!"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(hello))
.layer(TraceLayer::new_for_http());
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
TraceLayer is a Tower layer from the tower-http crate. Axum accepts it directly because Axum's Router is a Tower Service. You do not need to translate, adapt, or wrap it. The same TraceLayer could be used in another Tower-based project.
Actix-web Middleware Uses Its Own Trait
Actix-web middleware must implement Actix-web's own Transform and Service traits. These are distinct from Tower's traits. A simple logging middleware in Actix-web looks like this:
use actix_web::{
dev::{ServiceRequest, ServiceResponse},
middleware::Logger,
App, Error, HttpServer,
};
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.wrap(Logger::default())
})
.bind(("0.0.0.0", 3000))?
.run()
.await
}
Logger is an Actix-web middleware. It works well and is easy to use, but it is not a Tower layer. You cannot take this Logger and use it in an Axum app, and you cannot take a Tower TraceLayer and use it directly in Actix-web.
Do Not Mix Tower and Actix Middleware:
Attempting to use Tower layers in Actix-web or Actix-web middleware in Axum will not compile. The traits are different, even though the concepts sound similar. If you are switching frameworks, expect to rewrite your middleware using the target framework's specific traits.
A Side-by-Side Comparison with a Shared Example
Let's look at a slightly more complete example. We will build a small endpoint that responds with a greeting and a query parameter, then show how the same feature looks in each framework.
Axum Version
use axum::{extract::Query, routing::get, Router};
use serde::Deserialize;
#[derive(Deserialize)]
struct GreetingParams {
name: Option<String>,
}
async fn greet(
Query(params): Query<GreetingParams>,
) -> String {
let name = params.name.unwrap_or_else(|| "world".to_string());
format!("Hello, {name}!")
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/greet", get(greet));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
println!("Listening on http://localhost:3000");
axum::serve(listener, app).await.unwrap();
}
To test this, run cargo run and open http://localhost:3000/greet?name=Alice in your browser. You should see Hello, Alice!. Open http://localhost:3000/greet and you should see Hello, world!.
The handler is a normal async function. The Query extractor deserializes the query string. The Router connects the /greet path to the handler. The server runs on Tokio through axum::serve.
Actix-web Version
use actix_web::{get, web, App, HttpServer, Responder};
use serde::Deserialize;
#[derive(Deserialize)]
struct GreetingParams {
name: Option<String>,
}
#[get("/greet")]
async fn greet(
query: web::Query<GreetingParams>,
) -> impl Responder {
let name = query.name.clone().unwrap_or_else(|| "world".to_string());
format!("Hello, {name}!")
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.service(greet)
})
.bind(("0.0.0.0", 3000))?
.run()
.await
}
The route is declared with the #[get("/greet")] attribute. The handler is registered with .service(greet). The server runs on Actix-web's own runtime through HttpServer.
Both examples solve the same problem. The difference is in the surrounding machinery. In Axum, routing and handler registration are explicit and macro-free. In Actix-web, the route is attached via an attribute macro, and the handler is registered through the App builder.
Why the Service Model Makes Axum More Composable
Because Axum is built on Tower, you can combine Axum with other Tower-based libraries in ways that would be difficult in Actix-web. Suppose you want to add a timeout and a concurrency limit to a handler. In Axum, you can use Tower's concurrency limit layer directly, and the timeout layer from tower-http.
The timeout layer needs a short note first. Tower also ships its own tower::timeout::TimeoutLayer, but you cannot put it on an Axum Router: its error type is BoxError, and a Router layer must be infallible, so the code does not compile. The tower-http version is the one to use here, because instead of producing an error it answers the client directly with a status code you choose.
Add tower-http with its timeout feature to your project:
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
tower = "0.5"
tower-http = { version = "0.7", features = ["timeout"] }
use axum::{http::StatusCode, routing::get, Router};
use std::time::Duration;
use tower::limit::ConcurrencyLimitLayer;
use tower_http::timeout::TimeoutLayer;
async fn slow_handler() -> &'static str {
// Simulate slow work
tokio::time::sleep(Duration::from_secs(5)).await;
"Finished"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/slow", get(slow_handler))
.layer(ConcurrencyLimitLayer::new(10))
.layer(TimeoutLayer::with_status_code(
StatusCode::REQUEST_TIMEOUT,
Duration::from_secs(3),
));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
ConcurrencyLimitLayer limits how many requests can be processed simultaneously. TimeoutLayer::with_status_code takes the status code first and the duration second: if the handler takes longer than 3 seconds, the client gets a 408 Request Timeout response instead of waiting. Both are standard Tower layers, and Axum accepts them without any adapter code. Run it and request /slow - the handler sleeps for 5 seconds, so you will see a 408 after 3 seconds.
In Actix-web, you would need to use Actix-web's own timeout and concurrency middleware, or write custom middleware using the Actix-web trait system. The concepts are the same, but the implementation is tied to Actix-web.
Tower Compatibility Is Axum's Superpower:
If you learn how Tower Services and Layers work, you gain a skill that applies far beyond Axum. The same layering patterns appear in other Tokio-ecosystem tools like tonic for gRPC. This is one of the strongest practical arguments for choosing Axum when you already work in the Tokio ecosystem.
What Happens Inside Axum When a Request Arrives
To build a deeper mental model of the Service approach, walk through the journey of a single request in an Axum app.
- The Tokio runtime accepts a TCP connection from a listener.
axum::servepasses the HTTP request to the Router.- The Router acts as the outermost Service. It receives the request through its
callmethod. - The Router inspects the request's method and path, then finds the matching route.
- The matched route's handler has already been converted into a Service. The Router calls that handler Service.
- The handler Service runs any extractors you declared as function arguments.
- The handler function executes its body, producing a response.
- The response travels back up through any middleware layers that were added with
.layer. - The final response is written to the TCP connection.
The key insight: every step that handles the request is a Service. The Router is a Service. The handler is a Service. Middleware layers are Services. This uniformity is what makes Axum's design feel clean and composable.
What Happens Inside Actix-web When a Request Arrives
Actix-web's flow is similar, but built on its own traits.
- The
actix-rtruntime accepts a TCP connection. HttpServerdistributes the connection to one of its worker threads.- The worker passes the request through the App's middleware chain - each middleware is a
Transformwrapping the next service. - The App matches the request to a route.
- The route runs the handler function with Actix-web's extractors.
- The handler returns an
impl Responder, which Actix-web converts into an HTTP response. - The response travels back through the middleware chain.
- The worker writes the response to the TCP connection.
No actors are involved in this flow. You never create an actor in a normal Actix-web 4.x project; the service chain handles request distribution and middleware.
Where Actors Still Appear in Actix-web
In Actix-web 4.x, the actor model is an opt-in tool, not the foundation. It becomes visible when you use features that are built on the separate actix crate - most commonly WebSocket actors via actix-web-actors, where each connection is an actor that receives messages, or background tasks built on the actor system. In those cases, you define actors, send messages, and manage actor lifecycles yourself.
Axum has no actor option at all. For background tasks, Axum relies on Tokio primitives like tokio::spawn, channels, and shared state. For WebSockets, Axum works directly with the upgraded connection rather than wrapping it in an actor.
This is a reflection of the two frameworks' histories: Actix-web grew out of an actor framework and kept actors as an optional extra, while Axum was built on Tower and Tokio from the start and never added them.
Choosing Between the Two Models
The choice between Actix-web and Axum often comes down to which mental model you prefer and which ecosystem you need.
Choose Axum when:
- You want full compatibility with the Tower and tower-http ecosystem.
- You already use Tokio-based libraries and want a consistent async stack.
- You prefer macro-free routing and plain async function handlers.
- You value being able to reuse middleware across different Tokio ecosystem projects.
Choose Actix-web when:
- You need Actix-web's mature, integrated middleware and utility ecosystem.
- You want its opt-in actor support for stateful pieces such as WebSocket connection actors.
- You prefer Actix-web's attribute-macro routing style.
- You do not need Tower compatibility and are willing to commit to Actix-web's specific abstractions.
Both Frameworks Are Mature:
Actix-web is not "legacy" and Axum is not "experimental." Both are production-tested and actively maintained - Actix-web 4.19.0 and Axum 0.8.9 are the current stable lines. The Tower service model is not objectively superior to Actix-web's own service model - they are different design choices with different trade-offs.
Common Misconceptions
"Axum and Actix-web are basically the same thing"
They look similar from the outside: both are Rust web frameworks, both use async/await, both have extractors and middleware. But the internal models are different. Axum is built on Tower's shared Service/Layer traits; Actix-web 4.x is built on its own actix-service Transform/Service traits. That difference affects middleware compatibility, runtime choice, and advanced feature design.
"Tower middleware works everywhere"
Tower middleware works in Tower-based projects. Axum is Tower-based. Actix-web is not. So Tower middleware does not work in Actix-web. This surprises developers who assume Rust middleware is universal.
"Actix-web is built on the actor model"
That was true for Actix-web 1-3, but not for Actix-web 4.x. The actor framework was the foundation of the early versions; version 4 replaced it with the actix-service service model, and handlers became plain async functions. Actors survive only as an opt-in (for example, WebSocket actors via actix-web-actors). If you read a tutorial that says Actix-web handlers must be actors, it predates version 4.
"If Axum uses Tower, I must implement the Service trait myself"
No. Axum lets you write ordinary async functions as handlers. It converts them into Services for you. You can use Tower layers without ever implementing the Service trait by hand, though understanding the trait helps when debugging or building custom middleware.
Keep the Models Separate in Your Head:
When you read Axum code, think in terms of Tower Services and Layers. When you read Actix-web code, think in terms of actix-service Transforms and Services. Trying to map every Actix concept onto Tower - or vice versa - will make both frameworks feel more confusing than they are.
A Summary That Connects the Threads
The Tower Service model and Actix-web's own service model solve the same high-level problem - how to build asynchronous, concurrent servers - in similar ways with incompatible traits. Tower reduces everything to a request-in, response-out Service that can be layered and composed, and it shares that abstraction across the whole Tokio ecosystem. Actix-web's actix-service model does the same wrapping with its own Transform and Service traits, tuned to Actix-web's request and response types.
Axum inherits the Tower Service model and therefore inherits the entire Tower ecosystem: timeout layers, tracing layers, rate limiters, concurrency limiters, and more. Actix-web inherits its own service model and builds its own integrated middleware system on top of it.
The practical consequence for a beginner is not that one approach is always better. It is that the two frameworks have different extension points, different middleware ecosystems, and different runtime assumptions. Knowing which model you are working in explains why the code looks the way it does - and why you cannot simply copy middleware from one framework into the other.
If you are coming from Actix-web and moving to Axum, the biggest shift is not syntax. It is mental. You stop thinking about Actix-specific Transforms and start thinking about Tower Services and Layers. Once that mental shift happens, Axum's design feels simple and predictable. If you go the other direction, from Axum to Actix-web, the biggest shift is learning Actix-web's own middleware and runtime abstractions instead of reaching for Tower.