Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Rust: Future Cannot Be Sent Between Threads Safely in Tokio

spawn needs Send + 'static, and any non-Send value alive across an await breaks it. Shorten the guard, switch the lock, or move the work to a LocalSet.

~4 min readRust
#Rust#Tokio#Async#Concurrency
3D illustration of a future cube blocked from crossing a gap between two thread rails with a red cross

Introduction & Quick Summary

Symptom. tokio::spawn — or an axum handler, an actix worker, tokio::select!, or a JoinHandle awaited in another task — refuses to compile:

code
error: future cannot be sent between threads safely --> src/handler.rs:27:5 note: future is not `Send` as this value is used across an await = help: consider using `cargo check` … `MutexGuard<'_, …>` is not `Send`

The future is otherwise correct and compiles fine when run with block_on, so the error reads as a Tokio problem rather than a type problem.

Cause. tokio::spawn requires Future + Send + 'static because the runtime may move the task between worker threads at any .await. A future is Send only if every value alive across an await point is Send. std::sync::MutexGuard, Rc, RefCell borrows, parking_lot guards, Box<dyn Error> without + Send, and references to non-Sync types all break that, even when the guard is only used briefly.

Fix. Shrink the non-Send value's lifetime so it is dropped before the .await — a small block { … } or an explicit drop(guard). When the value must be held across the await, use the async-aware equivalent: tokio::sync::Mutex instead of std::sync::Mutex, Arc instead of Rc, Box<dyn Error + Send + Sync> instead of Box<dyn Error>. For work that is genuinely not Send, use spawn_blocking or a LocalSet instead of forcing the bound.

Core Mechanics, Signatures & Reproducible Setup

The minimal failing program, using an Arc<std::sync::Mutex<..>> because that is the shape most people reach for first:

rust
use std::sync::{Arc, Mutex}; use tokio::time::{sleep, Duration}; async fn tick(counter: Arc<Mutex<u64>>) { let mut guard = counter.lock().unwrap(); *guard += 1; sleep(Duration::from_millis(10)).await; // guard alive across await: future is !Send println!("{guard}"); } #[tokio::main] async fn main() { let counter = Arc::new(Mutex::new(0)); tokio::spawn(tick(counter)); // error: future cannot be sent between threads safely }

Two correct fixes. The first keeps std::sync::Mutex and drops the guard early, which is the fastest option because the critical section does not await:

rust
async fn tick(counter: Arc<Mutex<u64>>) { { let mut guard = counter.lock().unwrap(); *guard += 1; } // dropped before the await sleep(Duration::from_millis(10)).await; }

The second keeps the guard across the await and changes the lock, because a tokio::sync::MutexGuard is Send:

rust
use tokio::sync::Mutex; async fn tick(counter: Arc<Mutex<u64>>) { let mut guard = counter.lock().await; // async lock *guard += 1; sleep(Duration::from_millis(10)).await; // safe: guard is Send }

Read the compiler note rather than the first line. The note: names the exact type and the line where it is held across an await, and the full error with cargo check --message-format=json gives the same note as structured data, which is easy to grep for the offending type:

bash
cargo check --message-format=short 2>&1 | grep -A2 "not \`Send\`"

Key Comparison Table

TypeSend?Held across awaitReplacement
std::sync::MutexGuardNoCompile errortokio::sync::Mutex or drop early
parking_lot::MutexGuardNoCompile errortokio::sync::Mutex
Rc<T> / RefCell<T>NoCompile errorArc<T> / tokio::sync::RwLock
Arc<Mutex<..>>YesFine—
Box<dyn Error>NoCompile error in Send futureBox<dyn Error + Send + Sync>
&dyn TraitOnly if Trait: SyncCompile errorArc<dyn Trait + Send + Sync>
tokio::sync::MutexGuardYesFine—
ThreadRngYes (since rand 0.8 for thread_rng)FineKeep out of long awaits
Compiler noteReal causeFastest fix
MutexGuard<..> is not Sendstd lock held over .awaitBlock scope, or tokio::sync::Mutex
Rc<..> is not SendSingle-threaded refcount in an async fnArc
RefCell<..> is not SyncInterior mutability borrowed across awaitRwLock, or restructure
dyn Error is not SendDefault trait object lacks Send+ Send + Sync
&T is not Send with T: !SyncBorrow of a shared non-Sync valueOwn it, or Mutex<T>
*mut T is not SendRaw pointer in scopeWrap in a safe abstraction
cannot be sent between threads on impl FutureTrait method without Send bound-> impl Future + Send

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. A select! that borrows a guard in two branches

tokio::select! keeps every branch's future alive until one completes, so a guard created in one branch and used in another extends across the await of the select.

rust
// broken: guard from the first branch is alive while select polls the second loop { let guard = state.lock().unwrap(); tokio::select! { msg = rx.recv() => handle(&mut *guard, msg), _ = shutdown.cancelled() => break, } }

Take the lock inside each branch, after the await resolves:

rust
loop { tokio::select! { msg = rx.recv() => { let mut guard = state.lock().unwrap(); handle(&mut guard, msg); } _ = shutdown.cancelled() => break, } }

2. Box<dyn Error> in an axum handler

The handler's return type must be Send, and Box<dyn Error> is not. The error alias is the fix, and it propagates through ? without changes at call sites:

rust
type BoxError = Box<dyn std::error::Error + Send + Sync>; async fn handler() -> Result<String, BoxError> { let body = fetch().await?; Ok(body) }

anyhow::Error is already Send + Sync, which is one reason it is popular in application code; thiserror-derived enums are Send when their fields are.

3. Guards that are dropped "obviously" but not really

A guard bound with let _ = lock.lock() is dropped at the end of the statement, but let _guard = … lives until the end of the scope. The underscore-prefixed binding is the trap:

rust
let _guard = state.lock().unwrap(); // alive until end of function do_async().await; // error: guard held across await

Use an explicit block, or drop(_guard) before the await, and prefer that over renaming.

4. Genuinely !Send work: LocalSet, not a fight

A library that builds Rc graphs or FFI handles cannot be made Send. tokio::task::LocalSet runs such tasks on the current thread, where the Send bound does not apply:

rust
let local = tokio::task::LocalSet::new(); local.run_until(async { tokio::task::spawn_local(async { let rc = std::rc::Rc::new(1); do_work(rc).await; }).await.unwrap(); }).await;

spawn_blocking is the other escape hatch: it runs a closure on the blocking pool and only requires the result to be Send, so a non-Send intermediate is fine inside.

5. Traits with async methods and the Send bound

async fn in traits (stable since Rust 1.75) produces a future whose Send-ness is not part of the signature, so a generic caller requiring Send cannot prove it. State it:

rust
trait Store { fn get(&self, key: &str) -> impl std::future::Future<Output = Option<String>> + Send; } // or, on stable before RPITIT bounds were convenient: #[async_trait::async_trait] trait Store: Send + Sync { async fn get(&self, key: &str) -> Option<String>; // macro adds + Send }

#[async_trait] allocates a Box<dyn Future + Send> per call; it is the compatibility path, not the fast one.

6. The 'static half of the bound

The other half of spawn's requirement is 'static, and it fails with a different error that often appears together with the Send note: borrowing &self inside a spawned task. Clone what you need:

rust
let store = self.store.clone(); // Arc clone tokio::spawn(async move { store.put("k", "v").await });

tokio::task::spawn cannot borrow the stack; JoinSet and spawn_blocking have the same rule.

Common Compilation/Runtime Mistakes & Version Gotchas

  • Reaching for tokio::sync::Mutex everywhere. It is slower than std::sync::Mutex and adds an await point; use it only when the guard must live across an await. Most critical sections should be shortened instead.
  • Rust 2024 capture rules. Edition 2024 changes which values an async block captures (RFC 2394 precise capturing), so code that compiled on 2021 can start holding a non-Send value across an await. If a migration suddenly produces E0277, check the captures before changing types.
  • &mut self across await in a spawned task. A mutable borrow is Send only when the referent is, and &mut never satisfies 'static; restructure to own the state.
  • #[allow] does not apply. Send is a trait bound, not a lint; there is no suppression, only a redesign.
  • async-trait and default methods. The macro's generated future is Send only if the trait is, so add Send + Sync supertraits when spawned.
  • block_on hides the problem. futures::executor::block_on accepts a non-Send future, so a unit test passes while the same handler in tokio::spawn fails to compile. Test with the runtime you deploy on.
  • spawn_blocking inside a hot loop. Each call moves to a thread; thousands per second saturate the blocking pool (512 by default) and queue. Batch the work instead.

Related tools. Filter the compiler's JSON diagnostics for the exact not Send note with the regex tester, compare Cargo.lock before and after a dependency bump that changed a guard type with the text diff, and pretty-print tracing output captured as JSON lines with the JSON formatter.

Try matching browser tools

All tools

Small utilities that fit Rust work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Rust guides

More in Rust

All Rust guides

The guides filed next to this one in Rust, in library order.