Rust tokio 1.38 `spawn` error: future cannot be sent between threads safely (E0277)
I hit this on a Tuesday after adding a metrics aggregator to a small internal service. The service builds on an Ubuntu 22.04 GitHub Actions runner and runs on a Debian 12 VM. Local build fine, cargo test fine, and then cargo run --release on the VM started throwing the same error as soon as a background task was spawned.
## The error, verbatim
error[E0277]: Rc<RefCell<HashMap<String, u64>>> cannot be sent between threads safely
--> src/metrics.rs:31:5
|
31 | tokio::spawn(async move {
| ^^^^^^^^^^^^^ Rc<RefCell<HashMap<String, u64>>> cannot be sent between threads safely
|
= help: within metrics::{closure#0}, the trait Send is not implemented for Rc<RefCell<HashMap<String, u64>>>
= note: required because it appears within the type [closure@src/metrics.rs:31:22: 38:10]
= note: required for the cast from {async block@src/metrics.rs:31:22: 38:10} to dyn Future<Output = ()> + Send
I was on tokio = { version = "1.38.0", features = ["full"] } with Rust 1.79.0. Nothing exotic about the setup.
## What it's actually saying
tokio::spawn hands the future to a multi-thread runtime, which may move it to any worker thread. That requires Send. My future captured an Rc<RefCell<_>> because I'd written a shared counter without thinking about threads. Rc keeps everything on one thread by design, so the compiler is doing exactly its job here.
I briefly considered unsafe impl Send. Don't do that. I didn't, but I thought about it for a solid minute, which is long enough to mention.
We run the same binary with #[tokio::main(flavor = "current_thread")] for one CLI subcommand, and there the Rc version compiled fine. That difference confused me for a while. A current-thread runtime never moves the future between workers, so it doesn't need Send. Worth keeping that flavor around if you've got shared state that's awkward to make thread-safe, as long as you're honest about what it means.
## The fix and the one I kept
The minimal change is Arc<Mutex<T>>:
rust
let counts = Arc::new(Mutex::new(HashMap::<String, u64>::new()));
let c = counts.clone();
tokio::spawn(async move {
let mut guard = c.lock().unwrap();
*guard.entry("requests".to_string()).or_insert(0) += 1;
});
That compiles and runs. For the hot path I later moved to tokio::sync::Mutex, then to Arc<AtomicU64> per metric, because holding a std mutex across anything async is a smell. Aggregation happens once at flush time.
## The second error, right after I thought I was done
Then this landed:
error: future is not Send
--> src/metrics.rs:44:18
|
44 | let guard = state.lock().unwrap();
| ^^^^^^^^^^^^^^^^^^^^ this value is used across an await
45 | flush(&guard).await;
| ^^^^^^^^^^^^^^^^^^ await occurs here
|
= note: std::sync::MutexGuard is not Send
A std::sync::MutexGuard held across .await makes the whole future non-Send. I scoped the guard so it drops before the await:
rust
let snapshot = {
let guard = state.lock().unwrap();
guard.clone()
};
flush(&snapshot).await;
Obvious in hindsight. The diagnostic is genuinely good, it names the exact await that crosses the boundary; I just had to read past the first line instead of sighing at it.
Three weeks in and no more spawn errors. If there's a better pattern for per-metric counters than a pile of atomics, I haven't found one.