dust

Concurrency and Tasks

Introduction

Requests often need to perform several independent operations, such as counting both users and orders for a dashboard. Running those operations concurrently makes the response only as slow as the slowest query rather than the sum of all of them. Other work, such as notifying a webhook after an order ships, doesn't need to delay the HTTP response at all.

The dust::task module provides helpers for running work concurrently and in the background. Prefer these helpers over tokio::spawn: they propagate the application's context and tracing span into the spawned work so resolve, config, the HTTP client, and logging continue working as expected.

Helper Use it when
task::try_join! You need every result, and any failure should stop the rest
task::join! You need every result, and the operations do not fail
task::select! You need the first result and can cancel the rest
task::map You process a collection with a concurrency limit
task::timeout An operation must not wait longer than a deadline
task::sleep You pause without blocking the thread
task::background The response does not wait, but shutdown should
task::spawn You want a handle to collect the output later
task::spawn_blocking The work is synchronous or CPU-heavy
A tick Each process repeats work on an interval

Running operations concurrently

To run multiple operations concurrently and wait for all of them to finish, use task::try_join!. It returns each output in the order you passed the operations, or short-circuits on the first error. For example, this dashboard handler counts users and orders in parallel:

rust
use dust::db;use dust::prelude::*;use dust::task;use serde_json::json;pub async fn show() -> dust::Result<Json<serde_json::Value>> {    let (users, orders) = task::try_join!(        db::table("users").count(),        db::table("orders").count(),    )?;    Ok(Json(json!({ "users": users, "orders": orders })))}

Pass the futures without .await, since the macro awaits them for you. When the operations do not return a Result, use task::join! instead.

To race several operations and continue as soon as the first one finishes, use task::select!. It executes the winning branch and drops the remaining futures, cancelling them. For example, this handler queries two exchange-rate providers and returns whichever responds first:

rust
use dust::http::client;use dust::task;pub async fn rates() -> dust::Result<String> {    let response = task::select! {        response = client::get("https://rates.example.com/latest") => response?,        response = client::get("https://backup-rates.example.com/latest") => response?,    };    Ok(response.text().into_owned())}

These are re-exports of Tokio's macros. Because they run within the current task, the operations can borrow local variables from your handler. They share one thread and interleave while waiting on I/O, which works well for database queries and HTTP requests. Code that blocks the thread stalls the other operations too, so move blocking work to spawn_blocking.

Limiting concurrency

Sometimes you have a list of items to process, such as fetching the GitHub profile of each organization on a user's account, and the upstream API limits how many requests you may send at once. Pass the collection, the maximum number of operations to run at the same time, and an async closure to task::map:

rust
use dust::http::client;use dust::prelude::*;use dust::task;use serde_json::Value;pub async fn index() -> dust::Result<Json<Vec<Value>>> {    let orgs = ["dust", "rust-lang", "tokio-rs"];    let profiles = task::map(orgs, 5, async |org| {        client::get("https://api.github.com/orgs/{org}")            .url_parameters([("org", org)])            .await?            .json::<Value>()    })    .await?;    Ok(Json(profiles))}

task::map returns the results in the order of the input items, so profiles[0] is always the profile for dust regardless of which request finished first. If any call returns an error, task::map stops starting remaining items, drops the other in-flight futures to cancel them, and returns that error.

Time limits and pauses

An outgoing request waits as long as the remote service takes, which can tie up your handler if an upstream service hangs. To enforce a deadline, pass a duration and a future to task::timeout. Because the operation's own Result is nested inside the timeout's Result, unwrap both with ??:

rust
use dust::http::client;use dust::prelude::*;use dust::task;pub async fn rates() -> dust::Result<String> {    let response = task::timeout(        3.seconds(),        client::get("https://rates.example.com/latest"),    )    .await??;    Ok(response.text().into_owned())}

If the operation does not finish in time, timeout cancels it and returns a task::TimedOut error, which dust-framework renders as a 504 Gateway Timeout response. Since the outer Result only fails on timeout, you can match on it to fall back cleanly, such as returning cached rates:

rust
use dust::cache;use dust::http::client;use dust::prelude::*;use dust::task;pub async fn rates() -> dust::Result<String> {    let request = client::get("https://rates.example.com/latest");    match task::timeout(3.seconds(), request).await {        Ok(response) => Ok(response?.text().into_owned()),        Err(_) => Ok(cache::get::<String>("rates").await?.unwrap_or_default()),    }}

To pause execution without blocking the thread (for example, between rate-limited API calls), await task::sleep. Other requests continue running while the task sleeps:

rust
use dust::prelude::*;use dust::task;task::sleep(500.milliseconds()).await;

Background work

When the user does not need to wait for an operation to finish, run it with task::background. The task starts immediately while your handler returns its response. For example, this handler marks an order as shipped and notifies a webhook in the background:

rust
use dust::http::client;use dust::prelude::*;use dust::task;use serde_json::json;pub async fn ship(Params(id): Params<u64>) -> dust::Result<Redirect> {    // Mark the order as shipped...    task::background(async move {        client::post("https://example.com/webhooks/shipped")            .json(json!({ "order_id": id }))            .ensure_successful()            .await?;        Ok(())    })?;    Ok(Redirect::back())}

The future returns dust::Result<()>, and dust-framework reports any errors or panics as it does for handlers. Capture owned values such as IDs with async move, and avoid reading the request or session inside the task since it may outlive the HTTP response. background itself only returns an error if the application has already started shutting down, so propagate it with ?.

During graceful shutdown, the server waits for in-flight background work to complete, up to SERVER_SHUTDOWN_TIMEOUT. Console commands also wait for background work before exiting, so you may use task::background inside commands and scheduled callbacks as well.

[!WARNING] Background work is not a replacement for a queue. Tasks are not retried on failure and any unfinished work is lost if the process exits unexpectedly. For work that must succeed reliably, such as charging a card or sending a receipt, dispatch a queued job instead.

Spawned tasks

Sometimes you want to kick off an operation, perform other work in the meantime, and collect its output later in the same handler. task::spawn starts the future as an independent task that may run on another worker thread and returns a handle you can await. Like the other helpers in dust::task, it carries the current application context and tracing span into the new task:

rust
use dust::db;use dust::prelude::*;use dust::task;use serde_json::json;pub async fn show() -> dust::Result<Json<serde_json::Value>> {    let orders = task::spawn(async { db::table("orders").count().await });    let users = db::table("users").count().await?;    let orders = orders.await??;    Ok(Json(json!({ "users": users, "orders": orders })))}

A spawned task must own any data it uses, so capture values with async move. Awaiting the handle fails if the task panicked; otherwise it returns the task's output. When that output is itself a Result, ?? unwraps both layers. Spawned task errors are not reported automatically, so return them from your handler or report them directly.

Dropping the handle does not cancel the task; it continues running in the background, though server shutdown will not wait for it. Use task::background for work that graceful shutdown should wait for.

Blocking work

CPU-intensive work or synchronous libraries (such as image resizing or building a large export) block their OS thread until finished, delaying other requests sharing that thread. Offload blocking code with task::spawn_blocking, which runs the closure on a dedicated blocking thread pool while preserving your application context and tracing span:

rust
use dust::task;pub async fn export() -> dust::Result<String> {    let csv = task::spawn_blocking(move || {        // Build a large CSV report with a synchronous library...        String::from("id,total\n1,100\n")    })    .await?;    Ok(csv)}

Database queries and HTTP client requests are already async and do not need spawn_blocking. Once a blocking closure starts running, it cannot be cancelled mid-flight; wrapping its handle in task::timeout stops waiting for the output, but the closure itself still runs to completion.

Cancellation and ownership

task::select!, task::timeout, and task::map cancel the futures they no longer need by dropping them. A future stops at its next .await point, so a database write or HTTP request that has already been sent may still complete on the server even though your code never observes the result. Structure the work so a cancelled attempt leaves no half-written state, or move it into a queued job whose retries and idempotency you control.

Each helper also answers a different question about lifetime:

  • task::background belongs to the current request or command. Graceful shutdown waits for it up to SERVER_SHUTDOWN_TIMEOUT, but a crash loses it.
  • task::spawn returns a handle. Dropping the handle detaches the task, and shutdown does not wait for it.
  • task::spawn_blocking owns a dedicated thread until the closure returns, even if the caller stops waiting.

If the work must finish, survive a deploy, or be retried, it does not belong in any of these helpers; dispatch a job instead.

Ticks

Sometimes each process of your application maintains in-memory state, such as buffered view counts that you flush periodically instead of writing to the database on every request. A tick runs an async callback on a repeating interval inside each server process and each queue worker. Register ticks with with_ticks in src/app.rs:

rust
use dust::prelude::*;use crate::services::ViewCounts;async fn flush_view_counts(counts: Inject<ViewCounts>) -> dust::Result<()> {    counts.flush().await}Application::configure()    .with_ticks(|ticks, _| {        ticks            .every(10.seconds(), flush_view_counts)            .name("flush-view-counts")            .when(|host| host.is_server())            .run_on_shutdown();    })

A tick callback is an async function or closure returning () or dust::Result<()>, and may inject Inject<T> services and Section<T> config sections. Each tick runs in its own application context where resolve, config, and once work like they do in a request. dust-framework reports any errors or panics from a tick and continues scheduling future ticks. A service provider can register ticks via app.ticks() inside register.

Each interval starts after the previous tick finishes, so ticks never overlap. You may configure a tick with the following methods:

Method Effect
name("flush-view-counts") Names the tick for log output and testing.
immediately() Runs the first tick as soon as the process starts instead of waiting one interval.
jitter(2.seconds()) Randomizes each wait by up to the given duration so processes started together don't tick in lockstep.
run_on_shutdown() Runs the tick one final time during shutdown after in-flight requests or jobs finish, flushing any remaining buffered state.
when(|host| host.is_server()) Runs the tick only in the processes the closure accepts.

Ticks run in the HTTP server (serve) and in every queue worker (queue:work). Other console commands, the scheduler, and tests do not run them automatically.

Choosing where ticks run

Some ticks only apply to a specific type of process. For example, if only HTTP requests increment your buffered view counts, queue workers have nothing to flush. Pass a closure to when to inspect the current Host and return true when the tick should run (dust-framework evaluates the closure before each tick, so you may also check configuration values):

rust
use dust::foundation::Host;use dust::prelude::*;Application::configure()    .with_ticks(|ticks, _| {        ticks            .every(10.seconds(), flush_view_counts)            .when(|host| host.is_server());        ticks            .every(10.seconds(), flush_job_metrics)            .when(|host| host.is_worker());        ticks            .every(10.seconds(), flush_priority_metrics)            .when(|host| match host {                Host::Worker { queues, .. } => queues.iter().any(|queue| queue == "high"),                _ => false,            });    })

Host::Server represents the HTTP server, while Host::Worker represents a queue worker and carries the connection and queue names it processes. To run ticks inside your own long-running console commands, add with_ticks to #[command] (such as #[command("feeds:watch", long_running, with_ticks)]), which sets the host to Host::Command containing the command's name.

You may also inspect the current process host anywhere in your application, such as inside a job or service, by calling foundation::host(). It returns None in one-off console commands and tests:

rust
use dust::foundation;if foundation::host().is_some_and(|host| host.is_worker()) {    // Running in a queue worker...}

[!NOTE] Every server process and queue worker runs its matching ticks independently. For work that should run once across your entire fleet or at a specific time of day, use the scheduler instead.

Testing ticks

Tests do not run ticks on a timer. To execute a named tick inside a test, call app.tick (which invokes the tick directly without evaluating its when closure) and assert on its effects:

rust
use dust::testing::prelude::*;#[dust::test]async fn flushing_saves_view_counts(app: Application) -> dust::Result<()> {    app.tick("flush-view-counts").await?;    // Assert on what the tick saved...    Ok(())}