Sub topic 12
When to reach for the async_trait crate
This chapter assumes you know how async fn in traits works, why it is not dyn compatible, and how to write a boxed future by hand. It covers when the async_trait crate is worth adding.
What the crate does
async_trait is an attribute macro. It rewrites each async fn in a trait and its impls into a normal method that returns Pin<Box<dyn Future + Send + '_>>. This is the same boxed-future pattern you wrote by hand in the previous chapter. The macro writes the lifetimes and the Box::pin(async move { ... }) for you.
Add it to Cargo.toml:
[dependencies]
async-trait = "0.1"Then put #[async_trait] on both the trait and every impl:
use async_trait::async_trait;
#[async_trait]
trait Handler: Send + Sync {
async fn handle(&self, req: &str) -> String;
}
struct Echo;
#[async_trait]
impl Handler for Echo {
async fn handle(&self, req: &str) -> String {
req.to_string()
}
}
async fn run_all(handlers: Vec<Box<dyn Handler>>) {
for h in handlers {
println!("{}", h.handle("ping").await);
}
}Box<dyn Handler> compiles here. A trait with plain async fn methods would be rejected in this position.
What you get
- Dyn compatibility. You can store different implementations in one
Vec<Box<dyn Handler>>or pass&dyn Handleraround. - Send by default. The returned future is
Send, so it works with multithreaded executors such as Tokio's. If your futures hold non-Senddata likeRc, write#[async_trait(?Send)]on the trait and its impls. - Older compilers. The crate works on Rust versions before 1.75, which matters if you have a minimum supported Rust version (MSRV) below that.
What it costs
- One heap allocation per call. Each call boxes its future. For a handler that does network I/O, this is noise. In a hot loop that calls a tiny async method millions of times, it can show up in a profile.
- Dynamic dispatch of the future. Callers cannot inline through the
Pin<Box<dyn Future>>. - Worse error messages. Errors point into macro-generated code, and lifetime errors can be hard to read.
- Extra dependency and a macro in every impl. You must put the attribute on every impl. A missing attribute gives an error about a mismatched signature.
When to use it
Reach for async_trait when at least one of these is true:
- You need
dyn Trait, for example a plugin list, a middleware stack, or a handler registry chosen at runtime. - The trait has several async methods, so writing each
Pin<Box<...>>signature by hand is tedious and easy to get wrong. - Your MSRV is older than Rust 1.75.
Skip it when the code is generic over a concrete type (fn run<S: Storage>(s: &S)). Native async fn in traits needs no allocation there. If you only need a Send guarantee, use the impl Future + Send form from the earlier chapter.
A mixed approach
You can keep a native async fn trait for generic code and add a small dyn-compatible wrapper only at the boundary where you need trait objects. This keeps the allocation cost out of the code that does not need it. The cost is that you maintain two traits.
Exercise
You are writing a plugin system. Plugins are loaded at runtime and stored in a Vec<Box<dyn Plugin>>, and each plugin has an async fn run(&self). Which approach do you use, and what does each call cost?
Show answer
Use #[async_trait] on the trait and each impl, or write run by hand to return Pin<Box<dyn Future<Output = ()> + Send + '_>>. Plain async fn in the trait would make dyn Plugin impossible. Either option allocates one box per call to run, which is negligible for plugins that do real work.