dust

Queues

Introduction

While building your web application, you may have work that takes too long to do while a user waits, such as transcoding an uploaded podcast or sending a batch of emails. Queues let you defer that work as a job, so your application responds right away while a separate queue worker process handles it in the background.

dust-framework provides a unified queueing API across database, Redis, Amazon SQS, and DUST Cloud managed queues. Each job is a struct with an async handle method that runs when a worker picks it up via dust queue:work.

For lightweight work that does not need to survive a restart, task::background runs in the current process without a queue. To queue an event listener, use queued listeners.

Use this table when you are unsure which background mechanism fits:

Need Reach for
Work that must survive a restart, a deploy, or a provider outage A queued job, described here
A few seconds of work that can be lost if the process exits task::background
A flow that spans days and resumes after a webhook A workflow
Work that runs on a clock The scheduler
Several independent reactions to one action Events and listeners
A listener that calls a slow provider A queued listener

[!NOTE] Every queue driver delivers at least once: a worker may run a job again after a crash, a timeout, or a lost reservation. Write handle so running it twice has the same effect as running it once, and use a stable idempotency key when calling external services.

Connections and queues

Before you dispatch a job, it's important to know the difference between connections and queues. A connection is a backend that keeps jobs, such as your database or a Redis server. A queue is a named list of jobs on a connection, and a connection may have any number of them.

When you dispatch a job without specifying a queue, it's pushed onto the connection's default queue. Using separate queues lets you prioritize work. For example, you may push urgent jobs onto a high queue and instruct your worker to process them first:

shell
dust queue:work --queue=high,default

Configuration

By default, dust-framework uses the database queue connection and stores queued jobs in a jobs table on your default database connection. You can choose a different connection or customize the defaults through your environment variables:

Variable Sets Default
QUEUE_CONNECTION The default connection database
DB_QUEUE_CONNECTION, DB_QUEUE_TABLE, DB_QUEUE The database connection's database connection, table, and default queue The default database connection, jobs, and default
REDIS_QUEUE_CONNECTION, REDIS_QUEUE The redis connection's Redis connection and default queue default and default
DB_QUEUE_FAILED_CONNECTION, DB_QUEUE_FAILED_TABLE Where failed jobs are stored The default database connection and failed_jobs

The Amazon SQS and DUST Cloud connections have their own environment variables.

Drivers

dust-framework includes several built-in queue drivers:

Driver Behavior
database Stores jobs in a table on one of your database connections
redis Stores jobs in Redis. Requires the redis feature
sqs Pushes jobs to Amazon SQS queues. Requires the sqs feature
cloud Pushes jobs to DUST Cloud's managed queues. Requires the sqs feature
sync Runs each job immediately in the current process and returns any error from dispatch
discard Discards dispatched jobs without running them

The sync driver is useful during local development when you don't want to run a separate worker, and dust-framework uses it by default in tests. To disable queued work entirely, set QUEUE_CONNECTION=discard.

The driver you choose changes how delays, ordering, and failed jobs behave:

Driver Delays Ordering Queue depth Failed jobs
database Supported Oldest available job first Exact failed_jobs table
redis Supported Oldest available job first Exact failed_jobs table
sqs Supported; long delays are held by dust Best effort, unless the queue is FIFO Approximate failed_jobs table, which needs a database feature
cloud Supported, through SQS Best effort, unless the queue is FIFO Approximate The DUST Cloud dashboard
sync Ignored; the job runs immediately Immediate, in the current process Not applicable Returned from dispatch
discard Ignored The job is dropped Not applicable None

The jobs table

The database driver stores queued jobs in a jobs table and moves permanently failed jobs to a failed_jobs table so you can inspect and retry them later. New applications create both tables, along with the job batch tables, in their create_jobs_table migration, which holds only the queue::tables! macro:

rust
// database/migrations/0001_01_01_000002_create_jobs_table.rsdust::queue::tables!();

Run your migrations before dispatching jobs:

shell
dust migrate

If you customize DB_QUEUE_TABLE or DB_QUEUE_FAILED_TABLE, replace the macro with the migration it stands for and change the table names to match:

rust
// database/migrations/0001_01_01_000002_create_jobs_table.rsuse dust::db::AnyTransaction;pub async fn migrate(tx: &mut AnyTransaction<'_>) -> dust::Result<()> {    tx.schema()        .create("jobs", |table| {            table.id();            table.string("queue").index();            table.long_text("payload");            table.integer("attempts").default(0);            table.timestamp("reserved_at").nullable();            table.timestamp("available_at");            table.timestamp("created_at");        })        .await?;    tx.schema()        .create("failed_jobs", |table| {            table.id();            table.string("job_id").length(36).unique();            table.string("connection");            table.string("queue");            table.long_text("payload");            table.long_text("error");            table.timestamp("failed_at");            table.index(["connection", "queue", "failed_at"]);        })        .await?;    tx.schema()        .create("job_batches", |table| {            table.string("id").length(36).primary();            table.string("name").nullable();            table.integer("total_jobs");            table.integer("pending_jobs");            table.integer("failed_jobs");            table.long_text("options");            table.timestamp("created_at");            table.timestamp("cancelled_at").nullable();            table.timestamp("finished_at").nullable();        })        .await?;    tx.schema()        .create("job_batch_jobs", |table| {            table.string("batch_id").length(36);            table.string("job_id").length(36);            table.string("status").length(16);            table.primary(["batch_id", "job_id"]);        })        .await}

Permanently failed jobs are written to failed_jobs regardless of which queue driver you use, except on DUST Cloud, where managed queues store failed jobs in the DUST Cloud dashboard so you can inspect, retry, or delete them there instead. If you prefer to discard failed jobs instead of storing them, set queue.failed to FailedJobs::Discard in your queue configuration:

rust
use dust::config::queue::FailedJobs;queue.failed = FailedJobs::Discard;

Redis

To store queued jobs in Redis, enable dust-framework's redis feature in Cargo.toml, configure a Redis connection, and set QUEUE_CONNECTION=redis:

toml
dust-framework = { version = "0.1", features = ["database-postgres", "redis"] }

Store queued jobs in a separate Redis database from your cache, since flushing the cache clears every key in that database. By default, the default Redis connection uses database 0 and the cache connection uses database 1. If your REDIS_URL specifies a database number, both connections share it, so you should configure a dedicated Redis connection for queues. Because dust-framework does not prefix queue keys, separate applications should use their own Redis servers.

Blocking

By default, an idle worker sleeps for --sleep seconds before polling for new jobs. With block_for, the worker instead blocks on Redis for up to that duration and claims a job the moment one is pushed. Configure block_for in your queue configuration:

rust
use dust::config::queue::RedisQueue;queue.add_connection("redis", RedisQueue::from_env(env).block_for(5.seconds()));

block_for is not supported on a Redis Cluster.

Amazon SQS

To use Amazon SQS for your queues, enable dust-framework's sqs feature in Cargo.toml and set QUEUE_CONNECTION=sqs:

toml
dust-framework = { version = "0.1", features = ["database-postgres", "sqs"] }

You can configure the sqs connection using these environment variables:

Variable Description Default
AWS_DEFAULT_REGION The AWS region The region resolved by the AWS SDK, such as AWS_REGION
AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN AWS credentials Credentials resolved by the AWS SDK, such as a container's IAM role
SQS_PREFIX Base URL for your queues, such as https://sqs.us-east-1.amazonaws.com/123456789012 Look up each queue's URL by name
SQS_SUFFIX Suffix appended to every queue name, such as -production None
SQS_QUEUE The connection's default queue default
AWS_ENDPOINT_URL_SQS Custom SQS endpoint, such as a local emulator AWS's endpoint for the region
SQS_OVERFLOW_ENABLED, SQS_OVERFLOW_STORE Stores payloads that exceed SQS limits in a cache store Off, using the default cache store

Each queue name maps directly to an SQS queue. With the prefix and suffix above, the emails queue resolves to https://sqs.us-east-1.amazonaws.com/123456789012/emails-production. Because dust-framework does not create SQS queues automatically, create them in AWS first. To enable long polling so idle workers wait for new jobs efficiently, configure each queue's receive message wait time in AWS up to 20 seconds.

You may dispatch jobs with delays longer than SQS's 15-minute limit; dust-framework holds them until they are due. Because failed jobs from SQS are written to the failed_jobs table, the sqs driver requires a database feature unless you discard failed jobs.

FIFO queues

Any queue name ending in .fifo is treated as an SQS FIFO queue, processing jobs within each message group one at a time in dispatch order. When SQS_SUFFIX is set, dust-framework inserts it before .fifo, so orders.fifo becomes orders-production.fifo. Use on_group to assign a message group; jobs dispatched without one share a single group:

rust
use dust::prelude::*;pub async fn ship(Params(order_id): Params<i64>) -> dust::Result<Redirect> {    let order = Order::find_or_fail(order_id).await?;    ShipOrder { order_id }        .dispatch()        .on_queue("orders.fifo")        .on_group(format!("customer-{}", order.customer_id))        .await?;    Ok(Redirect::back())}

SQS FIFO queues drop any job whose deduplication ID matches another job dispatched within the last five minutes. By default, dust-framework generates a unique ID for each dispatch so duplicate dispatches run separately. To deduplicate jobs instead, pass your own deduplication_id:

rust
ShipOrder { order_id }    .dispatch()    .on_queue("orders.fifo")    .deduplication_id(format!("ship-order-{order_id}"))    .await?;

SQS FIFO queues do not support per-message delays, so dispatch delayed jobs to a standard queue.

Large payloads

SQS messages are limited to 1 MiB, and dispatching a larger job returns an error. To support larger payloads, set SQS_OVERFLOW_ENABLED=true. Oversized payloads are then stored in your cache store while the SQS message carries only the cache key. Set SQS_OVERFLOW_STORE to choose a specific store, or omit it to use your default store. Make sure you use a shared cache store such as database or redis so all workers can read the payload.

DUST Cloud

On DUST Cloud, managed queues provide fully managed, auto-scaling queue infrastructure with zero AWS setup. Because managed queues scale automatically to absorb sudden bursts of jobs, you don't need to provision SQS queues, manage IAM credentials, or size queue servers yourself. Applications with managed queues receive a preconfigured cloud connection automatically; enable the sqs feature and set QUEUE_CONNECTION=cloud to use it as your default connection.

Managed queues are backed by SQS, so they support all sqs driver features, including FIFO queues and large payloads. You can enable payload overflow from DUST Cloud's queue settings or with CLOUD_QUEUE_OVERFLOW_ENABLED and CLOUD_QUEUE_OVERFLOW_STORE. The DUST Cloud dashboard tracks each job's progress and stores permanently failed jobs instead of writing them to your failed_jobs table, allowing you to inspect, retry, or delete failed jobs directly from the dashboard.

Defining your own connections

When you need an additional connection, such as a reports connection that stores its jobs in a report_jobs table on the reporting database connection, create a src/config/queue.rs configuration file. Start from Queue::from_env to inherit the default connections and add your own. Multiple connections may share the same driver with different settings:

rust
// src/config/queue.rsuse dust::config::queue::{DatabaseQueue, Queue};use dust::config::{self, Env};#[config::section]fn queue(env: &Env) -> Queue {    let mut queue = Queue::from_env(env);    queue.add_connection(        "reports",        DatabaseQueue::new()            .connection("reporting")            .table("report_jobs")            .queue("reports"),    );    queue}

Then add the file to src/config/mod.rs:

rust
mod queue;

You may then dispatch jobs to the connection by name, as Connections, queues, and delays shows.

Creating jobs

A job is a struct that derives Queueable, paired with a #[job] impl containing its handle method. You can place jobs in any module, such as src/jobs/; dust-framework discovers them automatically, so there is nothing to register.

For example, consider a podcast publishing application that processes each uploaded episode before publishing it. This job receives a podcast's ID and loads the Podcast model when it runs:

rust
// src/jobs/process_podcast.rsuse dust::queue::{Queueable, job};use crate::models::Podcast;#[derive(Queueable)]pub struct ProcessPodcast {    pub podcast_id: i64,}#[job]impl ProcessPodcast {    async fn handle(self) -> dust::Result<()> {        let podcast = Podcast::find_or_fail(self.podcast_id).await?;        // Process the uploaded podcast...        Ok(())    }}

Because queued jobs are serialized until a worker executes them, a job should carry plain data or models rather than database connections or open file handles.

handle consumes self and returns () or dust::Result<()>. Alongside self, it may accept services via Inject<T>, config sections via Section<T>, and the current &Attempt in any order:

rust
use dust::container::Inject;use dust::queue::job;use crate::models::Podcast;use crate::services::AudioProcessor;#[job]impl ProcessPodcast {    async fn handle(self, processor: Inject<AudioProcessor>) -> dust::Result<()> {        let podcast = Podcast::find_or_fail(self.podcast_id).await?;        processor.process(&podcast).await?;        Ok(())    }}

Each job executes in a fresh application context, so helpers like config, resolve, URL generation, and once all work, though there is no HTTP request or session. dust-framework propagates any context values present at dispatch time, such as the active tenant, into the job's execution context.

Models in jobs

Instead of storing an ID and loading the record yourself, a job may store models directly as fields. When dispatched, dust-framework serializes only each model's primary key. Before handle runs, the worker reloads the model from the database so your job always works with fresh data:

rust
// src/jobs/process_podcast.rsuse dust::queue::{Queueable, job};use crate::models::Podcast;#[derive(Queueable)]pub struct ProcessPodcast {    pub podcast: Podcast,}#[job]impl ProcessPodcast {    async fn handle(self) -> dust::Result<()> {        // Process self.podcast...        Ok(())    }}

Pass the model directly when dispatching, as in ProcessPodcast { podcast }.dispatch().await?. Option<Podcast> and Vec<Podcast> fields also store keys and reload the models when the job runs. Relationships are not serialized, so load any relationships handle needs, such as self.podcast.load(Podcast::episodes).await?.

If a model's row no longer exists when the job runs, the worker deletes the job without running it. For example, there's no reason to process a podcast that its author has since deleted, and retrying the job couldn't bring the record back anyway. The worker logs each job it deletes this way at the info level, naming the missing model and its keys, and the JobProcessed event for the job reports the MissingModels outcome. For a Vec<Podcast> field, the worker leaves out the deleted records and runs the job with the remaining models.

When the deleted job is part of a chain, the rest of the chain doesn't run, and the chain's catch callback isn't called, since no job failed. In a batch, the job and the rest of its chain count as skipped, so the batch can still finish and run its then callbacks.

If a deleted record means something went wrong, such as a payment job whose invoice should never disappear, or a chain that must undo its earlier steps in catch, add fail_when_missing_models to fail the job permanently with a MissingModels error instead:

rust
#[job(fail_when_missing_models)]impl ChargeInvoice {    // ...}

Even when using fail_when_missing_models, the failed job's failed hook does not run, since the worker can't load the job's models to pass to it.

Job names

dust-framework records each job's name in the queue payload and resolves the job type by that name when a worker executes it. By default, the name is the type's module path, such as app::jobs::ProcessPodcast. If you rename or move the struct, jobs already sitting on the queue will fail to resolve. To keep a job's identifier stable across refactors, assign an explicit name:

rust
#[job(name = "podcasts.process")]impl ProcessPodcast {    // ...}

Jobs already on the queue retain the fields they were serialized with. When adding a new field, annotate it with #[serde(default)] so previously queued jobs still deserialize. When renaming a field, preserve the previous name with #[serde(alias = "...")]:

rust
#[derive(Queueable)]pub struct TranscribeEpisode {    #[serde(alias = "podcast_id")]    pub episode_id: i64,    #[serde(default)]    pub include_timestamps: bool,}

If you add a new model field to a job struct, wrap it in Option or Vec when using #[serde(default)], since models themselves do not have a default value.

Dispatching jobs

Once you've defined a job, dispatch it by calling the dispatch method generated by #[job] and awaiting it. By default, awaiting pushes the job onto your default queue connection. This handler creates a podcast and queues it for background processing:

rust
use dust::model::create;use dust::prelude::*;use crate::jobs::ProcessPodcast;#[dust::input]#[validate(anyone)]pub struct NewPodcast {    #[validate(required, max_length(255))]    title: String,}pub async fn store(Valid(form): Valid<NewPodcast>) -> dust::Result<Redirect> {    let podcast = create!(Podcast { title: &form.title }).await?;    ProcessPodcast { podcast }.dispatch().await?;    Ok(Redirect::to("/podcasts"))}

Awaiting dispatch returns the job's JobId, matching the ID exposed by attempt.id() and the failed jobs commands. You may dispatch jobs from route handlers, console commands, scheduled tasks, event listeners, or other jobs.

Connections, queues, and delays

Before awaiting a dispatch, you can specify a connection, choose a queue, or delay when the job becomes available:

rust
ProcessPodcast { podcast }    .dispatch()    .on_connection("redis")    .on_queue("podcasts")    .delay(10.minutes())    .await?;

delay accepts a duration span, a Timestamp, or a ZonedDateTime. The sync connection ignores delays and runs the job immediately.

To route every dispatch of a job to a specific queue by default, set the queue option on the job itself, such as #[job(queue = "podcasts")]. Calling on_queue at dispatch time overrides that default.

Database transactions

When you dispatch a job inside a database transaction, dust-framework waits until the transaction commits before pushing the job onto the queue, and discards it if the transaction rolls back. This ensures a worker never attempts to process a job before its database records are visible:

rust
use dust::db;use dust::model::create;db::transaction(async |_tx| {    let podcast = create!(Podcast { title: &form.title }).await?;    ProcessPodcast { podcast }.dispatch().await?;    Ok(())}).await?;

Inside the transaction, dispatch returns the JobId immediately and pushes the job once the transaction commits. If pushing to the queue fails after commit, db::transaction returns that error while the database changes remain committed, as described in after-commit work. In that case, retry dispatching the job rather than rerunning the transaction.

Events dispatched inside a transaction also wait until the transaction commits before running.

Synchronous dispatching

If you want to execute a job immediately within the current process instead of pushing it to a queue, call dispatch_sync:

rust
ProcessPodcast { podcast }.dispatch_sync().await?;

The job runs through its normal lifecycle, and dispatch_sync returns any error produced by handle. Unlike dispatch, it executes immediately even inside an open database transaction, so the job sees uncommitted writes from that transaction.

Dispatching jobs in bulk

To enqueue many jobs at once, pass them to queue::bulk. dust-framework sends them in as few backend requests as possible rather than pushing each job individually:

rust
use dust::queue;let subscriber_ids = Subscriber::query()    .filter(Subscriber::podcast_id.eq(podcast.id))    .pluck(Subscriber::id)    .await?;let jobs = subscriber_ids.into_iter().map(|subscriber_id| NotifySubscriber {    podcast_id: podcast.id,    subscriber_id,});queue::bulk(jobs).on_queue("notifications").await?;

queue::bulk accepts a single job, an iterator of jobs of the same type, or a tuple of jobs of different types, returning their JobIds in order. If pushing fails partway through, earlier jobs in the batch may already be queued. When you need to track a group of jobs together or run callbacks once they complete, use a job batch instead.

Debounced jobs

When a job may be dispatched repeatedly in quick succession, you may only want the latest dispatch to execute. For example, if a post is edited three times in a few seconds, its search index only needs to be updated once. Configure debounce_for on #[job] and implement debounce_id to group dispatches that should supersede each other:

rust
use dust::prelude::*;use dust::queue::{Queueable, job};#[derive(Queueable)]pub struct UpdateSearchIndex {    pub post_id: i64,}#[job(debounce_for = 30.seconds())]impl UpdateSearchIndex {    fn debounce_id(&self) -> i64 {        self.post_id    }    async fn handle(self) -> dust::Result<()> {        // Update the post's search index...        Ok(())    }}

Each dispatch waits 30 seconds before becoming eligible to run. When its turn arrives, the worker discards it if a newer dispatch for the same post is still pending. debounce_id may return any type implementing Display; omitting it causes every dispatch of that job type to supersede earlier ones.

If edits arrive continuously, each dispatch would reset the window indefinitely. To cap the total delay, set max_wait. Once the oldest pending dispatch reaches that age, the next dispatch runs immediately:

rust
#[job(debounce_for = 30.seconds(), max_wait = 2.minutes())]

dust-framework tracks debounce state in your default cache store, so make sure you use a shared store such as database or redis. Because the sync connection executes jobs immediately, it does not debounce dispatches.

Retries and timeouts

By default, a job that returns an error or panics is attempted once and not retried. You can configure retries, backoff delays, and execution timeouts on #[job]:

rust
use dust::prelude::*;use dust::queue::job;#[job(    queue = "podcasts",    tries = 3,    backoff = [10.seconds(), 1.minutes()],    timeout = 2.minutes(),)]impl ProcessPodcast {    // ...}

With these options, a failing job waits 10 seconds before its second attempt and one minute before its third before failing permanently. When backoff is a list, each entry sets the wait before the corresponding retry, and the final duration repeats for any subsequent retries.

Option Description Default
queue = "podcasts" Default queue when on_queue is not specified at dispatch The connection's default queue
tries = 3 Maximum number of attempts, including releases 1
backoff = 30.seconds() Wait before retrying, or a list such as [10.seconds(), 1.minutes()] No delay
timeout = 2.minutes() Maximum duration for a single attempt 60 seconds
retry_for = 1.hours() Time window after dispatch during which the job may be retried, replacing tries No limit
max_errors = 3 Maximum failed attempts before stopping retries Governed by tries
debounce_for, max_wait Deduplication window for debounced jobs Not debounced
name = "podcasts.process" Stable job name stored in the queue payload The type's path
fail_when_missing_models Fails the job when a model row is missing Deletes the job

Job options are attached to the job type, so updating them applies to jobs already sitting on the queue once you deploy the new code.

When a job exceeds its timeout, the worker cancels it at its next .await point and fails the attempt with a JobTimedOut error. Because Rust futures can only be cancelled at .await points, move CPU-bound or blocking work into task::spawn_blocking.

When an attempt fails and the job will be retried, the worker logs the error as a warning. Once a job fails permanently, the worker records it in the failed jobs table, invokes its failed hook, and reports the error through your error handler. A job with a retry_for fails permanently as soon as its window would end before its next attempt, and the failed job keeps that attempt's error.

Limiting errors

A job that releases itself repeatedly, such as one waiting on an external rate limit, may need many attempts while still failing quickly if unexpected errors occur. Pair retry_for with max_errors so the job can keep releasing within the time window while failing permanently after a set number of errors:

rust
#[job(retry_for = 1.hours(), max_errors = 3)]impl SyncContacts {    // ...}

Workers track error counts in your default cache store, so use a shared store such as database or redis.

Inside a job

A job's handle method may accept an &Attempt to inspect the current execution. number() returns the 1-based attempt count, and id() returns the job's JobId:

rust
use dust::queue::{Attempt, job};#[job(tries = 3)]impl ProcessPodcast {    async fn handle(self, attempt: &Attempt) -> dust::Result<()> {        tracing::info!(id = %attempt.id(), run = attempt.number(), "processing podcast");        // ...        Ok(())    }}

You can also inspect the current job's metadata with name(), connection(), and queue().

Method Returns
number() The 1-based attempt number, including releases
id() The job's JobId
name() The job's stored name
connection() The connection processing the job
queue() The queue the job came from

Releasing, deleting, and failing

Attempt also lets a job control its own lifecycle. For example, this job deletes itself if its podcast was archived, and releases itself back onto the queue if the audio upload is still in progress:

rust
use dust::prelude::*;use dust::queue::{Attempt, job};#[job(retry_for = 1.hours())]impl ProcessPodcast {    async fn handle(self, attempt: &Attempt) -> dust::Result<()> {        if self.podcast.archived {            attempt.delete();            return Ok(());        }        if !self.podcast.uploaded {            attempt.release(30.seconds());            return Ok(());        }        // Process the uploaded podcast...        Ok(())    }}
  • release(delay) pushes the job back onto its queue to run again after the given delay. Releases count toward tries, so jobs that release frequently should use retry_for instead, as shown in Limiting errors.
  • delete() removes the job from the queue without retrying it.
  • fail(error) fails the job permanently without further retries.

These instructions take effect when handle returns Ok(()). If handle returns an error, the attempt fails even if you called release. The one exception is a rate limit error: returning TooManyAttempts automatically releases the job back onto the queue until the rate limit allows it to run.

Handling failures

When a job fails permanently, you may want to notify the user or clean up partial work. Add an async failed method alongside handle that accepts &dust::Error along with any of the same injected arguments handle accepts:

rust
use dust::model::update;use dust::queue::job;#[job(tries = 3)]impl ProcessPodcast {    async fn handle(self) -> dust::Result<()> {        // Process the uploaded podcast...        Ok(())    }    async fn failed(self, error: &dust::Error) -> dust::Result<()> {        let mut podcast = self.podcast;        update!(podcast { failure: Some(error.to_string()) }).await?;        Ok(())    }}

failed receives a fresh instance deserialized from the stored payload, with any model fields reloaded, so in-memory mutations made during handle are not carried over.

Job middleware

When multiple jobs share the same guard or rate-limiting logic, such as staying within a mail provider's sending limit or skipping unverified users, extract it into job middleware instead of repeating it in every handle method. To stop a job from overlapping with itself, build a middleware around a cache lock.

Defining middleware

Job middleware is an async function annotated with #[middleware] from dust::queue. It receives next representing the remainder of the pipeline and returns dust::Result<()>. For example, this middleware rate limits mail jobs to 14 per second across all workers, releasing any job over the limit back onto the queue until capacity is available:

rust
use dust::queue::{Next, middleware};use dust::rate_limit::{self, Limit};#[middleware]pub async fn mail_rate_limit(next: Next) -> dust::Result<()> {    rate_limit::attempt("mail", Limit::per_second(14)).await??;    next.run().await}

next.run() executes the rest of the pipeline and returns its result, allowing your job middleware to run code before and after handle, or skip it altogether. Before next, a middleware function may accept any injected parameters that handle accepts, including &Attempt to release, delete, or fail the job.

To pass data from the job into a middleware function, such as a user ID, declare those parameters after next. Parameters before next are injected by dust-framework, while parameters after next become arguments you pass when assigning the middleware to a job, such as skip_unverified_users(self.user_id). For example, this middleware deletes the job when the user has not verified their email address:

rust
use dust::queue::{Attempt, Next, middleware};use crate::models::User;#[middleware]pub async fn skip_unverified_users(    attempt: &Attempt,    next: Next,    user_id: i64,) -> dust::Result<()> {    let verified = User::find(user_id)        .await?        .is_some_and(|user| user.email_verified_at.is_some());    if !verified {        attempt.delete();        return Ok(());    }    next.run().await}

Middleware can also intercept errors returned by the job. For example, this middleware releases the job back onto the queue when handle fails rather than failing the attempt:

rust
#[middleware]pub async fn release_on_error(attempt: &Attempt, next: Next) -> dust::Result<()> {    if let Err(error) = next.run().await {        tracing::warn!(%error, "releasing the job after an error");        attempt.release(1.minutes());    }    Ok(())}

Assigning middleware to jobs

To attach middleware to a job, add a middleware method to its #[job] impl taking &self and returning a single middleware or a tuple of them. Pass any job-specific parameters in order:

rust
use dust::queue::{IntoMiddleware, job};#[job(retry_for = 1.hours())]impl SendNewsletter {    fn middleware(&self) -> impl IntoMiddleware {        (skip_unverified_users(self.user_id), mail_rate_limit)    }    async fn handle(self) -> dust::Result<()> {        // Send the newsletter...        Ok(())    }}

Job middleware executes in the order listed, so here skip_unverified_users runs first, wrapping mail_rate_limit, which wraps handle.

To apply a middleware only when a condition is met, wrap it in an Option; dust-framework skips any None entries:

rust
fn middleware(&self) -> impl IntoMiddleware {    (        skip_unverified_users(self.user_id),        self.retry_errors.then_some(release_on_error),    )}

To share a set of middleware across multiple jobs, return a MiddlewareGroup from a helper function and return it from each job's middleware method:

rust
use dust::queue::{IntoMiddleware, MiddlewareGroup, job};pub fn mail() -> MiddlewareGroup {    MiddlewareGroup::new().with(mail_rate_limit).with(release_on_error)}#[job]impl SendNewsletter {    fn middleware(&self) -> impl IntoMiddleware {        mail()    }    async fn handle(self) -> dust::Result<()> {        // Send the newsletter...        Ok(())    }}

A job's timeout applies to its middleware and handle method together. Middleware runs wherever the job executes, including on the sync connection and in test attempts.

Job chains

Job chaining lets you specify a sequence of jobs that run one after another. Each job is dispatched only after the previous job succeeds; if any job fails, the remaining jobs in the chain will not run. Pass the jobs to queue::chain as a tuple and await it:

rust
use dust::prelude::*;use dust::queue;use crate::models::Podcast;pub async fn publish(podcast: Podcast) -> dust::Result<Redirect> {    queue::chain((        ProcessPodcast { podcast: podcast.clone() },        OptimizePodcast { podcast_id: podcast.id },        ReleasePodcast { podcast_id: podcast.id },    ))    .await?;    Ok(Redirect::back())}

queue::chain also accepts a single job or an iterator of jobs of the same type, and you can append more jobs with then when constructing a chain dynamically:

rust
let mut chain = queue::chain(ProcessPodcast { podcast: podcast.clone() });if !podcast.transcribed {    chain = chain.then(TranscribePodcast { podcast_id: podcast.id });}chain.then(ReleasePodcast { podcast_id: podcast.id }).await?;

Each job retains its configured options, so it is retried on its own before the chain continues. A job that releases itself pauses the chain until it succeeds, while a job that deletes itself lets the chain continue. A job deleted because a model's row is gone ends the chain without running subsequent jobs.

By default, each job in the chain uses its own connection and queue. To send every job in the chain to the same connection or queue, call on_connection and on_queue. Calling delay delays the first job in the chain:

rust
queue::chain((    ProcessPodcast { podcast: podcast.clone() },    OptimizePodcast { podcast_id: podcast.id },)).on_connection("redis").on_queue("podcasts").await?;

[!NOTE] Design each job in a chain to be idempotent. If a job succeeds but the worker fails to enqueue the next job in the chain, the worker will retry the completed job.

Adding jobs to the chain

A running job can add more jobs to its active chain through &Attempt. prepend_to_chain inserts one or more jobs to run immediately next, while append_to_chain adds them to the end of the chain:

rust
use dust::queue::{Attempt, job};#[job]impl ProcessPodcast {    async fn handle(self, attempt: &Attempt) -> dust::Result<()> {        // ...        // Run next...        attempt.prepend_to_chain(TranscribePodcast { podcast_id: self.podcast.id });        // Run at the end of the chain...        attempt.append_to_chain((            NotifyHosts { podcast_id: self.podcast.id },            UpdatePodcastFeed { podcast_id: self.podcast.id },        ));        Ok(())    }}

Both methods accept a single job, a tuple of jobs of different types, or an iterator of jobs of the same type. When you pass multiple jobs to prepend_to_chain, they run in the order listed before any remaining jobs in the chain. Added jobs are only enqueued if the current job succeeds or deletes itself. If the current job wasn't part of a chain, adding jobs starts a new chain.

Chain failures

When a job in a chain fails permanently, the remaining jobs do not run. To react to a chain failure, register a callback with catch:

rust
queue::chain((    ProcessPodcast { podcast: podcast.clone() },    OptimizePodcast { podcast_id: podcast.id },)).catch(PodcastFailed { podcast_id: podcast.id }).await?;

Like a job, a callback is a struct deriving Queueable so dust-framework can store it alongside the chain. Annotate its impl with #[callback] and implement an async catch method that receives the failing error:

rust
use dust::model::update;use dust::queue::{Queueable, callback};use crate::models::Podcast;#[derive(Queueable)]pub struct PodcastFailed {    pub podcast_id: i64,}#[callback]impl PodcastFailed {    async fn catch(self, error: &dust::Error) -> dust::Result<()> {        let mut podcast = Podcast::find_or_fail(self.podcast_id).await?;        update!(podcast { failure: Some(error.to_string()) }).await?;        Ok(())    }}

The worker invokes catch immediately, before running the failed job's failed hook. Because callbacks run inline rather than as queued jobs, they are not retried; any error they return is reported to your error handler. If one of a callback's model rows has been deleted, the worker skips the callback, unless you add fail_when_missing_models to its #[callback] attribute to report a MissingModels error instead. For long-running or retryable cleanup, dispatch a job from the callback instead.

If you later retry the failed job and it succeeds, the chain resumes with the remaining jobs.

Job batches

dust-framework's job batching lets you execute a group of jobs in parallel and then run callbacks once the entire batch has completed. For example, if a user uploads a CSV file of 300 contacts, you can split the import into three jobs of 100 rows each, process them concurrently across your workers, and mark the import complete once all three finish.

Pass the jobs to queue::batch and await it. Here, ImportCsv is a job that imports a slice of rows:

rust
use dust::prelude::*;use dust::queue;pub async fn start(Params(import_id): Params<i64>) -> dust::Result<Redirect> {    let batch_id = queue::batch([        ImportCsv { import_id, rows: 1..=100 },        ImportCsv { import_id, rows: 101..=200 },        ImportCsv { import_id, rows: 201..=300 },    ])    .name("Import CSV")    .then(ImportFinished { import_id })    .catch(ImportFinished { import_id })    .await?;    Ok(Redirect::to(format!("/imports/{import_id}/batches/{batch_id}")))}

queue::batch accepts an iterator of jobs of the same type or a tuple of jobs of different types. Awaiting dispatches every job and returns the batch's BatchId, which you can use to inspect its progress. Jobs in a batch may finish in any order. Call on_connection and on_queue to route every job in the batch to a specific connection and queue.

The batches tables

dust-framework tracks batch progress in two database tables, job_batches and job_batch_jobs. Your application's create_jobs_table migration creates them alongside the jobs table, so run your migrations before dispatching your first batch.

Batch records are stored on your default database connection regardless of which queue driver runs the jobs.

Batch callbacks

You can register callbacks for three points in a batch's lifecycle. The worker invokes the matching method on your callback:

Method Invoked when Optional arguments
then Every job in the batch succeeds &Batch
catch The first job in the batch fails permanently &Batch and &dust::Error
finally Every job has finished, whether it succeeded, failed, or was skipped &Batch

For example, this callback marks the Import model complete or records the failure reason:

rust
use dust::model::update;use dust::queue::{Queueable, callback};use crate::models::Import;#[derive(Queueable)]pub struct ImportFinished {    pub import_id: i64,}#[callback]impl ImportFinished {    async fn then(self) -> dust::Result<()> {        let mut import = Import::find_or_fail(self.import_id).await?;        update!(import { completed: true }).await?;        Ok(())    }    async fn catch(self, error: &dust::Error) -> dust::Result<()> {        let mut import = Import::find_or_fail(self.import_id).await?;        update!(import { failure: Some(error.to_string()) }).await?;        Ok(())    }}

The &Batch parameter reflects the batch's state at the moment the callback runs. You may call then, catch, and finally multiple times to register additional callbacks.

For a single-purpose callback, you can annotate an async function with #[callback] instead. Owned parameters such as import_id are stored with the batch, while framework parameters such as &Batch are injected when it runs:

rust
use dust::queue::Batch;#[callback]async fn log_import(import_id: i64, batch: &Batch) {    tracing::info!(        import_id,        jobs = batch.total_jobs(),        failed = batch.failed_jobs(),        "import finished",    );}queue::batch(jobs).finally(log_import(import_id)).await?;

Chains and batches

A batch may contain job chains. Each chain runs its jobs sequentially while running in parallel with the other items in the batch:

rust
queue::batch((    queue::chain(ReleasePodcast { podcast_id: 1 })        .then(SendReleaseNotification { podcast_id: 1 }),    queue::chain(ReleasePodcast { podcast_id: 2 })        .then(SendReleaseNotification { podcast_id: 2 }),)).then(ReleaseFinished).await?;

A batch can also be a step inside a chain. The chain advances once every job in the batch finishes:

rust
queue::chain(FlushPodcastCache)    .then(queue::batch([ReleasePodcast { podcast_id: 1 }, ReleasePodcast { podcast_id: 2 }]))    .then(queue::batch([        SendReleaseNotification { podcast_id: 1 },        SendReleaseNotification { podcast_id: 2 },    ]))    .await?;

If the batch is cancelled, such as when one of its jobs fails, the outer chain stops as well.

Adding jobs and cancelling batches

A job inside a batch can dynamically add more jobs to its batch through &Attempt. For a large import, your handler can dispatch a single starter job that splits the file in the background rather than building thousands of jobs during the HTTP request:

rust
use dust::queue::{Attempt, Queueable, job};#[derive(Queueable)]pub struct SplitImport {    pub import_id: i64,}#[job]impl SplitImport {    async fn handle(self, attempt: &Attempt) -> dust::Result<()> {        let import = Import::find_or_fail(self.import_id).await?;        let jobs = (0..import.total_rows)            .step_by(100)            .map(|start| ImportCsv { import_id: import.id, rows: start + 1..=start + 100 });        attempt.add_to_batch(jobs);        Ok(())    }}

The batch remains open until all added jobs finish as well. To cancel the batch from within a job, call attempt.cancel_batch(); workers skip any remaining pending jobs, and the batch's then callbacks will not run. Outside a job, cancel a batch with queue::cancel_batch(batch_id).await?.

Inspecting batches

Use queue::find_batch to look up a batch by ID and report its progress. It returns None if no matching batch exists:

rust
use dust::prelude::*;use dust::queue::{self, Batch, BatchId};pub async fn show(Params(batch_id): Params<BatchId>) -> dust::Result<Json<Batch>> {    let batch = queue::find_batch(batch_id).await?.or_abort(404)?;    Ok(Json(batch))}

Batch implements Serialize, so you can return it directly as JSON. It provides progress as a percentage from 0 to 100, along with total_jobs, pending_jobs, failed_jobs, is_finished, and is_cancelled.

Batch failures

By default, when any job in a batch fails permanently, dust-framework cancels the batch, invokes its catch callbacks, and skips the remaining jobs. To keep processing remaining jobs even if some fail, call allow_failures:

rust
queue::batch(jobs).allow_failures().catch(ImportFinished { import_id }).await?;

With allow_failures, catch callbacks run on the first failure, while then callbacks run only after every failed job has been retried and succeeded. You can retry all failed jobs in a batch with queue:retry-batch. Batches without allow_failures are cancelled on their first failure and cannot be retried this way:

shell
dust queue:retry-batch 0199f3c2-5b8d-7f3e-9a16-2d4b8e0c7f53

A retried job may add new jobs to a finished batch or resume its chain. In that case, the batch stays open until those jobs finish and then runs its finally callbacks again, so write finally callbacks to be idempotent.

Pruning batches

Completed batch records stay in the database until you prune them. queue:prune-batches removes batches that finished more than 24 hours ago. Pass --hours to keep them longer, and schedule the command daily in src/console/mod.rs:

rust
use dust::schedule::{self, Schedule};#[schedule::tasks]fn schedule(schedule: &mut Schedule) {    schedule.command("queue:prune-batches --hours=48").daily();}

Pass --unfinished=N to also prune unfinished batches older than N hours, or --cancelled=N for cancelled batches. Only prune unfinished batches you no longer plan to retry, since their callbacks will never run once deleted.

Running the worker

Start a queue worker with the queue:work command to begin processing queued jobs:

shell
dust queue:work

The worker runs continuously until you stop it, printing each job's name without the leading app::, its outcome, and its duration:

text
◆ jobs::ProcessPodcast  412.4ms
▲ jobs::SendInvoice retrying  18.2ms
  the payment service timed out

Before starting a worker, run your migrations so the jobs and failed_jobs tables exist. The worker prints each job's outcome as it goes, which makes it the first place to look when a job does not seem to run.

Worker options

By default, the worker processes the default queue on your default connection. You can pass a specific connection name or list multiple queues in priority order. When listing multiple queues, the worker drains higher-priority queues before pulling from lower-priority ones:

shell
dust queue:work redisdust queue:work --queue=high,default
Option Description Default
[connection] The queue connection to process The default connection
--queue=high,default Queues to process, in priority order The connection's default queue
--concurrency=4 Number of jobs to process concurrently 1
--sleep=3 Seconds to wait before polling again when no jobs are available 3
--max-jobs=1000 Exit after processing this many jobs No limit
--max-time=3600 Exit after running for this many seconds No limit
--stop-when-empty Exit once all monitored queues are empty Off

Before exiting, the worker finishes any jobs currently in flight.

Queue workers also run your application's ticks alongside the HTTP server. If a tick only applies to web requests (such as flushing counters buffered by HTTP handlers), restrict it with .when(|host| host.is_server()).

Worker concurrency

To process multiple jobs concurrently within a single worker process, pass --concurrency:

shell
dust queue:work --concurrency=8

Because concurrent jobs share one worker process, concurrency works best for I/O-bound jobs waiting on the network or database. Offload CPU-heavy or blocking work, such as image processing, to task::spawn_blocking so it does not stall other jobs. You may also run multiple worker processes across one or more servers; each job is claimed by only one worker.

Running workers in production

In production, run your queue workers under a process supervisor such as systemd or Supervisor so they restart automatically if they exit:

ini
# /etc/systemd/system/app-worker.service
[Unit]
Description=Queue worker
After=network.target
 
[Service]
WorkingDirectory=/srv/app
ExecStart=/srv/app/bin/your-app queue:work --concurrency=4
Restart=always
KillSignal=SIGTERM
TimeoutStopSec=150
 
[Install]
WantedBy=multi-user.target

When the worker receives SIGTERM, it stops claiming new jobs and waits for in-flight jobs to finish. Set your supervisor's stop timeout to more than twice your longest job's timeout so a job timing out on its final attempt still has time to run its failed hook.

If a worker is killed abruptly or its server crashes, another worker reclaims its in-flight jobs roughly a minute later. The interrupted run counts as one attempt.

Running workers on DUST Cloud

When deploying to DUST Cloud with managed queues, you don't need to configure systemd, Supervisor, or manually size worker clusters. DUST Cloud continuously monitors your queues and scales worker concurrency automatically based on queue depth, job latency, and throughput.

During traffic spikes, Cloud spins up additional workers to drain backlogs before wait times build up. When your queues are idle, workers can scale down to zero so you aren't paying for idle compute between bursts. Workers also roll over automatically on every deployment, and the DUST Cloud dashboard provides real-time visibility into queue depth, throughput, and failed jobs.

Restarting workers

Because workers keep running the binary they started with, restart them on every deploy. Running queue:restart signals all running workers to finish their current jobs and exit gracefully so your process supervisor can boot them with the new release:

shell
dust queue:restart

Restart signals are coordinated through your default cache store, so use a shared store such as database or redis.

Pausing queues

To stop workers from claiming jobs from a specific queue without shutting the workers down, such as during maintenance, pause the queue. Specify connection:queue, or pass only the queue name to target the default connection:

shell
dust queue:pause database:emailsdust queue:pause emails

Workers finish any jobs already running and leave new jobs on the paused queue untouched until you resume it with queue:continue:

shell
dust queue:continue database:emails

Pass --all to queue:pause or queue:continue to pause or resume every queue across all connections. Like queue:restart, pause state is shared through your default cache store.

Counting jobs

To monitor queue depth, call sizes on the queue manager, such as from a scheduled health check that alerts you when a queue backs up:

rust
use dust::queue;if let Some(sizes) = queue::manager().sizes("database", "emails").await? {    tracing::info!(        pending = sizes.pending,        running = sizes.reserved,        total = sizes.total(),        "emails",    );}

pending reports jobs ready to run, delayed reports jobs waiting out a delay, and reserved reports jobs currently being processed. sizes returns None for drivers that do not support queue depth queries, and SQS counts are approximate.

Failed jobs

Things don't always go as planned. When a job fails permanently, dust-framework records it in the failed_jobs table. Run queue:failed to inspect failed jobs, ordered with the most recent first:

shell
dust queue:failed

To retry a failed job, pass its ID to queue:retry, or pass all to retry every failed job. Retried jobs are pushed back onto their original connection and queue with a fresh attempt count:

shell
dust queue:retry 0199f3c2-5b8d-7f3e-9a16-2d4b8e0c7f53dust queue:retry all

To delete a single failed job, pass its ID to queue:forget. To clear the entire table, run queue:flush, or pass --hours=48 to delete only jobs that failed more than 48 hours ago. You can schedule queue:flush to keep the table manageable:

shell
dust queue:forget 0199f3c2-5b8d-7f3e-9a16-2d4b8e0c7f53dust queue:flush --hours=48

To delete all pending jobs from a queue, run queue:clear:

shell
dust queue:clear redis --queue=emails

[!NOTE] When using DUST Cloud managed queues, permanently failed jobs are tracked in the DUST Cloud dashboard rather than your database's failed_jobs table. You can inspect error details and payloads, retry individual or bulk failed jobs, and delete failed records directly from the dashboard without running CLI commands against your server.

Events

Workers dispatch events in dust::queue::events as they process jobs. Listeners run in the job's context, inheriting any context values it was dispatched with or added during execution.

Both JobProcessed and JobFailed include an event.job field of type JobInfo describing the job: id, name, connection, queue, and the 1-based attempt number.

JobProcessed fires after every attempt with event.duration and event.outcome, which is one of Succeeded, Released, Deleted, Debounced, MissingModels, Retrying, or Failed. A job the worker deleted because a model's row was deleted reports MissingModels, so you may count or alert on those jobs without failing them. For example, this listener logs a warning whenever a job takes longer than 30 seconds:

rust
use dust::event::{Event, listener};use dust::prelude::*;use dust::queue::events::JobProcessed;#[listener]pub async fn warn_about_slow_jobs(event: Event<JobProcessed>) -> dust::Result<()> {    if event.duration > 30.seconds() {        tracing::warn!(            job = %event.job.name,            queue = %event.job.queue,            duration = %event.duration,            "slow job",        );    }    Ok(())}

JobFailed fires once a job fails permanently, after its failed hook has run. Because failed jobs are already reported to your error handler, listen for JobFailed when you want custom alerting or metrics. Along with event.job, it provides event.error, which you can inspect with is::<E>() or downcast_ref::<E>():

rust
use dust::event::{Event, listener};use dust::queue::events::JobFailed;use dust::queue::{JobTimedOut, MissingModels};#[listener]pub async fn notify_on_job_failure(event: Event<JobFailed>) -> dust::Result<()> {    let reason = if event.error.is::<JobTimedOut>() {        "timed out"    } else if event.error.is::<MissingModels>() {        "lost its models"    } else {        "failed"    };    tracing::error!(        id = %event.job.id,        job = %event.job.name,        queue = %event.job.queue,        attempt = event.job.attempt,        error = %event.error,        "job {reason}",    );    Ok(())}

Common error types you can match on event.error include:

Error type Cause
dust::queue::JobTimedOut The attempt exceeded the job's configured timeout
dust::queue::MissingModels A model field's database record was deleted before a job with fail_when_missing_models ran
dust::rate_limit::TooManyAttempts A rate-limited job could not run before its retry_for window expired
Application errors Any error type returned from handle or passed to attempt.fail(error)

The sync connection and dispatch_sync do not dispatch these events.

Writing a driver

Packages can support additional queue backends, such as Cloudflare Queues, by registering a custom driver. Implement Driver to push, reserve, and clear jobs, and ReservedJob to manage each reserved job's lease and completion. dust-framework's worker handles retries, timeouts, and failed job recording automatically, renewing active reservations every HEARTBEAT against a LEASE duration so a driver only manages job storage and reservation.

Here is an example driver for Cloudflare Queues' HTTP pull API using dust-framework's HTTP client:

rust
use std::time::Duration;use dust::http::client::{self, PendingRequest};use dust::queue::{Driver, LEASE, Reservation, ReservedJob};use serde::Deserialize;use serde_json::json;#[derive(Debug, Clone)]pub struct CloudflareSettings {    pub account_id: String,    pub token: String,}#[derive(Clone)]pub struct CloudflareDriver {    settings: CloudflareSettings,}impl CloudflareDriver {    fn queue_api(&self, queue: &str) -> PendingRequest {        client::base_url(format!(            "https://api.cloudflare.com/client/v4/accounts/{}/queues/{queue}",            self.settings.account_id        ))        .token(&self.settings.token)        .accept_json()        .ensure_successful()    }}pub struct CloudflareJob {    driver: CloudflareDriver,    queue: String,    payload: String,    attempts: u32,    lease_id: String,}#[derive(Deserialize)]struct Envelope<T> {    result: T,}#[derive(Deserialize)]struct PullResult {    messages: Vec<PulledMessage>,}#[derive(Deserialize)]struct PulledMessage {    body: String,    attempts: u32,    lease_id: String,}#[derive(Deserialize)]#[serde(rename_all = "camelCase")]struct AckResult {    #[serde(default)]    ack_count: u64,    #[serde(default)]    retry_count: u64,}impl Driver for CloudflareDriver {    type Job = CloudflareJob;    async fn push(        &self,        queue: &str,        payload: String,        delay: Duration,    ) -> dust::Result<()> {        self.queue_api(queue)            .post("/messages")            .json(json!({                "body": payload,                "content_type": "text",                "delay_seconds": delay.as_secs(),            }))            .await?;        Ok(())    }    async fn reserve(&self, queues: &[String]) -> dust::Result<Option<CloudflareJob>> {        for queue in queues {            let response: Envelope<PullResult> = self                .queue_api(queue)                .post("/messages/pull")                .json(json!({                    "batch_size": 1,                    "visibility_timeout_ms": LEASE.as_millis(),                }))                .await?                .json()?;            if let Some(message) = response.result.messages.into_iter().next() {                return Ok(Some(CloudflareJob {                    driver: self.clone(),                    queue: queue.clone(),                    payload: message.body,                    attempts: message.attempts,                    lease_id: message.lease_id,                }));            }        }        Ok(None)    }    async fn clear(&self, queue: &str) -> dust::Result<u64> {        self.queue_api(queue)            .post("/purge")            .json(json!({ "delete_messages_permanently": true }))            .await?;        Ok(0)    }}impl ReservedJob for CloudflareJob {    fn queue(&self) -> &str {        &self.queue    }    fn payload(&self) -> &str {        &self.payload    }    fn attempts(&self) -> u32 {        self.attempts    }    async fn renew(&self) -> dust::Result<Reservation> {        // Cloudflare Queues sets the visibility window on pull rather than renewing per lease...        Ok(Reservation::Held)    }    async fn delete(&self) -> dust::Result<Reservation> {        let response: Envelope<AckResult> = self            .driver            .queue_api(&self.queue)            .post("/messages/ack")            .json(json!({ "acks": [{ "lease_id": self.lease_id }] }))            .await?            .json()?;        if response.result.ack_count > 0 {            Ok(Reservation::Held)        } else {            Ok(Reservation::Lost)        }    }    async fn release(&self, delay: Duration) -> dust::Result<Reservation> {        let response: Envelope<AckResult> = self            .driver            .queue_api(&self.queue)            .post("/messages/ack")            .json(json!({                "retries": [{                    "lease_id": self.lease_id,                    "delay_seconds": delay.as_secs(),                }],            }))            .await?            .json()?;        if response.result.retry_count > 0 {            Ok(Reservation::Held)        } else {            Ok(Reservation::Lost)        }    }}

Return Reservation::Lost from renew, delete, or release if the reservation lapsed and another worker claimed the job, signaling the current worker to stop touching it. You may also override Driver::bulk for batched pushes, Driver::sizes to report QueueSizes, and ReservedJob::fail if your backend records failed jobs itself.

Register your driver by name in a service provider's register method:

rust
use dust::container::Registrar;use dust::foundation::ServiceProvider;impl ServiceProvider for CloudflareQueueServiceProvider {    fn register(&self, app: &mut Registrar) {        app.queue().extend("cloudflare", async |_app, definition| {            let settings = definition.settings::<CloudflareSettings>()?.clone();            Ok(CloudflareDriver { settings })        });    }}

Then configure a custom connection referencing that driver, passing any custom settings your driver expects:

rust
use dust::config::queue::ConnectionConfig;queue.add_connection(    "cloudflare",    ConnectionConfig::custom("cloudflare")        .queue("emails-queue-id")        .settings(CloudflareSettings {            account_id: env.get("CLOUDFLARE_ACCOUNT_ID").unwrap_or_default(),            token: env.get("CLOUDFLARE_API_TOKEN").unwrap_or_default(),        }),);

[!NOTE] dust-framework invokes your driver factory once per configured connection on first use and caches that instance for the lifetime of the application, sharing it across concurrent requests and workers. Drivers built on TCP protocols should hold a connection pool or reconnecting client internally, while drivers built on dust::http::client share dust-framework's pooled HTTP client automatically.

Testing

When testing code that dispatches jobs, you typically want to verify that the right job was queued without executing it, and then test the job's logic independently.

In tests, dust-framework routes all jobs to the sync connection by default, even when a job, chain, batch, or queued notification specifies another connection. Unless you fake the queue, dispatched jobs execute immediately. To test against a real queue backend, override QUEUE_CONNECTION in your test configuration.

Faking the queue

Call queue::fake() to intercept dispatched jobs without pushing or executing them, then assert against the returned fake:

rust
use dust::queue;use dust::testing::prelude::*;#[dust::test]async fn uploading_a_podcast_queues_it_for_processing(app: Application) {    let queue = queue::fake();    app.post("/podcasts").json(json!({ "title": "Episode 1" })).await.assert_redirect();    queue.assert_pushed::<ProcessPodcast>();    queue.assert_pushed_times::<ProcessPodcast>(1);    queue.assert_pushed_where::<ProcessPodcast>(|job| {        job.podcast.title == "Episode 1" && job.queue() == "default"    });}

The predicate receives the deserialized job along with id(), connection(), queue(), and delay(). connection() reflects the connection requested at dispatch, and delay() compares directly with duration spans such as job.delay() == 10.minutes(). You can also assert with assert_not_pushed::<T>(), assert_not_pushed_where, and assert_nothing_pushed().

The fake respects database transactions and records jobs only after commit. It also round-trips each job through serialization so serialization bugs fail your test immediately. Model fields such as job.user are preserved without relationships and do not require database access inside the predicate.

To fake only specific job types, or fake everything except certain jobs, chain only or except. Unfaked jobs dispatch normally:

rust
let queue = queue::fake().only::<ProcessPodcast>();let queue = queue::fake().except::<SendInvoice>();

The fake remains active until its handle is dropped.

Testing a job

To test a job's handle method directly, execute a single attempt with app.job(..) and assert on the outcome. For example, this test verifies that ProcessPodcast releases itself when the upload has not finished:

rust
use dust::model::create;use dust::testing::prelude::*;#[dust::test]async fn uploading_podcasts_are_released(app: Application) -> dust::Result<()> {    let podcast = create!(Podcast { title: "Episode 1", uploaded: false }).await?;    app.job(ProcessPodcast { podcast })        .await        .assert_released_after(30.seconds());    Ok(())}

The job runs through its middleware as it would on a worker. Call attempt(n) to simulate a specific retry count for attempt.number(). Available outcome assertions include assert_succeeded, assert_released, assert_released_after, assert_deleted, assert_failed, and assert_failed_with::<E>(). Test attempts run once without retrying or invoking failed.

Testing chains

The queue fake records each chain alongside its first job. Use assert_chained with a tuple of job types to verify the chain's order:

rust
let queue = queue::fake();app.post("/orders/42/ship").await.assert_redirect();queue.assert_chained::<(ShipOrder, RecordShipment, UpdateInventory)>();

To inspect the payloads of subsequent jobs in the chain, call chain().get::<T>(index) inside assert_pushed_where:

rust
queue.assert_pushed_where::<ShipOrder>(|job| {    job.chain().get::<RecordShipment>(0).is_some_and(|next| next.order_id == 42)});

To test a job that dynamically modifies its chain, run it with app.job(..) and call assert_chained with a job type or tuple of job types:

rust
app.job(ProcessPodcast { podcast })    .await    .assert_succeeded()    .assert_chained::<TranscribePodcast>();

Testing batches

The queue fake intercepts dispatched batches without writing to the batch tables or executing their jobs. Assert on dispatched batches with assert_batched:

rust
let queue = queue::fake();app.post("/imports").json(json!({ "file": "contacts.csv" })).await.assert_redirect();queue.assert_batched(|batch| {    batch.name() == Some("Import CSV")        && batch.jobs().len() == 3        && batch.jobs().get::<ImportCsv>(0).is_some_and(|job| job.rows == (1..=100))});

Inside the predicate, you can also inspect then(), catch(), finally(), and allows_failures(). Call queue.assert_nothing_batched() to verify no batches were dispatched.

Because the fake does not execute batch callbacks, you can test callbacks directly with app.callback. By default, the callback receives a synthetic single-job batch, which you can customize with total_jobs, failed_jobs, and related builders:

rust
app.callback(ImportFinished { import_id: 7 }).total_jobs(3).then().await?;

To test a job that adds jobs to its batch or cancels it, execute it with app.job(..).in_batch() and assert with added_to_batch() or assert_batch_cancelled():

rust
let result = app.job(ImportCsv { rows: 1..=100 }).in_batch().await;result.assert_succeeded();assert_eq!(result.added_to_batch().len(), 1);assert!(    result        .added_to_batch()        .get::<ImportCsv>(0)        .is_some_and(|job| job.rows == (101..=200)));app.job(ImportCsv { rows: 1..=0 })    .in_batch()    .await    .assert_batch_cancelled();