Sharded spawn_blocking queue can leave later shards waiting under load
I've been testing the opt-in sharded spawn_blocking queue from #8067, and noticed that tasks in later shards can wait a lot longer once the blocking pool fills up. Throughput looks about the same, but the wait times don't.
Why this seems to happen
In normal builds, producers pick one of 16 shards at random. A blocking worker starts each scan at worker_thread_id % 16, takes the first task it finds, runs it, then starts again at that same shard. So with one worker, if shard 0 keeps getting work, the worker can keep taking it without reaching shard 15. I don't see anything in the busy loop that limits how long this can go on.
What I observed
On Tokio e133b6fec055d5cab447c06f953d330ce34f1517, I submitted 4,400 tasks over about two seconds. Each did about 500 µs of CPU work, with max_blocking_threads(1), so the arrival rate was roughly 110% of what that worker could handle. I measured from just before spawn_blocking to the start of the closure. Four release runs of the small reproducer below gave:
| Queue | p99 queue wait across runs | Throughput across runs |
|---|---|---|
| Default | 200–218 ms | 1,982–1,998 jobs/s |
| Sharded | 1,732–1,805 ms | 1,995–1,998 jobs/s |
I also checked a few other cases:
- The pattern also showed up with 2 and 4 blocking workers. At the same nominal 110% load, median p99 wait over four runs was 205/242 ms with the default queue and 1,767/1,766 ms with the sharded queue. Throughput was similar.
- I traced the actual random shard choices in one run. Counts were fairly even, 258–296 tasks per shard, but shard 0's median wait was 0.242 ms and shard 15's was 1,259 ms. At two seconds, shard 15 still had all 277 of its tasks pending; its oldest had waited about 1,993 ms. This shard-level check used research-only tracing, so the public reproducer below doesn't print it.
- In a controlled test, I queued one early task on shard 15, then 64 on shard 0. The early task ran first with the default queue and last with the sharded queue. Both batches finished in about 32.8 ms. Controlled shard placement also needed research-only instrumentation.
The reproducer below uses unmodified Tokio and its usual random shard choice. I also saw the same direction with 16–64 producers, so this doesn't seem to depend on a single producer or the controlled test.
Small public-API reproducerFor Cargo.toml, use tokio = { git = "https://github.com/tokio-rs/tokio", rev = "e133b6fec055d5cab447c06f953d330ce34f1517", features = ["rt"] }. Run this main.rs in release mode in separate processes, once with TOKIO_UNSTABLE_SHARDED_BLOCKING_QUEUE=0 and once with =1.
use std::hint::black_box;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
const JOBS: usize = 4_400;
const WORK: Duration = Duration::from_micros(500);
const ARRIVAL: Duration = Duration::from_nanos(454_545); // About 110% of one worker's capacity.
fn main() {
let rt = tokio::runtime::Builder::new_current_thread()
.max_blocking_threads(1)
.build()
.unwrap();
let waits = Arc::new((0..JOBS).map(|_| AtomicU64::new(0)).collect::<Vec<_>>());
let mut handles = Vec::with_capacity(JOBS);
let beginning = Instant::now();
for i in 0..JOBS {
let due = beginning + ARRIVAL.mul_f64(i as f64);
while Instant::now() < due {
std::hint::spin_loop();
}
let submitted = Instant::now();
let waits = Arc::clone(&waits);
handles.push(rt.spawn_blocking(move || {
waits[i].store(submitted.elapsed().as_nanos() as u64 + 1, Ordering::Relaxed);
let start = Instant::now();
while start.elapsed() < WORK {
black_box(1);
}
}));
}
rt.block_on(async {
for handle in handles {
handle.await.unwrap();
}
});
let mut sorted = waits.iter().map(|x| x.load(Ordering::Relaxed)).collect::<Vec<_>>();
assert!(sorted.iter().all(|&x| x > 0));
sorted.sort_unstable();
let p99 = sorted[(JOBS * 99).div_ceil(100) - 1];
let elapsed = beginning.elapsed().as_secs_f64();
println!(
"p99 queue wait: {} us; max: {} us; throughput: {:.0} jobs/s",
p99 / 1_000, sorted[JOBS - 1] / 1_000, JOBS as f64 / elapsed
);
}Notes
The sharded queue is still opt-in and experimental. No tasks were lost, and I know spawn_blocking doesn't promise global FIFO order. I'm reporting the wait-time difference, not an API correctness failure. Ordinary finite bursts had similar overall p99 in my tests, and at roughly 80% sustained load I didn't see a consistent gap. The big difference showed up around saturation or overload. These numbers are from one Windows machine with an AMD Ryzen 5 5600H; I haven't repeated them on Linux yet.
Is this wait-time spread expected for the sharded queue, or worth looking at before it becomes more widely used? Rotating the scan start or limiting how many tasks a worker takes from one shard might help, though I'd expect those to need benchmarking against the contention and locality gains from sharding.
Source: tokio-rs/tokio