dust

Workflows

Introduction

Some processes in your application span days rather than seconds. Onboarding a new user might involve sending a welcome email, waiting three days, and sending getting-started tips if they haven't created a project yet. Implementing that flow with queues alone requires chaining delayed jobs, tracking progress in status columns, and scheduling sweep commands for stalled users.

Workflows let you express that entire flow as a single async function. dust-framework executes each step once, persists its result, and resumes execution across sleeps, external webhooks, deploys, and worker restarts:

rust
// src/workflows/onboard_user.rsuse dust::queue::Queueable;use dust::time::ToSpan;use dust::workflow::{Run, workflow};#[derive(Queueable)]pub struct OnboardUser {    pub user_id: i64,}#[workflow]impl OnboardUser {    async fn handle(self, run: &Run) -> dust::Result<()> {        run.step("send welcome email", self.send_welcome_email()).await?;        run.sleep(3.days()).await?;        if run.step("count projects", self.count_projects()).await? == 0 {            run.step("send tips", self.send_tips()).await?;        }        Ok(())    }}

Choose the lightest tool that fits:

Shape of the work Use
One task that runs once and can be retried A job
A fixed sequence that must run in order A job chain
A fan-out that needs a callback when everything finishes A job batch
Logic that branches, sleeps for days, or waits for a webhook A workflow
Work that repeats on a clock The scheduler

Use a workflow when the control flow itself matters. If a hundred independent rows can run in any order, a batch is simpler and cheaper than a workflow with a hundred steps. If the flow is a straight line with no waiting, a chain already gives you ordering.

How a run advances

Workflows run on your existing queue workers and connections, so there is no extra infrastructure to deploy. Each advance executes as a queued job: the worker invokes handle from the top, immediately replays any steps whose results are already stored, and runs the next unrecorded step.

When execution reaches a sleep, a wait, or a step retry backoff, the run suspends. The worker finishes the current job and schedules the next advance with the appropriate delay. No worker sits idle while a workflow sleeps, so a run waiting for two weeks consumes no resources in the meantime.

If a worker crashes while advancing a run, the run's lease expires and workflow:recover requeues it from the last recorded step. A step that had already finished external work but had not been recorded runs again, which is why steps should be idempotent. A newer worker never advances a run whose lease is still held by another worker.

Setup

Workflows require a queue worker backed by a connection that supports delayed jobs, such as database, redis, or sqs.

The workflow tables

The database workflow store persists runs across five tables on your default database connection. Because new applications do not include these tables by default, add a migration that holds only the workflow::tables! macro before starting a workflow. The macro creates all five tables:

rust
// database/migrations/2026_01_01_000000_create_workflow_tables.rsdust::workflow::tables!();

If you'd like to change the tables, such as adding an index, replace the macro with the migration it stands for and edit it:

rust
// database/migrations/2026_01_01_000000_create_workflow_tables.rsuse dust::db::AnyTransaction;pub async fn migrate(tx: &mut AnyTransaction<'_>) -> dust::Result<()> {    tx.schema()        .create("workflow_runs", |table| {            table.string("id").length(36).primary();            table.string("workflow");            table.long_text("input");            table.long_text("context");            table.string("connection");            table.string("queue");            table.string("status").length(16);            table.long_text("output").nullable();            table.text("error").nullable();            table.timestamp("wake_at").nullable();            table.timestamp("leased_until").nullable();            table.string("lease_token").length(36).nullable();            table.timestamp("created_at");            table.timestamp("finished_at").nullable();            table.string("unique_key").nullable().unique();            table.boolean("purge_data").default(false);            table.index(["workflow", "id"]);            table.index(["status", "wake_at"]);            table.index("finished_at");        })        .await?;    tx.schema()        .create("workflow_steps", |table| {            table.id();            table.string("run_id").length(36);            table.string("kind").length(8);            table.string("name");            table.string("status").length(16);            table.integer("tries");            table.long_text("output").nullable();            table.text("error").nullable();            table.timestamp("wake_at").nullable();            table.timestamp("started_at");            table.timestamp("finished_at").nullable();            table.unique(["run_id", "kind", "name"]);        })        .await?;    tx.schema()        .create("workflow_waits", |table| {            table.string("token").primary();            table.string("run_id").length(36);            table.integer("number").nullable();            table.timestamp("resumed_at").nullable();            table.index("run_id");        })        .await?;    tx.schema()        .create("workflow_resumes", |table| {            table.string("run_id").length(36);            table.string("token");            table.big_integer("number");            table.long_text("value");            table.timestamp("created_at");            table.primary(["run_id", "token", "number"]);        })        .await?;    tx.schema()        .create("workflow_attributes", |table| {            table.string("run_id").length(36);            table.string("name");            table.string("value");            table.primary(["run_id", "name"]);            table.index(["name", "value"]);        })        .await}

To store these tables on a separate database connection, set DB_WORKFLOW_CONNECTION.

Choosing a store

By default, dust-framework stores workflow runs in the database store, switching to the memory store in tests so workflow tests do not require database tables. Set WORKFLOW_STORE to choose a different store. Because the memory store loses all state when the process exits, never use it in production.

You can define additional stores in src/config/workflow.rs, such as a database store targeting another connection or a custom store provided by a package:

rust
// src/config/workflow.rsuse dust::config::workflow::{DatabaseStore, Workflow};use dust::config::{self, Env};#[config::section]fn workflow(env: &Env) -> Workflow {    let mut workflow = Workflow::from_env(env);    workflow.add_store("database", DatabaseStore::new().connection("workflows"));    workflow}

Defining workflows

Like a job, a workflow is a struct deriving Queueable paired with a #[workflow] impl. Place each workflow in its own file under src/workflows/.

The struct's fields form the workflow's input. dust-framework persists them when the run starts and provides a fresh deserialized copy to handle on each advance. Model fields serialize only their primary keys and reload on every advance, so they always reflect the latest database state rather than the state when the run began. Only branch on mutable model columns inside a recorded step, and prefer storing IDs rather than models when rows may change while a run sleeps.

handle takes self and &Run, along with any Inject<T> services or Section<T> config sections in any order. It returns dust::Result<T>, where T is () or any serializable output type.

#[workflow] accepts two options:

Option Description
name = "users.onboard" Stable identifier persisted for runs. Defaults to the type's module path
queue = "workflows" Default queue for the run's jobs when on_queue is not set at start

In-flight runs resolve their workflow implementation by name, so renaming or moving a struct without an explicit name orphans active runs. Assign a stable name before deploying a workflow to production.

A workflow may also define a failed method that runs once when the run fails permanently. It receives &dust::Error along with any Inject<T> services or Section<T> config sections, returning () or dust::Result<()>, and dust-framework reports any error it returns. Because failed restores the workflow from its stored input, it does not run if a model field's row was deleted. Listen for RunFailed to observe every failure:

rust
use dust::container::Inject;use dust::workflow::{Run, workflow};#[workflow(name = "orders.checkout")]impl Checkout {    async fn handle(self, run: &Run, payments: Inject<Payments>) -> dust::Result<()> {        run.step("charge card", payments.charge(self.order_id)).await?;        Ok(())    }    async fn failed(self, error: &dust::Error, slack: Inject<Slack>) {        slack.alert(format!("checkout {} failed: {error}", self.order_id)).await;    }}

Starting runs

#[workflow] generates a start method analogous to a job's dispatch. Awaiting it persists the run, queues its first advance, and returns the RunId:

rust
use dust::prelude::*;use crate::workflows::OnboardUser;pub async fn store(user: User) -> dust::Result<Redirect> {    OnboardUser { user_id: user.id }.start().await?;    Ok(Redirect::to("/dashboard"))}

You can route the run's jobs to a specific queue connection or queue, or delay when it starts. The connection and queue chosen at start apply for the entire lifetime of the run:

rust
use dust::time::ToSpan;let run_id = OnboardUser { user_id: user.id }    .start()    .on_connection("redis")    .on_queue("workflows")    .delay(1.hours())    .await?;

Starting a workflow inside db::transaction waits until the transaction commits and is discarded on rollback, as dispatching a job does. dust-framework captures the current context values, such as the active tenant, and restores them on every advance.

Starting a run once

Duplicate form submissions or repeated webhooks can trigger the same workflow twice. To prevent duplicate runs, pass a uniqueness key to unique. If an active run already holds that key, start returns the existing run instead of creating a new one:

rust
use dust::prelude::*;use dust::workflow::Started;pub async fn submit(Params(expense_id): Params<i64>) -> dust::Result<Redirect> {    let started = ApproveExpense { expense_id }        .start()        .unique(format!("expenses.{expense_id}"))        .await?;    if let Started::Existing(run_id) = started {        tracing::info!(%run_id, "the expense is already waiting for approval");    }    Ok(Redirect::to("/expenses"))}

A unique start returns Started::New(run_id) or Started::Existing(run_id). Call started.id() when you want the RunId without matching on the variant. A run releases its key once it completes, fails, or is cancelled, so resubmitting an expense after rejection starts a new run. Inside db::transaction, start returns Started::Pending and checks uniqueness on commit.

Attributes

Attributes attach searchable metadata to a run, such as its tenant or current stage. You can filter by them with workflow:list --attribute and inspect them via workflow:show or RunInfo::attributes(). Set initial attributes when starting a run:

rust
let run_id = OnboardUser { user_id: user.id }    .start()    .attribute("tenant", "acme")    .attribute("plan", "pro")    .await?;

You can also update attributes as the workflow progresses so operators can see a run's current phase without inspecting individual steps. Later assignments overwrite earlier values for the same name:

rust
run.step("charge card", self.charge_card()).await?;run.set_attribute("phase", "shipping");

Attributes are persisted whenever an advance ends by sleeping, waiting, completing, or failing. Replays re-apply them in the same order without extra writes.

Keep attribute values short and non-sensitive, since they remain stored for the lifetime of the run.

Deleting a run's data

Workflow runs retain their input, step outputs, and final output until workflow:prune removes them. For workflows that handle sensitive data such as bank details, chain purge_when_finished to wipe those payloads as soon as the run completes, fails, or is cancelled:

rust
let run_id = VerifyBankAccount { account_id }    .start()    .purge_when_finished()    .await?;

The run still retains its ID, status, attributes, and step names and timestamps, so workflow:list and workflow:show continue to display it with <data deleted> in place of its input. RunInfo::purged() returns true and output() returns None, so persist any needed workflow output inside a step. A purged run that failed cannot be retried.

Steps

run.step(name, work) executes work once and persists its result under name. The work can be any future returning dust::Result<T> where T is serializable, such as an async method on the workflow struct or an inline async block:

rust
let receipt = run.step("charge card", self.charge_card()).await?;let total = run    .step("total the order", async {        let order = Order::find_or_fail(self.order_id).await?;        order.total().await    })    .await?;

Pass the future without awaiting it. dust-framework awaits work only if the step has not been recorded yet; on subsequent advances, it returns the stored result immediately.

Step names identify recorded results across replays, appear in workflow:show, and let tests stub individual steps. Every step name must be unique within a run, so include a distinguishing index or key when calling steps in a loop:

rust
for day in [1, 3, 7] {    run.sleep(day.days()).await?;    run.step(format!("send reminder {day}"), self.send_reminder(day)).await?;}

Retries and timeouts

By default, a failing step is retried up to three times with backoffs of 10 seconds and 1 minute. Panics count as failed attempts. You can customize a step's retry count, backoff schedule, and timeout:

rust
let receipt = run    .step("charge card", self.charge_card())    .tries(5)    .backoff([10.seconds(), 1.minutes(), 10.minutes()])    .timeout(30.seconds())    .await?;

The run suspends during each backoff delay so no worker is tied up waiting. When backoff is a list, the final duration repeats for any remaining retries.

Some external failures tell you when to retry, such as an API returning a Retry-After header. Return workflow::retry_after(when, error) to override the step's backoff with a specific span or timestamp. The retry still counts toward the step's tries:

rust
use dust::http::client;use dust::prelude::*;use dust::workflow;#[derive(Debug, thiserror::Error)]#[error("the CRM is busy")]struct CrmBusy;async fn sync_contacts(&self) -> dust::Result<()> {    let response = client::post("https://crm.example.com/contacts/sync").await?;    if response.status() == StatusCode::TOO_MANY_REQUESTS {        let seconds: i64 = response            .header("retry-after")            .and_then(|seconds| seconds.parse().ok())            .unwrap_or(60);        return Err(workflow::retry_after(seconds.seconds(), CrmBusy));    }    Ok(())}

If a worker crashes after a step completes external work but before dust-framework records its result, the step will run again, so design steps to be idempotent. Inside a step, workflow::current_step() returns the active step handle whose key() combines the run ID and step name deterministically across retries. Pass step.key() as an idempotency key to payment gateways or external APIs to prevent duplicate side effects:

rust
use serde_json::json;async fn charge_card(&self) -> dust::Result<()> {    let step = workflow::current_step();    client::post("https://payments.example.com/charges")        .header("Idempotency-Key", step.key())        .json(json!({ "order_id": self.order_id }))        .await?;    Ok(())}

You can also inspect step.attempt() to see the 1-based attempt number, such as when adjusting behavior on the final retry.

Permanent step failures

To fail a step immediately without retrying, such as when a card is declined by the bank, wrap the error with workflow::fatal:

rust
use dust::workflow;async fn charge_card(&self) -> dust::Result<Receipt> {    self.gateway.charge(self.order_id).await.map_err(workflow::fatal)}

When a step exhausts its retries or returns fatal, run.step(..).await resolves to a workflow::StepFailed error containing the step name and final error. Propagating it with ? fails the run. On every subsequent replay, the step returns that recorded error so error handling and branching behave identically across replays.

You can express compensating transactions in plain Rust. For example, a travel booking workflow can cancel the flight if booking the hotel fails:

rust
let flight = run.step("book flight", self.book_flight()).await?;if let Err(error) = run.step("book hotel", self.book_hotel()).await {    run.step("cancel flight", self.cancel_flight(&flight)).await?;    return Err(error);}

"cancel flight" is a normal workflow step, so dust-framework retries and records it like "book flight" and "book hotel".

Parallel steps

Use task::try_join! to run multiple steps concurrently on the current worker. If one step fails permanently, task::try_join! cancels the remaining steps and returns that error:

rust
use dust::task;let (projects, teammates) = task::try_join!(    run.step("count projects", self.count_projects()),    run.step("count teammates", self.count_teammates()),)?;

To fan work out across multiple queue workers and wait for all of it to finish, claim the completion token when you start the workflow so a fast batch can't finish before wait_for runs, dispatch a job batch whose finally callback calls workflow::resume with whether the batch succeeded, and pause the workflow with run.wait_for:

rust
use dust::queue::{self, Batch, callback};use dust::workflow::{self, Run};#[callback]async fn batch_finished(token: String, batch: &Batch) -> dust::Result<()> {    workflow::resume(token, batch.failed_jobs() == 0).await?;    Ok(())}// Claim the token before starting so early completions are buffered:// ImportContacts { import_id, chunks }//     .start()//     .claim(format!("imports.{import_id}.done"))//     .await?;async fn handle(self, run: &Run) -> dust::Result<()> {    let token = format!("imports.{}.done", self.import_id);    run.step("dispatch batch", async {        let jobs = self.chunks.iter().cloned().map(|rows| ImportCsv { rows });        queue::batch(jobs).finally(batch_finished(token.clone())).await?;        Ok(())    })    .await?;    let succeeded = run.wait_for::<bool>(&token).await?;    if !succeeded {        return Err(dust::Error::msg("one or more import jobs failed"));    }    run.step("mark import complete", self.mark_complete()).await?;    Ok(())}

Rules for handle

Because handle replays from the top on every advance, it must follow deterministic control flow. dust-framework enforces what it can and fails the run with a descriptive error if a rule is violated:

  • Perform all I/O inside steps. A database query or HTTP call outside a step may return different results on replay. If handle awaits anything other than an operation on &Run, the run fails and reports the last step it passed.
  • Branch only on workflow inputs and recorded step, sleep, or wait results. Read the current time and random values inside steps. run.id() and run.started_at() are deterministic across replays and safe to call anywhere.
  • Keep step names and wait tokens unique within a run. Reusing a step name or wait token fails the run, as does reading from the same inbox token through two separate Inbox handles.
  • Avoid task::select! and spawning tasks around steps. A cancelled branch stops mid-step and restarts on the next advance. To expire a wait after a duration, chain .timeout(..) on wait_for instead of combining it with run.sleep in task::select!.

Changing a workflow with runs in flight

Because workflows can sleep or wait for days, you will often deploy changes to a workflow while existing runs are still in flight. When a sleeping run wakes up, dust-framework runs your newly deployed handle method and matches each run.step call against the step names already recorded for that run. That makes adding or removing steps safe in most cases, while renaming steps or changing stored return types requires extra care:

Change Effect on in-flight runs
Add a step Runs the new step once reached
Remove a step Ignores the previously recorded result
Rename a step Executes it again under the new name, so avoid renaming steps with side effects
Change a step's output type Fails naming the step unless stored JSON still deserializes; use #[serde(default)] and #[serde(alias)]
Rewrite the flow Introduce a new workflow struct and retain the old one until existing runs finish

Sleeping

Call run.sleep to suspend a run for a duration, or run.sleep_until to wait until a specific Timestamp or ZonedDateTime. Sequential sleeps are numbered automatically, appearing in workflow:show as sleep 1, sleep 2, and so on, though you may label any sleep with named:

rust
use dust::time::ToSpan;run.sleep(3.days()).await?;run.sleep(1.hours()).named("trial grace period").await?;run.sleep_until(self.trial_ends_at).await?;

Because sleeps are implemented as delayed queue jobs, they require a queue connection that supports delays. SQS FIFO queues do not support delays, and the sync connection executes jobs immediately, pausing at the first sleep until a test or workflow:recover advances the run.

Waiting and resuming

run.wait_for::<T>(token) suspends the run until another part of your application delivers a value via workflow::resume(token, value). For example, this workflow pauses until a manager approves or rejects an expense:

rust
use dust::workflow::{Run, workflow};use serde::{Deserialize, Serialize};#[derive(Serialize, Deserialize)]pub enum Decision {    Approved,    Rejected { reason: String },}#[workflow]impl ApproveExpense {    async fn handle(self, run: &Run) -> dust::Result<()> {        run.step("ask the manager", self.ask_manager()).await?;        let decision = run            .wait_for::<Decision>(format!("expenses.{}.decision", self.expense_id))            .await?;        match decision {            Decision::Approved => run.step("pay out", self.pay_out()).await,            Decision::Rejected { reason } => {                run.step("notify the employee", self.reject(&reason)).await            }        }    }}

When the run reaches wait_for, it claims ownership of expenses.42.decision until the run completes, fails, or is cancelled. In this example, the approval email links to a route whose handler resumes the waiting run:

rust
use dust::prelude::*;use dust::workflow::{self, Resumed};pub async fn approve(Params(expense_id): Params<i64>) -> dust::Result<Redirect> {    let resumed =        workflow::resume(format!("expenses.{expense_id}.decision"), Decision::Approved).await?;    if resumed == Resumed::NotFound {        return Ok(            Redirect::to("/expenses")                .with("status", "This expense was already decided."),        );    }    Ok(Redirect::to("/expenses"))}

workflow::resume returns Resumed::Delivered when an active run owns the token and receives the value, or Resumed::NotFound when no active run owns it (storing nothing, so a duplicate click on an already-decided expense won't accidentally resume a future run). Inside db::transaction, workflow::resume defers delivery until commit and returns Resumed::Pending.

A wait token is an identifier, not a secret. Anyone who can reach the route can resume the run, so protect it with an authorization policy (for example, checking that the signed-in user manages the expense) or a signed URL.

Because a per-record token like expenses.42.decision always routes to whichever run for that expense is currently active, an approval page left open in an old tab could still decide a newer run. If a page should only resume the specific run that rendered it, include run.id() in the token and pass that token in the form or link (or use a resume URL, which embeds the token for you):

rust
let token = format!("expenses.{}.decision.{}", self.expense_id, run.id());let decision = run.wait_for::<Decision>(token).await?;

Only one active run may own a given token at a time; if a second run calls wait_for on a token already owned by another active run, the second run fails with an error naming the owner. Include the record's ID in your tokens, and use a unique start when a record should only have one active run at a time.

Chaining .timeout(span) changes the wait's return type to Option<T>, yielding None if the duration elapses before a resume arrives:

rust
let decision = run    .wait_for::<Decision>(format!("expenses.{}.decision", self.expense_id))    .timeout(3.days())    .await?;

To inspect the waiting run before resuming it (for example, to check its attributes), call workflow::waiting_for(token). It returns Some(RunInfo) for the run currently suspended on that token, or None if no run is waiting (including a run that has claimed the token but hasn't reached wait_for yet):

rust
let waiting = workflow::waiting_for(format!("expenses.{expense_id}.decision")).await?;if let Some(run) = waiting {    // Check run.attributes() before resuming...}

Early resumes

Sometimes a resume arrives before the workflow reaches wait_for. For example, a step might ask a payment gateway to charge a card, and the gateway's webhook might hit your application before the step finishes and the workflow advances to run.wait_for. Because no run owns the token yet, workflow::resume returns Resumed::NotFound.

To buffer early resumes for a run, claim the token when you start it. The run owns the token immediately, and any values sent before it reaches wait_for are queued and delivered in order:

rust
let run_id = ChargeOrder { order_id }    .start()    .claim(format!("orders.{order_id}.charged"))    .await?;

Starting the run fails if another active run already owns the token. You may chain claim for each token the run will wait on.

If you don't know the token at start time, return a non-2xx status from your webhook handler when workflow::resume returns Resumed::NotFound so the provider retries once the run is waiting. Webhook URLs do this automatically by responding with 404 Not Found. In a custom route handler, match on the result:

rust
use dust::prelude::*;use dust::workflow::{self, Resumed};pub async fn charged(    Params(order_id): Params<i64>,    Json(charge): Json<Charge>,) -> StatusCode {    match workflow::resume(format!("orders.{order_id}.charged"), charge).await {        Ok(Resumed::NotFound) => StatusCode::NOT_FOUND,        Ok(_) => StatusCode::ACCEPTED,        Err(_) => StatusCode::INTERNAL_SERVER_ERROR,    }}

Typed tokens

With string tokens, the workflow and the handler that resumes it are decoupled, so nothing stops a handler from sending the wrong type and causing a deserialization failure at runtime. Define a helper returning workflow::Token<T> so both sides share the same token string and payload type at compile time:

rust
use dust::workflow::Token;pub fn decision(expense_id: i64) -> Token<Decision> {    Token::new(format!("expenses.{expense_id}.decision"))}

The workflow can then wait without specifying a turbofish, and the handler is type-checked against Decision:

rust
// In the workflow...let decided = run.wait_for(decision(self.expense_id)).await?;// In the route's handler...workflow::resume(decision(expense_id), Decision::Approved).await?;

Plain strings remain supported wherever a token is accepted. Token<T> serializes as its underlying string, so you can store one on models or workflow structs.

Resume URLs

When a route exists solely to resume a workflow, like the approve handler above, dust-framework can generate signed URLs for you in two styles.

workflow::resume_url(token, value) returns a ResumeUrl representing a signed link that embeds a fixed payload, such as an "Approve" button in an email. ResumeUrl implements Display and Serialize, so you can call .to_string() or pass it directly into a mailable, template, or JSON payload:

rust
use dust::mail;use dust::time::ToSpan;use dust::workflow;let token = format!("expenses.{}.decision", self.expense_id);run.step("email the manager", async {    let approval_url = workflow::resume_url(&token, Decision::Approved)?        .expires(3.days())        .to_string();    mail::to(&self.manager_email)        .send(ApproveExpenseMail { approval_url })        .await}).await?;let decision = run.wait_for::<Decision>(&token).await?;

Webhook URLs

workflow::webhook_url(token) generates a signed callback URL that an external service can POST JSON to in order to resume your workflow. For example, in the step below, we send an uploaded receipt's URL along with a signed callback URL to an external receipt scanning service, then pause the workflow until the scanner POSTs back the scanned total in cents:

rust
use dust::http::client;use serde::Deserialize;use serde_json::json;#[derive(Deserialize)]pub struct Scan {    pub total_cents: i64,}let token = format!("expenses.{}.scan", self.expense_id);run.step("request receipt scan", async {    let callback_url = workflow::webhook_url(&token)?.to_string();    client::post("https://scanner.example.com/scans")        .json(json!({ "receipt_url": self.receipt_url, "callback_url": callback_url }))        .ensure_successful()        .await?;    Ok(())}).await?;let scan = run.wait_for::<Scan>(&token).await?;

Webhook requests whose body is not valid JSON receive a 400 response while the run keeps waiting. By default, the workflow decodes the body as T during its next advance, failing the run if the schema does not match.

Customizing the response

By default, dust-framework serves these URLs automatically and responds with 202 Accepted (or 404 Not Found when no active run owns the token). To return a custom view, JSON payload, or redirect instead, chain respond with one of your route handlers and its parameters, and accept workflow::Resume<T> as the handler's final parameter:

rust
use dust::prelude::*;use dust::view::View;use dust::workflow::{self, Resume, Resumed};pub async fn decided(    Params(expense_id): Params<i64>,    resume: Resume<Decision>,) -> View {    let approved = matches!(resume.value, Decision::Approved);    let already_decided = resume.outcome == Resumed::NotFound;    view(        "expenses.decided",        data! {            expense_id => expense_id,            approved => approved,            already_decided => already_decided,        },    )}
rust
let approval_url = workflow::resume_url("expenses.42.decision", Decision::Approved)?    .expires(3.days())    .respond(expenses::decided, 42)?;

Extracting Resume<T> verifies the signature, resumes the workflow before your handler runs, and provides the decoded payload. Invalid or expired signatures return 403 without invoking the handler. resume.outcome is Resumed::NotFound if no unfinished run owns the token, such as when a user clicks the link again after the run has finished. Routes that do not extract Resume<T> fail to compile with respond. Route middleware runs beforehand, so attaching Authenticate ensures only signed-in users can resume the run.

Because the signature only proves that dust-framework generated the URL and not who opened it, anyone with the link can trigger it, including automated email link scanners. For sensitive approvals, protect the route with Authenticate or link to a confirmation page that calls workflow::resume on form submission.

Inboxes

run.wait_for waits for a single value, whereas run.inbox_for::<T>(token) lets a workflow receive multiple messages over time. Each call to next() suspends the run until another message arrives on that token, delivering messages in arrival order.

For example, suppose a large expense requires sign-off from two different managers. The workflow below notifies the approvers and loops over incoming Vote messages, rejecting the expense immediately if anyone votes no, approving it once two distinct managers vote yes, or expiring if five days pass between votes:

rust
use std::collections::HashSet;use dust::queue::Queueable;use dust::time::ToSpan;use dust::workflow::{Run, workflow};use serde::{Deserialize, Serialize};#[derive(Serialize, Deserialize)]pub struct Vote {    pub approver_id: i64,    pub approve: bool,}#[derive(Serialize, Deserialize)]pub enum Outcome {    Approved,    Rejected,    Expired,}#[derive(Queueable)]pub struct ApproveLargeExpense {    pub expense_id: i64,}#[workflow]impl ApproveLargeExpense {    async fn handle(self, run: &Run) -> dust::Result<Outcome> {        let mut votes = run.inbox_for::<Vote>(format!("expenses.{}.votes", self.expense_id));        run.step("ask the approvers", self.ask_approvers()).await?;        let mut approvers = HashSet::new();        while let Some(vote) = votes.next().timeout(5.days()).await? {            if !vote.approve {                return Ok(Outcome::Rejected);            }            approvers.insert(vote.approver_id);            if approvers.len() == 2 {                return Ok(Outcome::Approved);            }        }        Ok(Outcome::Expired)    }}

Each approver's vote is delivered via workflow::resume(format!("expenses.{expense_id}.votes"), vote) in a route handler. The loop exits when your code returns or breaks, or when .timeout(span) elapses and next() returns None.

Once a read times out, dust-framework records that timeout so execution continues normally with any steps after the loop, and replays exit the loop at the same point even if late messages arrive afterward. Because the timeout applies per read, calling next() again after a timeout continues listening and receives any messages that arrive later without skipping them.

You can also build resume and webhook URLs for an inbox token. Because every request appends another message, clicking a link twice sends two votes, so deduplicate by approver ID as the HashSet above does rather than counting raw messages.

The first next() claims the token for the run, as wait_for does, and the inbox then delivers every message sent to the token, including messages that arrive while the run is busy with a step. To keep messages sent before the first read, claim the token at the start. Because messages replay on every advance, a run may read from a single inbox at most 1,000 times before failing.

Inspecting and cancelling runs

workflow::find loads a run by ID, returning its status, steps, and output or error. RunInfo implements Serialize, so a handler can return it directly as JSON for a progress page:

rust
use dust::prelude::*;use dust::workflow::{self, RunId, RunInfo};pub async fn show(Params(run_id): Params<RunId>) -> dust::Result<Json<RunInfo>> {    let run = workflow::find(run_id).await?.or_abort(404)?;    Ok(Json(run))}

RunInfo provides status(), steps() with attempt counts and timing, output::<T>(), error(), attributes(), and waiting_for(). On a wait record, timed_out() distinguishes timed-out waits from resumed ones.

Call workflow::cancel(run_id) to stop an active run and dispatch RunCancelled, matching the workflow:cancel command. Any currently executing step finishes, and no further steps start. You can optionally attach a reason that appears in workflow:show, RunInfo::error(), and the RunCancelled event:

rust
workflow::cancel(run_id).reason("the customer closed their account").await?;

RunId is a UUID that binds and decodes directly as a uuid database column, so you can store it on a model to track or inspect a run later. Add a table.uuid("onboarding_run_id").nullable() column in your migration, then add a RunId field to your model:

rust
use dust::model::{model, update};use dust::workflow::{self, RunId};#[model]pub struct User {    pub id: i64,    pub onboarding_run_id: Option<RunId>,}// When starting the workflow...let run_id = OnboardUser { user_id: user.id }.start().await?;update!(user { onboarding_run_id: Some(run_id) }).await?;// Later, when inspecting or cancelling the run...if let Some(run_id) = user.onboarding_run_id {    let run = workflow::find(run_id).await?;}

Commands

Command Description
workflow:list Lists runs, newest first. Filter with --status=failed, --name=users.onboard, and --attribute tenant=acme
workflow:show {id} Displays a run's input, status, attributes, output or error, and each step's attempts, timing, and errors
workflow:retry {id} Resumes a failed run from the failing step while keeping earlier recorded steps intact and resetting the step's retries
workflow:cancel {id} Cancels active runs. Pass --reason="..." to record why
workflow:recover Requeues runs whose sleep, timeout, retry, or resume is due without a pending wake-up job
workflow:prune Removes runs finished more than 24 hours ago, with their steps and resume values. Customize retention with --hours=72

Pass --json to workflow:list or workflow:show {id} for single-line JSON output suitable for scripts and dashboards.

When invoked without IDs, workflow:cancel targets unfinished runs matching --status, --name, and --attribute, capped at --limit which defaults to 50. It prompts for confirmation unless you pass --force:

shell
dust workflow:cancel --attribute tenant=acme --reason="the tenant closed their account"

Because wake-ups are scheduled as delayed queue jobs, a worker crash between persisting a run and enqueueing its wake-up, or a cleared queue, can leave a run stranded. Schedule workflow:recover and workflow:prune in src/console/mod.rs to recover stranded runs and keep your workflow tables clean:

rust
use dust::schedule::{self, Schedule};#[schedule::tasks]fn schedule(schedule: &mut Schedule) {    schedule.command("workflow:recover").every_five_minutes();    schedule.command("workflow:prune").daily();}

Events

dust-framework dispatches events from dust::workflow::events: RunCompleted when a workflow finishes, RunFailed after a permanent failure and its failed hook, and RunCancelled with its reason when a run is cancelled. Failed runs are also reported to your error handler. Any context values captured when the run started, such as the active tenant, are restored before your listeners execute so log entries include them automatically:

rust
use dust::event::{Event, listener};use dust::workflow::events::RunFailed;#[listener]pub async fn log_failed_workflow(event: Event<RunFailed>) {    tracing::error!(run = %event.run_id, error = %event.error, "A workflow run failed");}

Each time a run advances, dust-framework creates a tracing span named after the workflow, such as workflow users.onboard. Each step attempt creates a child span, such as step charge card, recording the run ID, step name, and attempt number. Both spans are marked failed on error, and starting or resuming a run continues the caller's trace so the triggering HTTP request and the workflow's execution appear in the same trace.

Writing a store

To persist workflow runs in another backend, such as DynamoDB, implement dust::workflow::store::Store. dust-framework handles replay orchestration, step retries, serialization, and job dispatching, so a custom store only handles persistence and atomic coordination. Four operations must be atomic: claiming a run lease with a fresh Lease token, assigning token ownership to a single active run, numbering values appended to a token owner's queue, and matching a wait against a pending resume. Each write during an advance (record, wait, stop_waiting, set_attributes, renew, and release) receives that Lease and must reject the write without mutating state if the lease is no longer active. When no active run owns a token, resume must discard the value rather than storing it:

rust
use std::collections::BTreeMap;use std::time::Duration;use dust::time::Timestamp;use dust::workflow::RunId;use dust::workflow::store::{    Claim, Created, Delivery, Entry, Filter, Lease, NewRun, Outcome, RunRecord, Store, Waited,};#[derive(Debug)]pub struct DynamoSettings {    pub table: String,}pub struct DynamoStore {    table: String,    // DynamoDB client...}impl DynamoStore {    pub async fn connect(table: &str) -> dust::Result<Self> {        Ok(Self { table: table.to_owned() })    }}impl Store for DynamoStore {    async fn create(&self, run: NewRun) -> dust::Result<Created> {        // Save the run and claim `run.tokens` unless unique or token conflicts...        Ok(Created::Saved)    }    async fn claim(&self, id: RunId, lease: Duration) -> dust::Result<Claim> {        // Acquire the lease with a fresh `Lease` token and return the run...        Ok(Claim::Ended)    }    async fn record(        &self,        id: RunId,        lease: &Lease,        entry: Entry,    ) -> dust::Result<bool> {        // Upsert the step, sleep, or wait entry while `lease` is active...        Ok(true)    }    async fn wait(        &self,        id: RunId,        lease: &Lease,        token: &str,        number: u32,    ) -> dust::Result<Waited> {        // Claim `token`, register the wait, or return a value while `lease` is active...        Ok(Waited::Waiting)    }    async fn stop_waiting(        &self,        id: RunId,        lease: &Lease,        token: &str,    ) -> dust::Result<bool> {        // Clear the run's wait on `token` after a timeout while `lease` is active...        Ok(true)    }    async fn resume(&self, token: &str, value: String) -> dust::Result<Delivery> {        // Append `value` to the token owner's queue, or discard if unowned...        Ok(Delivery::NotFound)    }    async fn waiting(&self, token: &str) -> dust::Result<Option<RunId>> {        // Return the ID of the run currently waiting on `token`...        Ok(None)    }    async fn set_attributes(        &self,        id: RunId,        lease: &Lease,        attributes: BTreeMap<String, String>,    ) -> dust::Result<bool> {        // Replace the run's stored attributes while `lease` is active...        Ok(true)    }    async fn renew(        &self,        id: RunId,        lease: &Lease,        duration: Duration,    ) -> dust::Result<bool> {        // Extend the run's lease while `lease` is active...        Ok(true)    }    async fn release(        &self,        id: RunId,        lease: &Lease,        outcome: Outcome,        now: Timestamp,    ) -> dust::Result<bool> {        // Apply `outcome`, clear the lease, and free tokens while `lease` is active...        Ok(true)    }    async fn find(&self, id: RunId) -> dust::Result<Option<RunRecord>> {        // Load a run record by ID...        Ok(None)    }    async fn entries(&self, id: RunId) -> dust::Result<Vec<Entry>> {        // Load all recorded entries for the run in order...        Ok(Vec::new())    }    async fn list(&self, filter: Filter) -> dust::Result<Vec<RunRecord>> {        // Query runs matching `filter`, newest first...        Ok(Vec::new())    }    async fn cancel(        &self,        id: RunId,        reason: Option<String>,        now: Timestamp,    ) -> dust::Result<bool> {        // Cancel the run via `RunRecord::cancel` and release its keys...        Ok(false)    }    async fn retry(&self, id: RunId, now: Timestamp) -> dust::Result<bool> {        // Reset a failed run to pending at `now` and clear failed entries...        Ok(false)    }    async fn overdue(&self, now: Timestamp) -> dust::Result<Vec<RunRecord>> {        // Return runs with an expired `wake_at`, lease, or ready wait...        Ok(Vec::new())    }    async fn prune(&self, before: Timestamp) -> dust::Result<u64> {        // Delete runs finished before `before` with their entries and values...        Ok(0)    }}

Register the store driver by name in src/app.rs or a package service provider:

rust
use dust::container::Registrar;use dust::foundation::ServiceProvider;impl ServiceProvider for DynamoWorkflowServiceProvider {    fn register(&self, app: &mut Registrar) {        app.workflow().extend("dynamodb", async |_app, definition| {            let settings = definition.settings::<DynamoSettings>()?;            DynamoStore::connect(&settings.table).await        });    }}

Then configure a store using that driver and select it with WORKFLOW_STORE=dynamodb:

rust
// src/config/workflow.rsuse dust::config::workflow::{StoreConfig, Workflow};use dust::config::{self, Env};#[config::section]fn workflow(env: &Env) -> Workflow {    let mut workflow = Workflow::from_env(env);    workflow.add_store(        "dynamodb",        StoreConfig::custom("dynamodb").settings(DynamoSettings { table: "workflows".into() }),    );    workflow}

Testing

In tests, dust-framework uses the memory workflow store and the sync queue connection by default, so workflow tests require neither database tables nor a running worker.

Faking starts

When testing a route handler that only needs to verify a workflow was started, call workflow::fake() to record starts without saving or executing them:

rust
use dust::testing::prelude::*;use dust::workflow;#[dust::test]async fn registering_starts_onboarding(app: Application) {    let workflows = workflow::fake();    app.post("/register")        .json(json!({ "email": "taylor@example.com" }))        .await        .assert_redirect();    workflows.assert_started::<OnboardUser>();    workflows.assert_started_where::<OnboardUser>(|run| run.user_id == 1);}

The fake also provides assert_started_times::<T>(count) and assert_nothing_started(), remaining active until its handle is dropped.

Running a workflow in a test

app.workflow(..) starts a run and advances it until it completes or suspends. You can then move the clock with app.travel and call run.advance() to simulate a worker waking the run:

rust
use dust::mail;use dust::testing::prelude::*;#[dust::test]async fn onboarding_sends_tips_when_user_has_no_projects(    app: Application,) -> dust::Result<()> {    let mail = mail::fake();    let user = User::factory().create().await?;    let run = app.workflow(OnboardUser { user_id: user.id }).await;    mail.assert_sent::<Welcome>();    run.assert_sleeping();    app.travel(3.days());    run.advance().await;    mail.assert_sent::<GettingStartedTips>();    run.assert_completed();    Ok(())}

Additional assertions on the returned run include assert_completed, assert_completed_with, assert_failed, assert_failed_with(message), assert_retrying(name), assert_step_ran(name), assert_step_not_ran(name), and assert_step_tries(name, count).

Because steps are named, you can stub a step's output directly in a test without faking the underlying service:

rust
let run = app    .workflow(Checkout { order_id: 1 })    .with_step("charge card", Receipt { id: "re_1".into() })    .await;

Stubbed steps record as completed with zero attempts, so run.assert_step_tries("charge card", 0) verifies the stub was used.

Testing waits and resumes

When a workflow pauses at run.wait_for or run.inbox_for, assert the wait token with run.assert_waiting_for(token), then call run.resume(token, value) to deliver a payload and advance the run immediately. Both methods accept either a plain string or a typed Token<T>:

rust
use dust::testing::prelude::*;use crate::workflows::approve_expense::{ApproveExpense, Decision, decision};#[dust::test]async fn approved_expenses_are_paid_out(app: Application) -> dust::Result<()> {    let token = decision(42);    let run = app.workflow(ApproveExpense { expense_id: 42 }).await;    run.assert_waiting_for(&token);    run.resume(token, Decision::Approved)        .await        .assert_step_ran("pay out")        .assert_completed();    Ok(())}

For inboxes, call run.resume once for each incoming message in order:

rust
use crate::workflows::approve_large_expense::{ApproveLargeExpense, Outcome, Vote};let token = "expenses.42.votes";let run = app.workflow(ApproveLargeExpense { expense_id: 42 }).await;run.assert_waiting_for(token);run.resume(token, Vote { approver_id: 1, approve: true })    .await    .assert_waiting_for(token);run.resume(token, Vote { approver_id: 2, approve: true })    .await    .assert_completed_with(Outcome::Approved);

To test an early resume arriving before the run reaches wait_for, claim the token when starting the test run:

rust
let run = app    .workflow(ChargeOrder { order_id: 42 })    .claim("orders.42.charged")    .await;

To test a wait's .timeout(..) branch, travel past the timeout and call run.advance() without resuming:

rust
let run = app.workflow(ApproveExpense { expense_id: 42 }).await;app.travel(4.days());run.advance().await.assert_completed();