A Rust loop runs `while let Some(r) = set.next().await` over a `FuturesUnordered` and awaits slow work for each result; why do the set's other futures stall?
answer
- the set is not a task
- polled only through poll_next
- wake-ups wait for the next call
- move slow work into the futures
basics
~10 sA FuturesUnordered makes progress only while someone polls it. While the loop body awaits other work, nothing calls poll_next, so the remaining futures stay suspended at their current .await even after their wakers fire.
solid answer
~50 s`FuturesUnordered` is a stream that owns a set of futures; it is not a spawned task. It polls its futures only inside its own `poll_next`, and then only the ones whose wakers fired, yielding outputs in completion order. In the loop, `poll_next` runs while `set.next().await` is pending; once `next()` returns an item and the body awaits slow work, nobody polls the set. Timers and sockets still signal readiness, but the code after each future's current `.await` waits until the loop calls `next()` again, so a multi-step future can miss a deadline. The same holds for `buffer_unordered` and `buffered`, which wrap a `FuturesUnordered`. The fix is to keep the slow work concurrent too: put it inside each future, push it into the same set, or spawn the futures as tasks so the executor drives them independently.
code
rust · 22 linesuse futures::stream::{FuturesUnordered, StreamExt};
use smol::Timer;
use std::time::{Duration, Instant};
async fn job(id: u64, start: Instant) -> u64 {
Timer::after(Duration::from_millis(id * 100)).await; // step 1: wait for a reply
println!("job {id} step 2 at {:>3} ms", start.elapsed().as_millis() / 10 * 10);
Timer::after(Duration::from_millis(10)).await; // step 2: send an ack
id
}
fn main() {
smol::block_on(async {
let start = Instant::now();
let mut set: FuturesUnordered<_> = (0..3).map(|id| job(id, start)).collect();
while let Some(id) = set.next().await {
println!("job {id} done at {:>3} ms", start.elapsed().as_millis() / 10 * 10);
// Slow per-result work awaited inside the loop: nothing in `set` is polled meanwhile.
Timer::after(Duration::from_millis(250)).await;
}
});
}go deeper
Recall that FuturesUnordered holds many futures and yields their outputs as each one finishes.
Explain that the set polls only woken futures and only during its own poll_next, and that push does not poll.
Diagnose stalls and missed deadlines caused by awaiting inside the consumer loop, and fix them by moving the slow work into the futures or into spawned tasks.
Set a review rule: no slow awaits inside a loop draining a set or buffered stream, and design per-item pipelines so every step is polled concurrently.
## What `FuturesUnordered` is `futures::stream::FuturesUnordered<Fut>` is a set of futures that is itself a `Stream`. Each `poll_next` call polls the futures that have been woken since the last call and yields the output of any that finished, so items come out in **completion order**, not push order (`FuturesOrdered` is the variant that preserves push order). You fill it by collecting an iterator of futures or by calling `push`. Three properties from its documentation matter here: - It is **optimised for many futures**: each future gets its own waker, and only futures that generated a wake-up are polled. `join!` and small `join_all` calls, by contrast, re-poll every unfinished future on each wake. - **`push` does not poll** the new future. The caller must keep calling `poll_next` for the future to start and to receive wake-ups. - An **empty set returns `Ready(None)`**, so `set.next().await` on an empty set yields `None` at once. Pushing again later makes it produce items again. The key point is the second one, generalised: the set is a data structure driven by its caller. It has no thread and no task of its own. ## Why the loop stalls ```rust while let Some(id) = set.next().await { process(id).await; // slow } ``` Trace who polls the set: 1. While `set.next().await` is pending, the enclosing task polls `Next`, which polls the set, which polls every woken future. Everything progresses. 2. When one future finishes, `next()` resolves and the loop body runs. Now the task is awaiting `process(id)`, and **nothing is polling the set**. 3. Other futures' timers expire and sockets become readable; their wakers fire and wake the task. But the task is busy inside `process(id).await`, which is the only thing it polls. Those futures stay suspended at their current `.await`. 4. Only when the body finishes and `next()` is awaited again do they resume, possibly long after their wake-up. The demonstration snippet shows it with three two-step jobs: job 1's first step completes at 100 ms and job 2's at 200 ms, but both start their second step at about 260 ms, after the 250 ms of processing for job 0. With real I/O that delay can mean a server-side timeout firing, a keep-alive being missed or a lease expiring, which look like network flakiness rather than a code bug. ## The same trap in other shapes | construct | contains | stalls when | |---|---|---| | `FuturesUnordered` in a `while let` loop | a set of futures | the loop body awaits something else | | `stream.buffer_unordered(n)` or `.buffered(n)` | a `FuturesUnordered` | the consumer awaits slow work per item | | a stream stored in a struct and polled occasionally | any futures inside it | the owner stops polling it | ## Fixes 1. **Move the slow work into the futures.** Make each future do fetch-then-process, for example `.map(|id| async move { process(job(id).await).await }).buffer_unordered(16)`. Now the processing is polled concurrently with everything else. In the fixed version of the demonstration, the jobs start their second steps at 0, 100 and 200 ms as intended. 2. **Push follow-up work into the same set.** Use an enum output so one set holds both kinds of future, and push the processing future when a fetch completes; the loop body itself then does no awaiting. 3. **Spawn tasks.** Futures spawned onto an executor are polled by the executor whenever they are woken, independently of any loop. That brings `Send` and `'static` requirements, which the lesson on spawning covers. 4. **Hand results to a separate consumer.** Send each output through a channel to a consumer that is driven independently, keeping the loop body free of slow awaits. Keep the loop body non-blocking and short, and treat every `.await` inside it as a pause for the whole set. That rule, rather than any particular API, is what a senior engineer applies when reviewing such code.
- Why does `FuturesUnordered` scale to thousands of futures better than `join_all` on a small list does?It gives each future its own waker and keeps a ready queue, so a `poll_next` call polls only the futures that were woken. A small `join_all` and `join!` re-poll every unfinished future on each wake-up, so the work per wake grows with the number of futures.
- You push a new future into a `FuturesUnordered` that is not currently being polled. When does that future start running?Only on the next `poll_next` call. `push` merely inserts the future; it is polled for the first time, and starts receiving wake-ups, only when the set is polled again, for example by awaiting `set.next()`.
- What does `while let Some(x) = set.next().await` do if the set is empty at the start?It exits immediately, because an empty `FuturesUnordered` returns `Ready(None)` from `poll_next`. Push the initial futures before the loop; if more arrive later, a fresh `next()` after a `push` yields again, because pushing resets the set's terminated state.
- FuturesUnordered runs its futures on a background thread
- push polls the new future immediately
- The executor polls the set's futures even while the loop awaits other work
- FuturesUnordered yields outputs in the order futures were pushed
- An empty FuturesUnordered waits until a future is pushed