skip to content

For a latency-sensitive Rust service, how do you choose between a work-stealing multi-threaded executor requiring `Send` futures and thread-per-core local executors accepting `!Send` ones?

level: principalimportance: should knowfreq 30%

answer

  1. who pays for the Send bound
  2. load balancing versus locality
  3. Arc and Mutex or Rc and RefCell
  4. skewed connections and tail latency
  5. ecosystem assumes Send + 'static

basics

~20 s

Default to a work-stealing executor with Send futures: it balances uneven load and fits most libraries. Choose thread-per-core local executors only when measurements show cross-thread synchronisation dominates and the work can be sharded evenly, accepting Rc-based state and manual balancing.

solid answer

~50 s

The choice decides who pays for the `Send` bound. A **work-stealing multi-threaded executor**, Tokio's default being the common one, lets idle workers take queued tasks from busy ones, so a few heavy connections do not stall the rest, but every spawned future must be `Send + 'static`: shared state goes behind `Arc` and locks, and handlers must never hold a `MutexGuard` or `Rc` across an `.await`. **Thread-per-core** designs pin each connection to one thread running a local executor, such as `smol::LocalExecutor`, which accepts `!Send` futures, so state can be `Rc<RefCell<..>>` with no atomics and better cache locality; the price is that a hot shard cannot be helped by idle cores and many libraries assume `Send` tasks. I would start with work stealing and switch only for a measured, evenly shardable workload, such as per-partition state machines, with p99 latency under skewed load as the deciding test.

code

rust · 24 lines
rust
use std::cell::RefCell;
use std::rc::Rc;

async fn flush() { smol::future::yield_now().await; }

fn main() {
    let ex = smol::LocalExecutor::new();
    let log = Rc::new(RefCell::new(Vec::new()));
    let tasks: Vec<_> = (0..3)
        .map(|id| {
            let log = Rc::clone(&log);
            // Rc and RefCell held across .await: !Send, fine on a local executor
            ex.spawn(async move {
                log.borrow_mut().push(format!("joined {id}"));
                flush().await;
                log.borrow_mut().push(format!("left {id}"));
            })
        })
        .collect();
    smol::block_on(ex.run(async {
        for t in tasks { t.await; }
    }));
    println!("{:?}", log.borrow());
}

go deeper

for a junior

Know that some executors move tasks between threads and need Send futures, while local executors keep a task on one thread and accept Rc and RefCell.

for a middle

Explain how the executor choice changes the code: Arc and locks versus Rc and RefCell, and which spawn functions demand Send + 'static.

for a senior

Diagnose when a design is fighting its executor: Send errors from refactors under work stealing, or one hot core under thread-per-core, and propose the matching fix.

for a principal

Own the default and its exceptions: weigh load balancing and library compatibility against synchronisation cost, insist on skewed-load p99 measurements, and document when a team may run !Send work on local executors.

## What the decision is really about Every async Rust service eventually decides how tasks map onto threads, and in Rust that decision surfaces in the type system. A **multi-threaded executor** that moves tasks between workers needs every spawned future to be `Send + 'static`. A **local executor**, one per thread with no task migration, accepts `!Send` futures. Choosing between them is choosing which constraint the whole codebase lives with. Work stealing itself, idle workers taking queued tasks from busy ones, is a general scheduling idea; what is specific to Rust is how it shapes the code you write. ## Option one: work-stealing, multi-threaded How it works for you: - **Load balancing is automatic.** A worker that drains its queue steals from others, so a burst on a few connections spreads across cores without design work. - **The ecosystem expects it.** Most async libraries are written and tested against a multi-threaded runtime, Tokio's default scheduler being the usual one, and their APIs often take or return `Send + 'static` futures. - **One mental model.** Any handler can be spawned anywhere. What it costs: - **The `Send` discipline everywhere.** Shared state is `Arc<Mutex<..>>`, `Arc<RwLock<..>>` or atomics; no `Rc`, no `RefCell`, and no std `MutexGuard` across an `.await`. Every refactor can break a build far from the change. - **Synchronisation and cache traffic.** Atomic reference counts, contended locks and tasks hopping cores add latency that shows up in the tail. ## Option two: thread-per-core, local executors How it works for you: - **`!Send` is allowed.** A local executor such as `smol::LocalExecutor` has a spawn with no `Send` bound, so per-thread state can be `Rc<RefCell<..>>` and tasks can hold it across awaits. - **No cross-thread sharing on the hot path.** Each core owns its connections and data, so there are no atomics or lock contention between shards, and caches stay warm. - **Predictable latency** when the load is evenly spread, because no task ever waits on another core. What it costs: - **You balance the load.** Connections or partitions are assigned to cores up front; a hot key or a long-lived heavy client saturates one core while others sit idle, and no executor steals the work. - **Library friction.** A crate whose API requires `Send` futures cannot be handed your `!Send` ones, so some code must still be written `Send`, or kept off the local executors. - **Cross-shard work needs messages,** usually channels between threads, which reintroduces `Send` at those boundaries. ## Comparing them | concern | work-stealing, multi-threaded | thread-per-core, local | |---|---|---| | bound on spawned futures | `Send + 'static` | `'static` or a scope, no `Send` | | shared state | `Arc`, locks, atomics | `Rc`, `RefCell`, per-core data | | uneven or bursty load | absorbed by stealing | lands on one core | | tail latency under even load | synchronisation adds jitter | usually lower | | library compatibility | broad | narrower | ## How I would decide 1. **Start from the workload's shape.** Many independent, uneven requests favour work stealing; state that partitions cleanly by key, with even traffic per partition, favours thread-per-core. 2. **Measure before switching.** Profile a realistic load with skew, and compare p99 latency and CPU per request; adopt thread-per-core only if synchronisation cost is a measured, dominant share. 3. **Check the dependencies.** List the crates on the hot path and whether they require `Send` futures. 4. **Consider a hybrid.** Keep a multi-threaded runtime for most handlers and run a local executor on dedicated threads for the `!Send` state, talking to it through channels. 5. **Write the rule down.** Whichever wins, make the bound a team convention, clippy's `future_not_send` lint (nursery, allowed by default) on handler code if everything must be `Send`, and a documented exception path if not. There is no universally right answer; the strong answer names the costs on both sides and says what evidence would change the decision. A weak answer picks one model on reputation, claims it is simply faster, and ignores that the choice is written into every handler's types: moving from local executors to work stealing later means making every spawned future `Send`, which can touch most of the codebase.

  • If you choose work stealing, what team rules keep handlers spawnable as the code grows?
    Take owned or `Arc` arguments in handlers, never hold a std `MutexGuard`, `Rc` or `RefCell` borrow across an `.await`, keep clippy's `await_holding_lock` and `await_holding_refcell_ref` on, and add a `require_send` test for public async functions so a lost `Send` fails in the crate that caused it.
  • In a thread-per-core design, how do you handle a request that needs data owned by another core?
    Send a message to the owning core over a channel and await the reply, instead of sharing the data. The message and the reply must be `Send`, so `Send` reappears at shard boundaries; keeping those boundaries few and coarse is what preserves the design's advantage.

  • Thread-per-core is always faster because it avoids atomics.
  • Work stealing removes the need to think about Send.
  • A local executor lets you use any library unchanged.
  • Choosing the executor is a detail you can change later for free.
  • Uneven load does not matter if each core has its own executor.