Sub topic 12
When to reach for the async_trait crate
This chapter assumes you have read the earlier chapters on async fn in traits, Send bounds on trait method futures, and boxed futures for trait objects. You should be comfortable with Pin<Box<dyn Future>> and with the difference between static dispatch (generics) and dynamic dispatch (dyn Trait).
Native async fn in traits has been stable since Rust 1.75. Before that, the async_trait crate was the standard way to write async trait methods, and it is still widely used. This chapter explains what the crate does, which problems it still solves, and when native syntax is the better choice.
What the crate does
async_trait is an attribute macro. It rewrites each async fn in a trait, and in its impls, into an ordinary method that returns a boxed future:
// What you write
#[async_trait]
trait Handler {
async fn handle(&self, req: &str) -> String;
}
// Roughly what the macro generates
trait Handler {
fn handle<'a>(&'a self, req: &'a str)
-> Pin<Box<dyn Future<Output = String> + Send + 'a>>;
}The generated signature is the same hand-written pattern from the previous chapter. The macro writes it for you, adds the lifetimes, and wraps each method body in Box::pin(async move { ... }).
The generated return type is a plain Pin<Box<dyn Future + Send>>. That type is dyn compatible, which is why the crate makes dyn Trait work.
Setting up the crate
Add the dependency. The example below also uses Tokio as the runtime.
[dependencies]
async-trait = "0.1"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }A trait object that works
This program stores different handlers in one Vec<Box<dyn Handler>>. A trait that uses native async fn cannot do this.
use async_trait::async_trait;
#[async_trait]
trait Handler: Send + Sync {
async fn handle(&self, req: &str) -> String;
}
struct Echo;
struct Shout;
#[async_trait]
impl Handler for Echo {
async fn handle(&self, req: &str) -> String {
req.to_string()
}
}
#[async_trait]
impl Handler for Shout {
async fn handle(&self, req: &str) -> String {
req.to_uppercase()
}
}
#[tokio::main]
async fn main() {
let handlers: Vec<Box<dyn Handler>> = vec![Box::new(Echo), Box::new(Shout)];
for h in &handlers {
println!("{}", h.handle("hello").await);
}
}Both the trait and every impl need the #[async_trait] attribute. If you put it on only one side, the signatures no longer match and the compiler reports a mismatch.
The trade-offs
One heap allocation per call
Every call to an async_trait method allocates a Box for the future. Native async fn in a trait does not, because the future is a concrete type known at compile time and can live on the caller's stack.
For code that does network or disk I/O, this cost is usually tiny compared with the operation itself. It matters more in hot paths, such as a method called millions of times per second that returns almost immediately.
Dynamic dispatch is the real reason
Boxing is not extra cost you pay for no benefit. With dyn Trait, the caller does not know the concrete future type, so something has to erase it. A box is the usual way. Hand-written boxed futures pay the same allocation.
`Send` is the default
By default the macro adds + Send to the boxed future. This matches what multithreaded executors such as Tokio's default runtime require when you tokio::spawn. It has two consequences:
- Every implementation's future must be
Send. Holding anRcor astd::sync::MutexGuardacross an.awaitinside the method is a compile error. - For default method bodies that use
&self, the trait needsSelf: Sync. This is why the example declarestrait Handler: Send + Sync.
Opting out with `?Send`
On a single-threaded runtime you can drop the Send requirement:
use async_trait::async_trait;
use std::cell::Cell;
use std::rc::Rc;
#[async_trait(?Send)]
trait Counter {
async fn bump(&self) -> u32;
}
struct Local(Rc<Cell<u32>>);
#[async_trait(?Send)]
impl Counter for Local {
async fn bump(&self) -> u32 {
let n = self.0.get() + 1;
self.0.set(n);
n
}
}
#[tokio::main(flavor = "current_thread")]
async fn main() {
let c = Local(Rc::new(Cell::new(0)));
c.bump().await;
println!("{}", c.bump().await);
}This program prints 2. With ?Send, the returned futures are not Send, so you cannot pass them to tokio::spawn. Use tokio::task::spawn_local inside a LocalSet instead. For this example, add the rt feature to Tokio (rt-multi-thread already includes it).
Where native async fn in traits falls short
The crate is useful today because native async fn in traits has gaps. These are the ones that matter in practice.
| Need | Native `async fn` in trait | `async_trait` |
|---|---|---|
| Generic static dispatch (`T: Trait`) | Works, no allocation | Works, allocates per call |
| `dyn Trait` | Not dyn compatible | Works |
| `Send` guarantee on futures | Must be written by hand with `impl Future + Send` | Default |
| Callers need `Send` without changing the trait | Not available on a plain `async fn` | Default |
| Older compilers (before 1.75) | Not available | Works |
Dyn compatibility
A trait with a native async fn cannot be turned into &dyn Trait or Box<dyn Trait>. The returned future is an unnamed type that differs for every impl, so the vtable has no single return type to describe. Plugin systems, middleware stacks, and handler registries that store mixed implementations in one collection all hit this limit.
Send on public traits
For a public trait, a plain async fn leaves callers unable to require that its future is Send. Generic code that calls store.get(key).await inside tokio::spawn fails to compile unless the trait promises Send. The two native options are the fn ... -> impl Future<Output = T> + Send form from the earlier chapter, or a helper such as the trait_variant crate, which generates a Send variant of your trait from a single definition. async_trait gives you the Send promise by default, with no change to the syntax.
Other ecosystem tools
async_trait is not the only option when you want dyn with less manual work.
trait_variantgenerates a second trait (for example one whose futures areSend) from your nativeasync fntrait. It keeps static dispatch and does not box. It does not make the trait dyn compatible.dynosaurgenerates a dyn-compatible wrapper type for a trait that uses nativeasync fn. You keep native syntax for generic code and pay for boxing only where you use the wrapper. Check its documentation for the exact attribute syntax and its current limits before relying on it.
Both are younger than async_trait, and their APIs may change more often. Pin versions and read the changelog.
A decision procedure
Use these rules in order:
- If the trait is private to your crate and only used with generics, write native
async fn. You get zero allocation and no dependency. - If the trait is public and generic callers will spawn its futures, declare the method as
-> impl Future<Output = T> + Sendor usetrait_variant. - If you need
dyn Trait, pickasync_traitfor the least effort, or hand-writtenPin<Box<dyn Future>>if you want no macro in your public API. - If you must support compilers older than 1.75, use
async_trait. - If a profiler shows the box allocation is a real cost on a hot path and you do not need
dyn, switch that trait to native syntax.
Common mistakes
- Forgetting the attribute on the impl. The trait compiles, then every impl fails with a lifetime or signature error that mentions
'life0or'async_trait. - Holding a non-
Sendvalue across.await. The error points at the whole future, not at the offending line. Look forRc,RefCellborrows, or astd::sync::MutexGuardthat is still alive at an await point. Either drop the value before awaiting or switch to#[async_trait(?Send)]. - Adding the macro to code that never needed it. On a trait used only through generics, the macro adds an allocation and a dependency for no gain.
- Expecting
async_traitto fixSendproblems in a generic function. The macro makes the trait's own futuresSend. A generic function that awaits them isSendonly if its other captured values are too.
Exercise
A crate defines trait Plugin { async fn run(&self, input: &str) -> String; } using native async fn, and the application wants Vec<Box<dyn Plugin>> holding several plugin types. The compiler rejects dyn Plugin. Name two ways to fix this and one cost of the simplest one.
Show answer
Fix 1: add #[async_trait] to the trait and to every impl, so run returns Pin<Box<dyn Future + Send>>, which is dyn compatible. Fix 2: write the method by hand as fn run<'a>(&'a self, input: &'a str) -> Pin<Box<dyn Future<Output = String> + Send + 'a>> and use Box::pin(async move { ... }) in each impl. The cost of the macro approach is one heap allocation for the future on every call, plus the default Send requirement on each implementation's future.
Exercise
You mark a trait with #[async_trait] and one implementation holds an Rc<String> across an .await. The compiler says the future cannot be sent between threads safely. Give two fixes and say when each is appropriate.
Show answer
Fix 1: stop holding the Rc across the await, for example by cloning the data you need into a local before the await, or replace Rc with Arc. This is right when the code runs on a multithreaded runtime. Fix 2: change both the trait and the impl to #[async_trait(?Send)]. This is right when everything runs on a single thread, such as a current-thread Tokio runtime with LocalSet. The futures are then no longer Send, so they cannot go to tokio::spawn.
Exercise
A public trait is used only with generics, T: Store, in a service that calls tokio::spawn on futures that call store.get(key).await. Should you use async_trait? Justify your answer.
Show answer
Probably not. There is no need for dyn, so native async fn avoids the per-call allocation. The requirement is that the futures be Send. Declare get as fn get(&self, key: &str) -> impl Future<Output = Option<String>> + Send (or use trait_variant) so the guarantee is part of the trait. Use async_trait only if you must support compilers older than 1.75 or later need dyn Store.