skip to content

With Rust's `futures::try_join!`, what happens to the other futures when one of them resolves to `Err`?

level: middleimportance: should knowfreq 48%

answer

  1. first error wins
  2. the rest are dropped, not finished
  3. work after the last .await never runs
  4. one shared error type

basics

~10 s

try_join! completes at once with that error, and the futures still pending are dropped unfinished: they are never polled again, their destructors run, and any code after their current .await never executes.

solid answer

~40 s

`futures::try_join!(a, b)` polls each future like `join!`, but as soon as a poll returns `Err` the macro returns that `Err`. The futures that were still pending are dropped when the macro's combined future goes out of scope, so they are cancelled at whatever `.await` they were suspended on: their `Drop` impls run, and the rest of their bodies never executes. Nothing they already did is undone. All futures must share one error type, though their `Ok` types can differ, and the success value is a tuple in argument order. For a `Vec` of fallible futures, `futures::future::try_join_all` behaves the same way and returns `Result<Vec<T>, E>`. Plain `join!` on futures that return `Result` never short-circuits: it waits for every one and hands back a tuple of results.

code

rust · 27 lines
rust
use futures::try_join;
use smol::Timer;
use std::time::Duration;

struct Guard(&'static str);
impl Drop for Guard {
    fn drop(&mut self) {
        println!("dropped: {}", self.0);
    }
}

async fn load_profile() -> Result<String, String> {
    let _g = Guard("load_profile");
    Timer::after(Duration::from_millis(300)).await;
    println!("profile loaded"); // never printed
    Ok("alice".to_string())
}

async fn load_orders() -> Result<Vec<u32>, String> {
    Timer::after(Duration::from_millis(50)).await;
    Err("orders: 503".to_string())
}

fn main() {
    let r = smol::block_on(async { try_join!(load_profile(), load_orders()) });
    println!("{r:?}");
}

go deeper

for a junior

Recall that try_join! returns Ok with a tuple only if every future succeeds, and returns the first error otherwise.

for a middle

Explain that the pending futures are dropped as soon as an error is seen, so their remaining code never runs, and that all branches need one error type.

for a senior

Show that you think about what a cancelled branch leaves behind, such as half-written state or open connections, and whether dropping it there is safe.

for a principal

Weigh fail-fast against collecting every outcome: try_join! saves time on doomed requests, join! gives complete diagnostics and partial results.

## Short-circuiting a group of fallible futures Many async operations return `Result<T, E>`: a database query, an HTTP call, a file read. When a handler needs several of them and any single failure makes the whole request fail, waiting for the slow survivors is wasted time. The `futures` crate offers `try_join!` for that case: ```rust let (profile, orders) = futures::try_join!(load_profile(), load_orders())?; ``` `try_join!` evaluates to `Result<(T1, T2), E>`. If every future returns `Ok`, the tuple holds the values in argument order. If any returns `Err`, the whole expression is that `Err`, and it is produced **as soon as the error is observed**, not when the other futures finish. ## What happens to the losers The macro's expansion in futures 0.3 polls every unfinished future in argument order each time the task wakes. When a future reports `Ready(Err(e))`, the combined future returns `Ready(Err(e))` at once. The pending futures are locals of the macro's block, so when the `.await` completes they are **dropped**. Dropping a future is how Rust cancels it: - It is **never polled again**, so the code after the `.await` it was suspended on never runs. - Its **destructors run**, for every value it owned at that suspension point: guards, buffers, connections. - Work it **already finished** stays finished. A request already sent is not unsent, and a row already written is not rolled back. The demonstration snippet makes this visible. `load_orders` fails after 50 ms, `load_profile` still has 250 ms to go: the program prints `dropped: load_profile` from a guard's `Drop`, never prints `profile loaded`, and finishes with `Err("orders: 503")` after about 50 ms. Whether dropping a particular future mid-operation is safe is the question of **cancellation safety**, which the lesson on cancellation covers. ## The family of joins | combinator | input | waits for | output | |---|---|---|---| | `futures::join!` | a fixed list of futures | all of them | `(T1, T2, ...)` | | `futures::try_join!` | a fixed list of `Result` futures | all, or the first `Err` | `Result<(T1, T2, ...), E>` | | `futures::future::join_all` | an iterator of futures | all of them | `Vec<T>` in input order | | `futures::future::try_join_all` | an iterator of `Result` futures | all, or the first `Err` | `Result<Vec<T>, E>` in input order | A few rules fall out of the types: 1. **One error type.** The macro returns `Err` from whichever branch failed, so every branch must use the same `E`. Mixing `String` and `std::io::Error` fails to compile with E0308 (mismatched types); convert the errors first, for example with `map_err` or into a shared error enum. 2. **`Ok` types may differ.** Each position in the success tuple has its own type. 3. **Which error wins.** The first `Err` seen in a poll pass, in argument order, is returned. If two futures fail in the same pass, the earlier argument's error is the one you get. 4. **`join!` on `Result`s never short-circuits.** It returns `(Result<T1, E1>, Result<T2, E2>)` after every future finished, which is what you want when partial success is useful, for example to report every failed check at once. ## Choosing between them - Use **`try_join!`** when any failure fails the whole operation and the remaining work is pointless. - Use **`join!`** when each result is reported separately or failures are tolerated. - Use **`try_join_all`** for a dynamic number of fallible futures, remembering that it starts and polls all of them at once. - If the losers hold resources that must be released in an orderly way, give them guards with `Drop` impls, because there is no stable async drop to await cleanup in. The core idea to say in an interview: `try_join!` does not stop the other futures by signalling them; it simply stops polling them and drops them, and that drop is the cancellation.

  • If a future cancelled by `try_join!` had already sent an HTTP request, is that request undone?
    No. Dropping a future only stops future polling and runs destructors. Anything already done, such as bytes written to a socket or a row inserted, stays done. If the operation must be compensated, the caller has to do it explicitly; whether stopping mid-operation is safe at all is the cancellation-safety question.
  • How do you use `try_join!` on futures whose error types differ?
    Convert them to one type before joining, for example `load_a().map_err(AppError::from)` with `futures::TryFutureExt`, or by awaiting inside small async blocks that apply `?` with a `From` conversion. The macro returns one `Result<(..), E>`, so a mismatch fails to compile with E0308.
  • When is plain `join!` the better choice for fallible futures?
    When partial results matter: a health check that reports every failing dependency, a batch that records which items failed, or a page that renders the sections that loaded. `join!` waits for all and returns each `Result`, so no failure hides another.

  • try_join! lets the other futures run to completion in the background
  • try_join! waits for every future and then returns the first error
  • Dropping a cancelled future rolls back what it already did
  • Each future in try_join! may use its own unrelated error type
  • join! on Result futures stops at the first Err