As a Rust library lead publishing a `Storage` trait that third parties implement, used both generically and as `Box<dyn ...>` on multi-threaded executors, how would you shape its async methods?
answer
- who implements, who calls
- Send is a one-way door
- box only at the dyn boundary
- a breaking change to switch later
basics
~20 sDecide Send and dyn support up front; both are SemVer commitments. A common shape: methods returning impl Future + Send, plus a boxed dyn-compatible companion trait via a blanket impl; async-trait when simplicity or an old MSRV outweighs per-call allocation.
solid answer
~40 sI start from who implements and who calls. Multi-threaded callers need `Send` futures, which native `async fn` cannot promise, so the trait should say `fn get(&self, key: &str) -> impl Future<Output = Option<Vec<u8>>> + Send`, accepting that single-threaded `!Send` backends are excluded; `trait_variant::make` keeps a local variant for them. Dyn users need a boxed signature, so I add a `DynStorage` companion with a blanket impl, and only that path allocates. The async-trait crate is the simpler alternative when the allocation per call does not matter or the MSRV is below 1.75. Whatever I pick is hard to change: rustc's own lint notes a `Send` bound "cannot be relaxed without a breaking API change", and moving between async-trait and native signatures breaks implementors.
code
rust · 27 linesuse std::future::Future;
use std::sync::Arc;
#[trait_variant::make(Storage: Send)]
pub trait LocalStorage {
async fn get(&self, key: &str) -> Option<Vec<u8>>;
}
struct RamStore;
impl Storage for RamStore {
async fn get(&self, _key: &str) -> Option<Vec<u8>> { Some(vec![7]) }
}
fn spawn_on_pool<F: Future<Output = ()> + Send + 'static>(fut: F) {
futures::executor::block_on(fut);
}
fn warm<S: Storage + Sync + 'static>(store: Arc<S>) {
spawn_on_pool(async move {
println!("send variant: {:?}", store.get("k").await);
});
}
async fn local_use<S: LocalStorage>(s: &S) -> Option<Vec<u8>> { s.get("k").await }
fn main() {
warm(Arc::new(RamStore));
println!("local: {:?}", futures::executor::block_on(local_use(&RamStore)));
}go deeper
Recall that a public async trait must decide whether its futures are Send and whether it supports dyn Trait.
Compare native async fn, + Send desugaring, trait_variant and async-trait on Send, dyn use and allocation.
Map the storage scenario to a shape and explain which implementors and callers each option excludes or charges.
Own the SemVer consequences: adding or removing Send, or switching macro and native forms, is a major-version change, so decide it once and document it.
## The decision A library publishes `Storage` with `get` and `put`. Third parties write backends (in-memory, remote, embedded databases); applications call it generically in hot paths and also keep heterogeneous backends behind `Box<dyn ...>`; most applications run a multi-threaded, work-stealing executor. Rust 1.99 offers several shapes for the async methods, and none satisfies every constraint for free. This is a judgment call about API surface, cost and future compatibility. ## The options | Shape | Send futures for generic callers | `dyn` use | Allocation | `!Send` backends | |---|---|---|---|---| | Native `async fn` | no (and `async_fn_in_trait` warns) | no | none | allowed | | `fn ... -> impl Future<Output = T> + Send` | yes | no | none | excluded | | `#[trait_variant::make(Storage: Send)]` on `LocalStorage` | yes, via the variant | no | none | allowed, on the local trait | | `#[async_trait]` (async-trait crate) | yes, by default | yes | one box per call, every call | only with `?Send`, which drops the guarantee | | Send-bounded native trait plus a boxed `DynStorage` companion | yes | yes, through the companion | only on the dyn path | excluded from the main trait | ## The questions that decide it 1. **Do implementors need `!Send` state?** A backend wrapping a single-threaded client may hold an `Rc` across an `.await`. Requiring `+ Send` locks it out; `trait_variant` keeps a local trait for it, at the cost of two traits in the docs. 2. **How hot is the call?** The Async Book's guidance is that one heap allocation per call is insignificant for most applications but matters for a low-level API called millions of times a second. A storage `get` in a request path is usually fine; a per-message codec trait may not be. 3. **How many dyn users are there?** If dynamic dispatch is the main use, async-trait's single signature is simpler. If it is one plugin registry, isolate the box in a companion. 4. **What is the minimum supported Rust version?** Native async fn in traits needs 1.75; a library supporting older compilers has only async-trait. ## Why it is hard to change later - **Adding `Send`** to a published trait's futures breaks every implementor whose future is not `Send`. - **Removing `Send`** breaks every generic caller that spawned those futures; rustc's help text for `async_fn_in_trait` says a bound added this way "cannot be relaxed without a breaking API change". - **Switching between async-trait and native** changes every method's return type: `dyn Storage` users stop compiling, and impls still carrying `#[async_trait]` fail with E0195. Each of these is a major-version change under Cargo's SemVer rules. ## A defensible default For the scenario above, many leads would choose: - a `Storage` trait whose methods are written `fn ... -> impl Future<Output = T> + Send`, so implementors still write `async fn` and generic callers can spawn; - a `DynStorage` companion with `Pin<Box<dyn Future<Output = T> + Send + '_>>` methods and `impl<T: Storage> DynStorage for T`, so dyn users pay for the box and nobody else does; - `trait_variant` only if a real `!Send` backend is expected. A team that values one trait and one mental model over the allocation may reasonably choose async-trait instead, especially for a low-traffic plugin interface. Either way, write the choice into the crate's documentation, because it is the one part of the trait that cannot be revised quietly. ## Migrating an existing async-trait API When the crate already ships `#[async_trait]` and the allocation or the `Pin<Box<...>>` signatures have become a problem, the move is a planned major release rather than a quiet refactor: - introduce the native `Send`-bounded trait and the boxed companion in the new major version, keeping method names and argument types the same so implementors mostly delete the attribute; - tell implementors that `#[async_trait]` must come off their impls too, or they hit E0195; - point dyn users at the companion trait in the release notes, since `Box<dyn Storage>` becomes `Box<dyn DynStorage>`; - keep the old major version maintained for a while if downstream crates cannot move at once. The cost of this migration is the strongest argument for taking the decision carefully the first time.
- What exactly does `#[trait_variant::make(Storage: Send)]` generate from `trait LocalStorage`?It keeps `LocalStorage` as written and adds `trait Storage: Send` in which each `async fn` becomes `fn ... -> impl Future<Output = T> + Send`, plus a blanket impl so any type implementing `Storage` also implements `LocalStorage`. Ordinary methods are unchanged, and the generated trait is still not dyn-compatible.
- Would you ever ship native `async fn` with no `Send` bound in a public trait?Yes, when the trait is meant for single-threaded or thread-per-core executors, or when callers only ever await the futures in place and never spawn them. Then I would allow the `async_fn_in_trait` lint deliberately and document that the futures make no `Send` promise.
- Native async fn in a public trait is fine for multi-threaded callers.
- A Send bound on trait futures can be dropped later in a minor release.
- trait_variant solves both the Send problem and dyn compatibility.
- async-trait's allocation only affects callers that use dyn Storage.
- Switching from async-trait to native async fn is a patch-level change.