Axum "Handler<_, _> Is Not Satisfied": Eight Causes, Eight Repros
The trait bound fn(...): Handler<_, _> is not satisfied looks the same whatever you broke. I reproduced eight causes on axum 0.8.9, ran each one with and without #[axum::debug_handler], and wrote down the line that names the cause and the fix.
TL;DR. Put #[axum::debug_handler] on the handler the error points at and run cargo check again. The Handler<_, _> error stays at the bottom of the output, but above it you now get one error that names the real problem. Read that one first, then find it in this table:
| Cause | Telltale line with #[axum::debug_handler] | Fix |
|---|---|---|
std::sync::MutexGuard or Rc held across .await | error: future cannot be sent between threads safely | drop the guard before .await, or use tokio::sync::Mutex / Arc |
Json, String or Bytes not the last argument | `Json<_>` consumes the request body and thus must be the last argument to the handler function | move the body extractor to the end |
| your own type as an argument | the trait bound `CurrentUser: FromRequest<(), axum_core::extract::private::ViaParts>` is not satisfied | impl FromRequestParts<S> for it |
Json<T> with T not Deserialize | the trait bound `NewUser: serde::Deserialize<'de>` is not satisfied | #[derive(Deserialize)] |
Result<_, E> with E not IntoResponse | the trait bound `AppError: IntoResponse` is not satisfied | impl IntoResponse for AppError |
plain fn instead of async fn | error[E0277]: `&str` is not a future | make it async fn |
a reference argument (&HeaderMap) | error[E0637]: `&` without an explicit lifetime name cannot be used here | take the extractor by value |
| 17 or more arguments | error: Handlers cannot take more than 16 arguments | nest some extractors in a tuple |
One cause from the usual lists is missing on purpose: a State type that doesn’t match with_state. On axum 0.8.9 it never produced this error for me. It gives mismatched types instead, covered near the end.
The error, and why it says nothing
Here is the whole output for the first repro, a counter behind a std::sync::Mutex:
Checking handler-repros v0.1.0 (/w)
error[E0277]: the trait bound `fn(State<Arc<Mutex<u64>>>) -> _ {handler}: Handler<_, _>` is not satisfied
--> src/bin/c1_send_broken.rs:13:25
|
13 | .route("/", get(handler))
| --- ^^^^^^^ the trait `Handler<_, _>` is not implemented for fn item `fn(State<Arc<std::sync::Mutex<u64>>>) -> impl Future<Output = String> {handler}`
| |
| required by a bound introduced by this call
|
= note: Consider using `#[axum::debug_handler]` to improve the error message
note: required by a bound in `axum::routing::get`
--> /usr/local/cargo/registry/src/index.crates.io-1949cf8c6b5b557f/axum-0.8.9/src/routing/method_routing.rs:167:16
|
167 | H: Handler<T, S>,
| ^^^^^^^^^^^^^ required by this bound in `get`
...
441 | top_level_handler_fn!(get, GET);
| ------------------------------- in this macro invocation
[...]
error: could not compile `handler-repros` (bin "c1_send_broken") due to 1 previous error
It points at the .route(...) call, not at the handler, and it only says that the function is not a Handler. The reason is structural. axum doesn’t check your function against a list of rules. It has blanket impls of Handler for functions that happen to fit a shape, and the handler docs spell that shape out: an async fn, at most 16 arguments that are all Send, every argument except the last implementing FromRequestParts, the last implementing FromRequest, a return type that implements IntoResponse, and a future that is Send. When one condition fails, no impl matches, and rustc can only tell you that no impl matched. It can’t tell you which condition you missed, because from its side there was no condition, only a set of impls that didn’t apply.
The note: Consider using #[axum::debug_handler] line is axum talking, not rustc. In the 0.8.9 source the Handler trait carries a #[diagnostic::on_unimplemented] attribute with exactly that text. So the error already contains its own first step, it’s just easy to skip because it sits in the middle of the block.
How I reproduced them
I wanted every error in this post to be something I could paste, not something I remembered. So I built one throwaway crate with one binary per case: cN_broken.rs, the same file with the attribute added (cN_debug.rs, generated with sed so nothing else changes), and cN_fixed.rs. Each one is checked on its own with cargo check --bin <name>, so one broken handler can’t hide another.
[dependencies]
axum = { version = "=0.8.9", features = ["macros"] }
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
Versions, from the lockfile and the container: axum 0.8.9 (latest on crates.io today), axum-core 0.5.6, axum-macros 0.5.1, tokio 1.54.1, serde 1.0.229, rustc and cargo 1.100.0 in the official rust:1 Docker image, on an x86_64 Linux box. The debug_handler attribute needs the macros feature, which is off by default.
Compiler output changes between Rust releases. If your rustc is older or newer, the wording around the telltale line may differ, but the telltale lines come from axum’s macro and trait attributes, so they should be stable within 0.8.
Cause 1: a std Mutex guard held across .await
This is the one I’d bet most people hit first, because the code looks fine and works in a sync program:
async fn handler(axum::extract::State(counter): axum::extract::State<Arc<Mutex<u64>>>) -> String {
let mut n = counter.lock().unwrap();
*n += 1;
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
format!("hits: {n}")
}
Without the attribute you get the 24 lines above. With it, the first error is the useful one:
error: future cannot be sent between threads safely
--> src/bin/c1_send_debug.rs:4:1
|
4 | #[axum::debug_handler]
| ^^^^^^^^^^^^^^^^^^^^^^ future returned by `handler` is not `Send`
|
= help: within `impl Future<Output = String>`, the trait `Send` is not implemented for `std::sync::MutexGuard<'_, u64>`
note: future is not `Send` as this value is used across an await
--> src/bin/c1_send_debug.rs:8:62
|
6 | let mut n = counter.lock().unwrap();
| ----- has type `std::sync::MutexGuard<'_, u64>` which is not `Send`
7 | *n += 1;
8 | tokio::time::sleep(std::time::Duration::from_millis(10)).await;
| ^^^^^ await occurs here, with `mut n` maybe used later
[...]
The variable, its type, and the .await that crosses it. The fix I prefer is to keep the lock in a block so the guard is dropped before any .await:
let n = {
let mut n = counter.lock().unwrap();
*n += 1;
*n
}; // guard dropped here, before the .await
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
format!("hits: {n}")
Swapping in tokio::sync::Mutex and counter.lock().await also compiles (I checked it as a separate binary), and it’s the right tool when you really do need to hold the lock across an await. For a counter it’s overkill. An Rc held across .await fails the same way: with the attribute, the telltale is the trait `Send` is not implemented for `Rc<String>` with the same “used across an await” note.
Cause 2: the body extractor is not last
async fn handler(Json(user): Json<NewUser>, headers: HeaderMap) -> String {
format!("{} via {:?}", user.name, headers.get("user-agent"))
}
This one still produces the Handler error in axum 0.8. I half expected 0.8 to have relaxed it, so I checked: the extractor docs still require “the last extractor implements FromRequest and all others implement FromRequestParts”, and the compiler agrees. The attribute gives the clearest message of the whole set:
error: `Json<_>` consumes the request body and thus must be the last argument to the handler function
--> src/bin/c2_order_debug.rs:10:30
|
10 | async fn handler(Json(user): Json<NewUser>, headers: HeaderMap) -> String {
| ^^^^
Fix: async fn handler(headers: HeaderMap, Json(user): Json<NewUser>). The same rule covers String, Bytes, Form and anything else that reads the body. It also means you can’t have two of them.
Cause 3: a type that isn’t an extractor
The typical version is a CurrentUser you meant to extract from a header and haven’t wired up yet:
struct CurrentUser {
id: u64,
}
async fn handler(user: CurrentUser) -> String {
format!("user {}", user.id)
}
With the attribute:
error[E0277]: the trait bound `CurrentUser: FromRequest<(), axum_core::extract::private::ViaParts>` is not satisfied
--> src/bin/c3_notextractor_debug.rs:8:24
|
8 | async fn handler(user: CurrentUser) -> String {
| ^^^^^^^^^^^ unsatisfied trait bound
|
help: the trait `FromRequestParts<()>` is not implemented for `CurrentUser`
[...]
= note: Function argument is not a valid axum extractor.
See `https://docs.rs/axum/0.8/axum/extract/index.html` for details
The ViaParts in the first line looks scary but it’s just how axum routes a FromRequestParts type through FromRequest internally. The help: line under it is the readable one. The fix is to implement FromRequestParts (0.8 uses native async fn in traits, so there’s no #[async_trait] any more):
impl<S: Send + Sync> FromRequestParts<S> for CurrentUser {
type Rejection = StatusCode;
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
let id = parts
.headers
.get("x-user-id")
.and_then(|v| v.to_str().ok())
.and_then(|v| v.parse().ok())
.ok_or(StatusCode::UNAUTHORIZED)?;
Ok(CurrentUser { id })
}
}
If the type should come from the body instead, implement FromRequest and keep it last.
Cause 4: Json of a type without Deserialize
I added this one because it’s a variant of cause 3 that’s easy to misread. Json<T> is a perfectly good extractor, but only when T: DeserializeOwned:
struct NewUser {
name: String,
}
async fn handler(Json(user): Json<NewUser>) -> String {
user.name
}
Without the attribute it’s the same 22-line Handler error as everything else. With it, the output grows to 79 lines, the longest in this set, because rustc prints the serde error twice before the Handler one. The first line is enough:
error[E0277]: the trait bound `NewUser: serde::Deserialize<'de>` is not satisfied
--> src/bin/c6_deser_debug.rs:8:30
|
8 | async fn handler(Json(user): Json<NewUser>) -> String {
| ^^^^ unsatisfied trait bound
[...]
= note: for local types consider adding `#[derive(serde::Deserialize)]` to your `NewUser` type
Fix: #[derive(Deserialize)] on NewUser. The same applies to Query<T>, Path<T> and Form<T>.
Cause 5: an error type that can’t become a response
#[derive(Debug)]
enum AppError {
NotFound,
}
async fn handler() -> Result<String, AppError> {
Err(AppError::NotFound)
}
Result<T, E> implements IntoResponse only when both sides do. With the attribute:
error[E0277]: the trait bound `AppError: IntoResponse` is not satisfied
--> src/bin/c4_return_debug.rs:9:23
|
9 | async fn handler() -> Result<String, AppError> {
| ^^^^^^ unsatisfied trait bound
[...]
= note: required for `Result<String, AppError>` to implement `IntoResponse`
Fix:
impl IntoResponse for AppError {
fn into_response(self) -> Response {
match self {
AppError::NotFound => StatusCode::NOT_FOUND.into_response(),
}
}
}
This is the cause I’d expect to see most in a real service, because the error enum usually comes from somewhere else (a database layer, a domain module) and was written before anyone thought about HTTP. The opposite trap exists too: a handler that returns nothing compiles fine and always answers 200, which I wrote about in the health check that always said OK. How errors should travel up through a Rust program in the first place is the subject of my post on main returning Result.
Three rarer ones, where the attribute is less helpful
The last three are less common in real code, and debug_handler handles them with mixed success.
A plain fn. fn handler() -> &'static str fails with the usual Handler error. With the attribute, the first line is right (error[E0277]: `&str` is not a future), but rustc then suggests this:
help: alternatively, consider making `fn __axum_macros_check_handler_into_response_make_value` asynchronous
|
4 | fn handler() -> async &'static str {
| +++++
That isn’t valid Rust and the function it names doesn’t exist in your code, it’s generated by the macro. Ignore the suggestion and write async fn.
A reference argument. async fn handler(headers: &HeaderMap) compiles as a function, but no extractor produces a borrowed value. With the attribute you get error[E0637]: `&` without an explicit lifetime name cannot be used here and a suggestion to add for<'a>, which would not help either. The fix is headers: HeaderMap, by value. I’m not sure why the macro surfaces it as a lifetime error rather than a “not an extractor” error. It still points at the right &, which is what matters.
17 arguments. The limit is 16. The attribute says so directly and even proposes the workaround:
error: Handlers cannot take more than 16 arguments. Use `(a, b): (ExtractorA, ExtractorA)` to further nest extractors
Tuples of extractors are extractors themselves, so (_p, _q): (Version, HeaderMap) as the 16th argument compiled. If you have 17 extractors, though, the handler probably wants a custom extractor that groups them.
What the attribute changes, measured
I counted the lines of cargo check output for each repro, with and without the attribute. Errors are the error: / error[E...] diagnostics, not counting the final could not compile line.
| Repro | Lines without | Errors without | Lines with | Errors with |
|---|---|---|---|---|
std MutexGuard across .await | 24 | 1 | 46 | 2 |
Rc across .await | 22 | 1 | 43 | 2 |
Json not last | 22 | 1 | 28 | 2 |
| type not an extractor | 22 | 1 | 52 | 2 |
Json<T>, T not Deserialize | 22 | 1 | 79 | 3 |
error type not IntoResponse | 22 | 1 | 52 | 2 |
plain fn | 22 | 1 | 53 | 3 |
&HeaderMap argument | 22 | 1 | 34 | 2 |
| 17 arguments | 25 | 1 | 35 | 2 |
Two things stood out. Without the attribute, all nine outputs are the same error with the same shape and 22 to 25 lines, so the size of the output tells you nothing. With it, the output always gets longer, between 28 and 79 lines, because the original Handler error is still printed at the bottom. The attribute adds a diagnosis, it doesn’t replace the noise. So the habit to build is to read the first error, not the last one, which is the opposite of what the Handler line trains you to do.
One more thing I verified because the docs say it: debug_handler “has no effect when compiled with the release profile”. cargo check --release on the Json-not-last repro, attribute included, printed only the single Handler error. So the attribute costs nothing in a release build, and it also won’t help you there.
Not this error: State that doesn’t match with_state
Most lists of causes include a state mismatch, so I reproduced three versions of it: a handler taking State<AppState> with .with_state(Arc::new(state)), two handlers on one router with different state types, and a module function returning Router<AppState> whose handler takes State<Db>. None of them produced the Handler error. All three gave mismatched types, for example:
error[E0308]: mismatched types
--> src/bin/c5c_modstate_broken.rs:17:32
|
17 | Router::new().route("/db", get(ping_db))
| ----- ^^^^^^^^^^^^ expected `MethodRouter<AppState>`, found `MethodRouter<Db>`
That’s a better error already, and plain #[axum::debug_handler] doesn’t change it: with only a State<Db> argument the macro assumes the state is Db, so from its point of view nothing is wrong. Telling it the real state with #[axum::debug_handler(state = AppState)] adds the line that explains the fix:
error[E0277]: the trait bound `Db: FromRef<AppState>` is not satisfied
#[derive(Clone, FromRef)] struct AppState { db: Db } makes State<Db> work inside a Router<AppState>, and the module version compiled after that. Forgetting with_state entirely is different again: it fails at axum::serve with a 68-line error about Router<AppState> not implementing Service. If you’re structuring routers per module, the shape in the liveness and readiness post is the one I use, and I hit the double with_state version of this mismatch there.
Verdict
I’d stop treating debug_handler as a tool you reach for after the error appears. Put it on every handler while you write it. It’s free in release builds, it only needs the macros feature, and it turns the one error axum can’t explain into eight that it can, as long as you read from the top. The two cases where it gave a misleading suggestion (async &'static str, for<'a>) still pointed at the right line, which is more than the bare error ever does.
Once the handler compiles, the next things that bite in an axum service are runtime ones, like shutting down cleanly on SIGTERM without dropping the request in progress.