Service trait
Learn what the Tower Service trait is, why it sits underneath every Axum handler and middleware, and how to implement it yourself with working examples
Every Axum application you have built so far is made of handlers. A handler is a function that receives part of a request and returns a response. A handler like async fn hello() -> &'static str looks small and ordinary, and that is the point. Axum hides a larger idea behind that small function. Underneath every handler, every route, and every piece of middleware sits one shared shape, and that shape is the Service trait from the tower crate.
This page teaches that shape from the ground up. You will read the trait definition line by line, write your first service from scratch, wrap one service inside another, change requests and responses as they pass through, stop a request early, and test a service without starting a server. By the end you will understand why Axum has no middleware system of its own, and why learning this one trait unlocks every middleware you will meet in the rest of the chapter.
What a Service is
A service is an asynchronous function from a request to a response. The word asynchronous means the work may take time, so calling a service does not return the response at once. It returns a future, which is a value that represents work that will finish later. You await the future to get the result. If you have written an async fn handler, you already know this rhythm. A handler takes something in, does some work, and produces a response. A service is the same idea, written as a Rust trait so that different pieces of request handling can be stacked, swapped, and reused.
A trait in Rust is a set of methods and types that a type promises to provide. When a type implements the Service trait, it promises that it can accept a request and eventually produce a response. Axum converts your handler functions into services behind the scenes. Middleware is also a service. A middleware service wraps the handler service, does some work of its own, and then calls the inner service. The whole application becomes a chain of services calling each other, and every link in the chain has the same shape.
A useful way to picture this is a line of people passing a note. The first person reads the note, maybe writes something on it, and passes it to the next person. Each person does the same until the note reaches the last person, who writes the reply. The reply then travels back through the same line in reverse. Every person in that line is a service. The note going in is the request. The reply coming back is the response. Nobody in the line needs to know what anyone else does. Each person only needs to know how to receive a note, do their own small job, and pass it on.
Service comes from Tower, not Axum:
The Service trait is defined in the tower crate, a separate library that Axum builds on. Axum does not have its own middleware system. It adopts tower's Service trait as the universal interface, so middleware written for tower works with Axum, and the same trait shape is used by other tower-based tools such as tonic. Hyper 1.x is the exception. It defines its own hyper::service::Service trait rather than using tower's, so a tower service needs the TowerToHyperService adapter from the hyper-util crate before it can serve hyper requests directly.
The trait definition, line by line
Here is the definition as it appears in the tower crate. It looks dense at first, so the paragraphs below unpack each part in plain words.
use std::task::{Context, Poll};
pub trait Service<Request> {
type Response;
type Error;
type Future: Future<Output = Result<Self::Response, Self::Error>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>;
fn call(&mut self, req: Request) -> Self::Future;
}
The <Request> after the trait name is a generic parameter. A generic parameter is a placeholder for a type that gets filled in later. It means a service is always a service for one specific kind of request. When you use Axum, that request type is usually axum::extract::Request, which represents an incoming HTTP request with a method, a URI, headers, and a body. You will write impl Service<Request> for MyService, and the Request there is the Axum request type.
The three type lines inside the trait are associated types. An associated type is a type that each implementation must fill in with a concrete choice. When you implement the trait for your own type, you must say what each one is.
type Response is what your service produces when it succeeds. For Axum middleware, this is almost always axum::response::Response, the HTTP response type. type Error is what your service produces when something goes wrong. For Axum, this should almost always be std::convert::Infallible. Infallible is a special type that can never be constructed, so writing Result<Response, Infallible> is a way of saying the service never fails. Axum wants services to always produce a response, even for errors, rather than letting an error escape up the chain. type Future is the specific future type that call returns. Rust is an async language, so calling a service does not give you the response right away. It gives you a future that will eventually resolve to a Result<Response, Error>. The associated type lets you pick which kind of future to return, and you will see three common choices later on this page.
The two methods are where the work happens. poll_ready takes a mutable reference to the service and a Context, and it returns Poll::Ready(Ok(())) when the service can accept another request, or Poll::Pending when it is busy. You never call this method yourself in normal Axum code. The tower runtime calls it before each call to manage backpressure, which is the subject of its own section below. call takes the actual request and returns a future. This is the method that does the real work. The request goes in, and the future eventually resolves to a response or an error.
One detail in both method signatures matters for everything that follows. Both take &mut self, a mutable reference to the service itself. That means a service is stateful. It can hold data in its fields and change that data from one request to the next, like a counter, a connection pool, or a set of cached values. You will see a counter example near the end of this page.
Your first Service implementation
The best way to understand a trait is to implement it. Start with the simplest possible service, one that ignores the incoming request entirely and always returns the same response. This is the same job as a handler that always returns "Hello, World!", written as a service instead.
Create a new Rust project and add the required dependencies to Cargo.toml. The versions below are the current ones, axum 0.8.9 with tokio 1.54.1 and tower 0.5.3.
[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
tower = { version = "=0.5.3", features = ["util"] }
futures-util = "0.3"
Now put this code in src/main.rs.
use axum::{extract::Request, http::StatusCode, response::Response};
use std::{
convert::Infallible,
task::{Context, Poll},
};
use tower::Service;
// Our service type. It holds no state at all.
#[derive(Clone)]
struct HelloService;
impl Service<Request> for HelloService {
type Response = Response;
type Error = Infallible;
type Future = std::future::Ready<Result<Response, Infallible>>;
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Infallible>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, _request: Request) -> Self::Future {
let response = Response::builder()
.status(StatusCode::OK)
.body("Hello, World!".into())
.unwrap();
std::future::ready(Ok(response))
}
}
#[tokio::main]
async fn main() {
let mut service = HelloService;
let request = Request::builder()
.method("GET")
.uri("/")
.body(axum::body::Body::empty())
.unwrap();
let response = service.call(request).await.unwrap();
println!("Status: {}", response.status());
let body = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.unwrap();
println!("Body: {}", String::from_utf8_lossy(&body));
}
This is a complete program, and it runs without a server. The HelloService struct has no fields. It is only a marker type, a name to attach the implementation to. The #[derive(Clone)] line is included because Axum will require it when this kind of service is layered into a router, since Router::layer requires the layer to be Clone + Send + Sync + 'static, and a layer carrying this service clones the service along with it. The Service trait itself has no Clone bound at all, and this standalone program never layers the service into a router, so the derive is not needed for the program above to run. It is there so the same struct can be reused later without changes.
The call method builds a response with status 200 OK and the body "Hello, World!". It returns std::future::ready(...), which is a future that resolves immediately without ever yielding to the async runtime. Because this service does no real async work, Ready works as the future type. The main function builds a request by hand with Request::builder(), calls the service directly, awaits the future, and prints the result. Run it with cargo run and you will see this output.
Status: 200 OK
Body: Hello, World!
The request is completely ignored. No matter what URI or method you put in the builder, the response is always the same. That is the point of the example. A service is a function from request to response, and this one is the most boring function possible. Everything else on this page is a variation on this shape.
The rest of this page builds on this same file. Each new service below goes into the same src/main.rs, and each new main replaces the previous one, so the file always has exactly one main function.
The poll_ready method returns Poll::Ready(Ok(())) unconditionally. That says the service is always ready to accept a request, which is correct for a service that holds no limited resources. The underscore in _cx and _request tells the compiler you are deliberately ignoring those values.
A working first Service:
If your program compiles and prints Status: 200 OK followed by Body: Hello, World!, you have implemented the Service trait from scratch. This is the same trait Axum uses internally for every handler, route, and middleware. The rest of the chapter is variations on this one shape.
Why poll_ready exists
You might wonder why the trait has a poll_ready method at all. Why not just have call and be done with it? The answer is backpressure. Backpressure is a way for a system to say it is overloaded and ask the caller to stop sending work for a while. Real services often have limited capacity. A service that talks to a database might only handle a fixed number of concurrent queries. A service that calls an external API might have a limit on how many requests it can send per second. When more requests arrive than the service can handle, something has to give.
The poll_ready method lets a service communicate its current capacity to the caller. If it returns Poll::Ready(Ok(())), the service has room for another request. If it returns Poll::Pending, the service is busy, and the caller should wait before asking again. The Context argument carries a waker, which is a small handle the service uses to wake the caller up when capacity frees up. You do not need to use the waker yourself in simple services. Returning Ready unconditionally means there is nothing to wait for.
In Axum, you rarely interact with poll_ready directly. The tower runtime calls it for you before each call. A service is even allowed to panic if call is invoked without poll_ready first returning ready, which is why the runtime is careful to check. For beginner middleware, your poll_ready will almost always delegate to the inner service's poll_ready, like this.
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Infallible>> {
self.inner.poll_ready(cx)
}
That one line says the wrapper is ready exactly when the inner service is ready. If the inner service is busy, your middleware is busy too. If the inner service has capacity, your middleware does too. This delegation pattern is standard and correct for most cases. If your service holds no limited resources, like HelloService, returning Poll::Ready(Ok(())) unconditionally is the simplest correct behavior.
Never call poll_ready from inside call:
A common beginner mistake is calling poll_ready from inside the call method, thinking this checks readiness before processing the request. That is wrong. The runtime already called poll_ready before calling call, and the docs for call say implementations should take care not to call poll_ready. Inside call, assume the service is ready and just do the work. Calling poll_ready again inside call can cause subtle bugs and confusing runtime behavior.
Choosing the Future type for call
The call method returns a future instead of a response, because Rust's async model is built on futures. A future is a value that represents work that will complete at some point later. When you write async fn, Rust turns that into a function that returns a future. The same principle applies here. call starts the work and returns a future, and the caller awaits that future to get the result. Choosing the right future type is a real decision, and there are three common approaches.
std::future::Ready is the choice when your service does no actual async work. HelloService uses it. The future resolves immediately when awaited. This is the simplest option, and it only works for trivial services that already have their answer ready.
BoxFuture is the choice for middleware that wraps other services. It is a boxed future, which means the future is stored on the heap behind a pointer, and the exact type of the future is hidden. Boxing lets you use a familiar async block inside call and return it as one uniform type, no matter what the async block contains. The cost is one small heap allocation per request. For almost every middleware you will write, that cost is negligible, and the simplicity is worth it. The next section uses BoxFuture throughout.
A custom future type is the third choice. You define your own struct and implement the Future trait for it by hand. That gives the best performance with no heap allocation, but it requires understanding how to implement Future manually, which is an advanced Rust topic. You do not need it to write good middleware. Know that it exists, and reach for BoxFuture until a measured performance problem tells you otherwise.
Wrapping another Service to add logging
A service that always returns the same answer is a good first step, but middleware is about wrapping. A middleware service holds an inner service in a field, does some work of its own, and then calls the inner service. Here is a service that wraps another service and prints a log line for each request and each response.
use axum::{extract::Request, response::Response};
use futures_util::future::BoxFuture;
use std::{
convert::Infallible,
task::{Context, Poll},
};
use tower::Service;
#[derive(Clone)]
struct LoggingService<S> {
inner: S,
}
impl<S> Service<Request> for LoggingService<S>
where
S: Service<Request, Response = Response, Error = Infallible> + Send + 'static,
S::Future: Send + 'static,
{
type Response = Response;
type Error = Infallible;
type Future = BoxFuture<'static, Result<Response, Infallible>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Infallible>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, request: Request) -> Self::Future {
println!("Request received: {} {}", request.method(), request.uri());
let future = self.inner.call(request);
Box::pin(async move {
let response = future.await?;
println!("Response status: {}", response.status());
Ok(response)
})
}
}
This service is generic over the inner service type S. Generic means the struct works with any inner service, not one specific type. The struct holds a field called inner of type S. When call runs, it prints the request method and URI, then calls self.inner.call(request) to pass the request downstream. It wraps the inner future in a Box::pin(async move { ... }) block, which creates the boxed future. Inside the async block, it awaits the inner future to get the response, prints the response status, and returns the response.
The where clause constrains what S can be. It requires that S implements Service<Request> with Response = Response and Error = Infallible, that S is Send and 'static, and that S::Future is Send and 'static. Send means the type can be safely moved between threads. 'static means the type holds no borrowed references, so it owns everything it needs. Axum runs on a multi-threaded Tokio runtime, so services and their futures must be Send and 'static. If you forget these bounds, the compiler will produce an error that can be hard to read, so include them from the start.
The Box::pin call is needed because each async block has a unique compiler-generated type that has no name you can write down. Boxing erases that type into a BoxFuture<'static, Result<Response, Infallible>>, which is the type declared in type Future. The move keyword moves the inner future into the async block, so the block owns it.
To see this service run, wrap it around HelloService from the previous section. Add a small main that builds the chain by hand and sends one request through it.
#[tokio::main]
async fn main() {
let mut service = LoggingService { inner: HelloService };
let request = Request::builder()
.method("GET")
.uri("/hello")
.body(axum::body::Body::empty())
.unwrap();
let response = service.call(request).await.unwrap();
println!("Final status: {}", response.status());
}
Running this prints three lines. The first two come from the logging service, and the third comes from main.
Request received: GET /hello
Response status: 200 OK
Final status: 200 OK
Notice the order. The request line prints before the inner service runs, and the response line prints after it finishes. That sandwich shape, work before the call and work after the await, is the core pattern of all middleware. Logging, timing, authentication checks, and header changes are all variations on it.
Why the Send and 'static bounds appear everywhere:
The Send bound means a value can be moved to another thread safely. The 'static bound means a value owns its data and borrows nothing that could disappear while it is still in use. Axum runs handlers on a multi-threaded Tokio runtime, so a service and its future may move between threads at any await point. Both bounds together are what make that safe. When a compiler error mentions Send or 'static on a service, the fix is usually to add the bounds to the where clause, as in the example above.
Changing the request before it moves on
Now that you understand the wrapping pattern, you can use it to build practical middleware. One of the most common things middleware does is change the request before it reaches the handler. Here is a service that adds a custom header to every incoming request.
use axum::{extract::Request, http::HeaderValue, response::Response};
use futures_util::future::BoxFuture;
use std::{
convert::Infallible,
task::{Context, Poll},
};
use tower::Service;
#[derive(Clone)]
struct AddHeaderService<S> {
inner: S,
}
impl<S> Service<Request> for AddHeaderService<S>
where
S: Service<Request, Response = Response, Error = Infallible> + Send + 'static,
S::Future: Send + 'static,
{
type Response = Response;
type Error = Infallible;
type Future = BoxFuture<'static, Result<Response, Infallible>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Infallible>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, mut request: Request) -> Self::Future {
request.headers_mut().insert(
"x-request-source",
HeaderValue::from_static("axum-service-tutorial"),
);
let future = self.inner.call(request);
Box::pin(async move {
let response = future.await?;
Ok(response)
})
}
}
The difference from the logging example is small but important. The request parameter is declared as mut request, which is necessary because the code modifies the request by inserting a new header. The headers_mut() method returns a mutable reference to the request's header map, and insert adds the new header key and value. After adding the header, the code passes the modified request downstream by calling self.inner.call(request). The inner service, which could be your handler or another layer of middleware, receives the request with the custom header already in place. Nothing else changes. The response comes back untouched.
A header is only one example. The same pattern lets you rewrite the request URI, add data the handler will read later, or strip a header you do not want the handler to see. The rule is simple. Anything you can do to the request value before calling the inner service is request-side middleware.
Changing the response on the way back
Middleware can also work on the response side. After the inner service produces a response, your middleware can inspect it, change it, or replace it entirely before returning it to the caller. Here is a service that adds a header to every response.
use axum::{extract::Request, http::HeaderValue, response::Response};
use futures_util::future::BoxFuture;
use std::{
convert::Infallible,
task::{Context, Poll},
};
use tower::Service;
#[derive(Clone)]
struct AddResponseHeaderService<S> {
inner: S,
}
impl<S> Service<Request> for AddResponseHeaderService<S>
where
S: Service<Request, Response = Response, Error = Infallible> + Send + 'static,
S::Future: Send + 'static,
{
type Response = Response;
type Error = Infallible;
type Future = BoxFuture<'static, Result<Response, Infallible>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Infallible>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, request: Request) -> Self::Future {
let future = self.inner.call(request);
Box::pin(async move {
let mut response = future.await?;
response.headers_mut().insert(
"x-powered-by",
HeaderValue::from_static("axum-service-tutorial"),
);
Ok(response)
})
}
}
This example is nearly identical to the request-header one, but the change happens after awaiting the inner future. The future.await? line yields the inner service's response. The code then calls response.headers_mut().insert(...) to add a header before returning the response. You can combine request-side and response-side changes in a single service. Print a log line before calling the inner service, then print another after getting the response back, exactly as the logging example does. You can also read the response status and decide what to do next, for example counting how many responses came back with a 500 status.
Stopping a request early
So far every example has passed the request on to the inner service. A service does not have to do that. It can answer the request itself and never call the inner service at all. That is called short-circuiting, and it is how authentication middleware rejects a request before the handler ever sees it. Here is a service that blocks one path and lets everything else through.
use axum::{extract::Request, http::StatusCode, response::Response};
use futures_util::future::BoxFuture;
use std::{
convert::Infallible,
task::{Context, Poll},
};
use tower::Service;
#[derive(Clone)]
struct BlockPathService<S> {
inner: S,
}
impl<S> Service<Request> for BlockPathService<S>
where
S: Service<Request, Response = Response, Error = Infallible> + Send + 'static,
S::Future: Send + 'static,
{
type Response = Response;
type Error = Infallible;
type Future = BoxFuture<'static, Result<Response, Infallible>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Infallible>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, request: Request) -> Self::Future {
if request.uri().path() == "/blocked" {
let response = Response::builder()
.status(StatusCode::FORBIDDEN)
.body("This path is blocked".into())
.unwrap();
return Box::pin(async move { Ok(response) });
}
let future = self.inner.call(request);
Box::pin(async move {
let response = future.await?;
Ok(response)
})
}
}
When the request path is /blocked, the service builds a 403 Forbidden response itself and returns it immediately. The inner service is never called, so the handler never runs. For any other path, the request passes through unchanged. Send a request for /blocked through this service wrapped around HelloService and the body will be This path is blocked with status 403. Send a request for /hello and you get the normal Hello, World! reply. The short-circuit branch is the whole mechanism behind login checks. Replace the path comparison with a header check, and you have the skeleton of an authentication service.
The Error type and turning failures into responses
The Error associated type represents the possibility of failure. When call returns a future, that future resolves to a Result<Response, Error>. If it resolves to Err(e), something went wrong. In Axum, the convention is to use Infallible as the error type. Because Infallible can never be constructed, Result<Response, Infallible> effectively means the operation cannot fail. The ? operator on an Infallible error will never actually return early, because the error value can never exist.
Axum insists on Infallible because its error model requires handlers and services to always produce a response. If a service could fail with an error, that error would need to be converted into a response somewhere. By using Infallible, the type system guarantees that no error can escape. The following service compiles on its own, but you cannot plug it into an Axum router.
use axum::{extract::Request, response::Response};
use std::task::{Context, Poll};
use tower::Service;
#[derive(Clone)]
struct BadService;
impl Service<Request> for BadService {
type Response = Response;
type Error = String;
type Future = std::future::Ready<Result<Response, String>>;
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), String>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, _request: Request) -> Self::Future {
let response = Response::new("Hello".into());
std::future::ready(Ok(response))
}
}
Axum's router expects all services to have Error = Infallible. If you try to use this service, you will get a compile error about mismatched error types. The fix is to change type Error to Infallible and make sure call always returns Ok(...).
A non-Infallible Error type breaks compilation:
If your service declares an error type other than Infallible, Axum will refuse to accept it. The compiler error will mention that your service's error type does not match the expected Infallible. The fix is to change type Error to Infallible and convert any real errors into responses inside call, instead of propagating them as errors.
The right way to handle a fallible operation inside a service is to catch the error and convert it into a response. Here is a complete wrapper service that does exactly that. It holds an inner service whose Error type is a real error, such as std::io::Error, and turns any failure into a 500 Internal Server Error response. Its own Error type stays Infallible, because call always returns Ok.
use axum::{extract::Request, http::StatusCode, response::Response};
use futures_util::future::BoxFuture;
use std::{
convert::Infallible,
task::{Context, Poll},
};
use tower::Service;
#[derive(Clone)]
struct CatchErrorsService<S> {
inner: S,
}
impl<S> Service<Request> for CatchErrorsService<S>
where
S: Service<Request, Response = Response> + Send + 'static,
S::Future: Send + 'static,
S::Error: std::fmt::Display,
{
type Response = Response;
type Error = Infallible;
type Future = BoxFuture<'static, Result<Response, Infallible>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Infallible>> {
match self.inner.poll_ready(cx) {
Poll::Ready(Ok(())) => Poll::Ready(Ok(())),
Poll::Ready(Err(_)) => Poll::Ready(Ok(())),
Poll::Pending => Poll::Pending,
}
}
fn call(&mut self, request: Request) -> Self::Future {
let future = self.inner.call(request);
Box::pin(async move {
match future.await {
Ok(response) => Ok(response),
Err(error) => {
eprintln!("Inner service failed: {error}");
let error_response = Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.body("Something went wrong".into())
.unwrap();
Ok(error_response)
}
}
})
}
}
The where clause is the interesting part. It does not fix the inner error type to one concrete type. It says the inner service can fail with any error type, as long as that error can be printed with Display, which the eprintln! line needs. The match on the awaited future is where the conversion happens. On Ok, the response passes through untouched. On Err, the code logs the error and builds a 500 response, then returns it wrapped in Ok. The error type stays Infallible because call always returns Ok. The failure is handled by producing an error response, not by returning an error.
The poll_ready method needs the same treatment. The inner service's readiness check can fail with a real error, but this service's poll_ready can only return Infallible, so a readiness failure is converted to Poll::Ready(Ok(())). That is safe here because any real failure still surfaces from call as a 500 response instead of a dropped connection.
To see it run, wrap it around a service that always fails. Add this small failing service and a main to the same file.
#[derive(Clone)]
struct AlwaysFailsService;
impl Service<Request> for AlwaysFailsService {
type Response = Response;
type Error = std::io::Error;
type Future = std::future::Ready<Result<Response, std::io::Error>>;
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), std::io::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, _request: Request) -> Self::Future {
std::future::ready(Err(std::io::Error::new(
std::io::ErrorKind::Other,
"database down",
)))
}
}
#[tokio::main]
async fn main() {
use tower::ServiceExt;
let mut service = CatchErrorsService {
inner: AlwaysFailsService,
};
let request = Request::builder()
.uri("/")
.body(axum::body::Body::empty())
.unwrap();
let response = service.oneshot(request).await.unwrap();
println!("Status: {}", response.status());
let body = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.unwrap();
println!("Body: {}", String::from_utf8_lossy(&body));
}
Running this prints the error line to standard error, then the 500 response the client actually receives.
Inner service failed: database down
Status: 500 Internal Server Error
Body: Something went wrong
The client receives a clean HTTP status instead of a dropped connection. That distinction matters. If an error escapes a service and reaches the HTTP server underneath Axum, the connection closes without any response at all, and the client sees a network failure rather than a status code it can understand.
Testing a Service without starting a server
You do not need a running server to test a service. Tower provides a helper called oneshot, available through the ServiceExt trait, which sends exactly one request through a service and returns the response. It is the fastest way to check that your service behaves as written. Add a test to the same project.
#[cfg(test)]
mod tests {
use super::*;
use axum::body::Body;
use tower::ServiceExt;
#[tokio::test]
async fn hello_service_returns_hello_world() {
let request = Request::builder()
.uri("/")
.body(Body::empty())
.unwrap();
let response = HelloService.oneshot(request).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let body = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.unwrap();
assert_eq!(&body[..], b"Hello, World!");
}
#[tokio::test]
async fn block_path_service_blocks_the_blocked_path() {
let mut service = BlockPathService { inner: HelloService };
let request = Request::builder()
.uri("/blocked")
.body(Body::empty())
.unwrap();
let response = service.oneshot(request).await.unwrap();
assert_eq!(response.status(), StatusCode::FORBIDDEN);
}
}
Run these with cargo test. These tests live in the same src/main.rs as the services above, so use super::*; brings HelloService and BlockPathService into scope. The first test sends a request through HelloService and checks the status and body. The second sends a request for /blocked through the short-circuit service and checks that it comes back 403. The oneshot helper consumes the service, which is why the second test builds the service inside the test. For a service you want to reuse across tests, build a fresh one in each test. This pattern is how you verify middleware behavior in seconds, without binding a port or running curl.
State inside a Service
Because call takes &mut self, a service can keep data in its fields and change it across requests. Here is a service that counts how many requests it has handled and adds the count as a response header.
use axum::{extract::Request, http::HeaderValue, response::Response};
use futures_util::future::BoxFuture;
use std::{
convert::Infallible,
task::{Context, Poll},
};
use tower::Service;
#[derive(Clone)]
struct CountingService<S> {
inner: S,
count: usize,
}
impl<S> Service<Request> for CountingService<S>
where
S: Service<Request, Response = Response, Error = Infallible> + Send + 'static,
S::Future: Send + 'static,
{
type Response = Response;
type Error = Infallible;
type Future = BoxFuture<'static, Result<Response, Infallible>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Infallible>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, request: Request) -> Self::Future {
self.count += 1;
let count = self.count;
let future = self.inner.call(request);
Box::pin(async move {
let mut response = future.await?;
let value = HeaderValue::from_str(&count.to_string())
.unwrap_or_else(|_| HeaderValue::from_static("0"));
response.headers_mut().insert("x-request-count", value);
Ok(response)
})
}
}
Each call increments self.count before the inner service runs, copies the value into a local variable, and then moves that copy into the async block, where it becomes the x-request-count header. The copy matters. The async block cannot borrow self, because the boxed future is 'static, so anything the block needs must be owned before the block is created. Send three requests through one CountingService and the header will read 1, then 2, then 3. Drive the repeated requests with call directly, as in the earlier programs, because oneshot consumes the service after a single request and cannot be called three times on the same value.
There is one catch to this kind of state, and it is easy to get wrong. When Axum applies a layer to routes added with .route(), it builds a fresh service for every request, so state stored on the service itself does not survive from one request to the next. The counter above would read 1 on every request if the service were rebuilt each time. State that must be shared across requests belongs in the layer that builds the service, behind a shared pointer such as Arc, because the layer is what gets cloned and reused. State on the service is still useful for per-request bookkeeping and for services you drive directly, as in the standalone programs on this page, but do not rely on it to persist across requests inside a router.
Services beyond Axum
The Service trait is not an Axum invention, and its uses are not limited to Axum. Tonic, a Rust library for gRPC services, builds its servers on tower services too, so the same trait shape shows up there. A service written for Axum does not move across unchanged, though, because the request type is different: Axum services take http::Request<axum::body::Body>, while tonic services take requests carrying tonic's own body type. The pattern transfers directly, and a logging or timing wrapper written in the generic style of this page can be adapted, but the concrete service needs its request type changed first. That shared shape is the payoff of Axum adopting tower instead of inventing its own interface. You learn one shape, and it appears across the ecosystem.
Hyper 1.x is the one place where the shape differs. Hyper defines its own hyper::service::Service trait rather than using tower's. A tower service cannot be handed to hyper directly. The hyper-util crate provides an adapter called TowerToHyperService that wraps a tower service and presents it as a hyper service. You do not need the adapter when you work with Axum, because Axum performs that bridging for you internally. You only need to know it exists if you ever build a raw hyper server and want to reuse a tower service there.
Common mistakes and misconceptions
When you first implement the Service trait, several things can trip you up. Here are the most common mistakes, each with its cause and its fix.
Forgetting the Clone derive is the first. The Service trait itself does not require Clone, but Axum's Router::layer requires the layer to be Clone, and the router clones the layer each time it builds the service for a request. If your service struct is carried inside a layer, it must be Clone too, or the compiler will reject the layer. Every service struct in the examples above includes the derive for this reason.
Declaring the wrong error type is the second. Axum expects Error = Infallible. If you declare type Error = BoxError or type Error = String, your service will not be compatible with Axum's router. Always use Infallible and convert real errors into responses inside call.
Calling poll_ready from inside call is the third. The runtime calls poll_ready before every call. If you call it again inside call, you are doing double work and may cause the service to behave incorrectly. Assume readiness inside call and just do the work.
Not delegating poll_ready to the inner service is the fourth. If your service wraps an inner service and you return Poll::Ready(Ok(())) unconditionally from poll_ready instead of delegating to self.inner.poll_ready(cx), you are ignoring the inner service's capacity. The inner service might be busy, but your middleware would tell the runtime it is ready anyway. That can overload downstream systems. Always delegate poll_ready to the inner service.
Using the wrong request type is the fifth. The Service trait is generic over the request type. In Axum middleware, you must implement Service<axum::extract::Request>, which is http::Request<axum::body::Body>. If you implement the trait for a request carrying a different body, such as http::Request<hyper::body::Incoming>, the compiler will complain that your service does not match what Axum expects.
Trait bound errors look worse than they are:
When you make one of these mistakes, the Rust compiler will produce an error. Some of these errors, especially trait bound errors involving Service, Layer, and Send, can be long and difficult to read. If you see an error that mentions Service<Request> not being satisfied, check the five mistakes above first. The fix is usually one of these. Add Clone, change the error type to Infallible, delegate poll_ready, or use the correct request type.
Summary
A service is an async function from request to response, packaged as a Rust trait so it can be composed and reused. Every handler in Axum is a service. Every middleware is a service. Because every service has the same shape, poll_ready plus call returning a future, they can be stacked without limit. Your logging service can wrap an authentication service, which wraps a rate-limiting service, which wraps the handler, and the outer service just calls self.inner.call(request) and awaits the result.
The decision framework that falls out of this page is short. If you need a single piece of behavior that transforms a request or a response, write a service that wraps an inner service and does its work around the call. If the work needs no async behavior of its own, use std::future::Ready as the future type. If it wraps another service, use BoxFuture. If a request should never reach the handler, return a response yourself and skip the inner call. If something inside can fail, turn the failure into a response and keep Error = Infallible. And if the behavior needs to be reused across many different services, the next idea to learn is the factory that builds services, which is the Layer trait.