Skip to content
NestRS

Queue

Redis-backed durable job queues — handlers declared as methods on any provider, activated by importing one module.

Background work shares the rest of the framework’s shape. A queue handler is a method on any #[injectable] provider, tagged #[process(queue = <Name>Queue, retries)] inside a #[processor] impl block. The decorator brings QueueModule to the queue adapter listing it, which attaches the port’s worker at boot; the worker discovers the reachable methods and runs each with permits of its own. A producer-only app imports no queue adapter and only pushes — same crate, same types, no worker.

A queue is named by a type, not a string. #[queue(name = "...", job = <Payload>)] on a unit struct at the feature port declares the wire name and the payload in one artifact both sides import, so a typo or a mismatched payload is a compile error rather than a job that silently never drains.

Read this section, then start from the working reference: the worker app in Publish — audio transcoding jobs, with the api app as the producer.

The contract — Queue, the Jobs handle a feature pushes through and the JobProducer a backend implements, PushOptions, the #[processor] macro, what one attempt at a job is, and the QueueWorker that runs them — ships in nest-rs-queue. The first-class storage, Redis, ships in nest-rs-redis, written on Redis Streams: RedisQueueModule binds its RedisQueueProducer and the consumer the worker runs jobs through. Both are compilation units, not lines you write: the redis-queue feature below pulls them together, and an app’s manifest names neither.

Terminal window
cargo add nest-rs --features redis-queue

One line in the feature crate’s manifest: redis-queue implies queue and redis — the Redis connection and the queue’s binding over it, the macros, the job timeout and the pipe fold #[process] expands to, together. redis alone is the connection, and compiles no queue.

A job payload declares serde itself; anyhow and tracing come through nest_rs::core::anyhow and nest_rs::core::tracing. nestrs g queue <feature> writes the stanza for you.

One declaration, at the feature port — beside the payload, not inside the queue/ adapter. The producer is usually the port’s own service, so this is the artifact both sides reach for:

crates/features/src/audio/command.rs (from the demo)
use nest_rs::queue::{Queue, queue};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TranscodeCommand {
pub file: Uuid,
}
#[queue(name = "audio", job = TranscodeCommand)]
pub struct AudioQueue;
pub const AUDIO_QUEUE: &str = <AudioQueue as Queue>::NAME;

Re-export both from the feature’s mod.rs: a producer pushes through the marker, so one it cannot reach is a queue it cannot push onto.

The name is 1 to 128 of A-Z a-z 0-9 _ . -, checked when the macro expands: : separates the levels of a key, and whitespace would reach a log field.

A regular #[injectable] service with one decorated method. The #[processor] attribute marks the impl block; #[process] marks the method as a queue consumer.

crates/features/src/audio/queue/processor.rs (from the demo, abridged)
use std::sync::Arc;
use anyhow::Result;
use nest_rs::core::injectable;
use nest_rs::queue::processor;
use crate::audio::{AudioQueue, AudioService, TranscodeCommand};
#[injectable]
pub struct AudioProcessor {
#[inject]
svc: Arc<AudioService>,
}
#[processor]
impl AudioProcessor {
#[process(queue = AudioQueue, retries = 3, concurrency = 4)]
async fn transcode(&self, job: TranscodeCommand) -> Result<()> {
self.svc.transcode(job.file).await?;
Ok(())
}
}

The processor is thin: it owns no business logic of its own — it hands job.file to AudioService::transcode and propagates the result. The same AudioService is what an HTTP producer calls to enqueue, so a single audited choke point describes everything the feature can do. Adapters carry transport mechanics; the service carries intent.

  • #[injectable] makes AudioProcessor a regular DI provider.
  • #[processor] on the impl block orchestrates the per-method #[process] attributes and submits one queue consumer per decorated method.
  • #[process(queue, retries, concurrency)] binds the method to a Queue type, gives it a retry budget, and lets concurrency attempts run side by side on each replica — see How many at once. The job type is read from the one parameter that is neither an Attempt nor a Checkpoint<_>, and the macro asserts it is AudioQueue::Job — a handler consuming the wrong payload is a compile error naming both types. A queue is drained by one method: a second #[process] on the same queue fails the boot naming both.

A job is held to the validator rules of every value it carries once it decodes (validation), and the job argument may bind a pipe: Piped<P> exposes the pipe’s input as the wire payload, runs the pipe after deserialization, and hands the handler the transformed value. Either rejection is a job error that dead-letters at once — the same payload would fail every attempt.

Beside the job, a method may take what the port hands one attempt, recognised by its type, once each and in any order: an Attempt — the job’s id, the one its push’s receipt returned and the same on every attempt, and the attempt’s number from 1 — and a Checkpoint<S>, the job’s saved progress (Retries and failure).

use nest_rs::queue::Attempt;
#[process(queue = NotifyQueue, retries = 3)]
async fn notify(&self, job: NotifyCommand, attempt: Attempt) -> Result<()> {
self.svc.send(&job, &attempt.job_id().to_string()).await
}

A #[process] method runs one attempt at a time per worker replica unless it declares more — concurrency = 4 lets four run side by side in each replica — and throughput beyond that comes from running more replicas. A throttle(limit = 120, window = "1m") caps how many attempts start per window across every replica together, which is the key for a provider’s rate limit. Both, the pool they draw on, and scaling replicas on queue depth, are on Concurrency and scaling.

Two modules, two roles:

  • RedisQueueModule — binds the queue port over the Redis connection: the Jobs handle a feature injects as Arc<Jobs>, and the consumer the worker runs jobs through. Every app that enqueues or runs jobs imports it, and it imports the RedisModule opening that connection (<PREFIX>_REDIS__URL), which a root names only to pin it; a second Valkey is a named instance.
  • QueueModule — from nest_rs::queue, attaches the port’s QueueWorker transport. At boot it discovers the reachable #[process] methods, runs each over the bound consumer, and drains them with the app. Each #[processor] host brings it bare, so the app importing a queue adapter runs its jobs and a producer-only app, which imports none, runs no worker; QueueModule::for_root(cfg) at the root only pins the drain window.
apps/worker/src/module.rs (from the demo, abridged)
use nest_rs::core::module;
// …
use nest_rs::redis::{RedisQueueModule, RedisScheduleModule};
// …
use features::audio::AudioQueueModule;
// …
#[module(
imports = [
// …
RedisQueueModule,
// …
AudioQueueModule,
// …
],
)]
pub struct WorkerModule;

The demo’s worker also opens the database — its notifications job writes a row — runs the notifications purge on a schedule, and serves health probes on HTTP. AudioQueueModule imports the AudioModule port and its processor brings QueueModule, so the app lists only the adapter and the backend binding it chooses — registration is idempotent.

main is the universal skeleton every app shares (Fundamentals), booting WorkerModule.

Terminal window
$ nestrs run dev worker
Terminal window
INFO nest_rs::app: transport attached transport="queue"
INFO nest_rs::queue: mounted host="AudioProcessor" method="transcode" queue="audio" retries=3 concurrency=4
DEBUG features::audio: transcoded file=01a015a9-2520-7f30-8c45-9e1a7b3d5f62 derived_key="transcoded/01a015a9-2520-7f30-8c45-9e1a7b3d5f62" trace_id=01a0deaacf87732d9226abd2af0d5896 span_id=0da7f0208abbae0b
INFO nest_rs::operation: queue.job queue=audio host="AudioProcessor" method="transcode" job_id=01a0deaa-cf87-732d-9226-abd166aa514c backend_id="1790442131336-0" attempt=1 outcome="ok" duration_ms=32.129 trace_id=01a0deaacf87732d9226abd2af0d5896 span_id=0da7f0208abbae0b

The last two lines share the job’s trace_id, and it is the producer’s; the job_id is the one the push returned — see Observability for the full field set.

  • Processors — several queues on one provider, the layers around an attempt, and its one transaction.
  • Producing jobs — typing payloads, the publisher handle, and the rule that keeps a push behind a service.
  • Wiring — RedisModule, RedisQueueModule and QueueModule, and module-gating across a shared features crate.
  • Delays, unique keys and cancels — what a push may declare besides its payload, and a waiting job taken back.
  • The outbox — a push inside a transaction, filed once it commits.
  • Valkey topologies — one server, Sentinel or Cluster, the URL of each, a failover under a running queue, and the ACL each adds.
  • Retries and failure — what an Err means, the retry budget and its backoff, panics, dead-lettering.
  • Long-running jobs — an attempt’s timeout, and a checkpoint to resume from.
  • Wire format — a job another release sealed, across a rolling deploy.
  • Concurrency and scaling — concurrency, throttle, the database pool, and replicas on queue depth with KEDA.
  • Delivery on Redis — where a queue’s keys live, the ACL each role takes, what each capability keeps, and the dead letters.
  • Leases and redelivery — the lease and the fence, a crash, a slow Redis and a shutdown.
  • Writing a queue driver — the contract a non-Redis backend implements.
  • Binding a queue driver — the module an app imports, its budget, its failures, its TLS and the behaviour kit.
  • Observability — the span, its fields, and the lines a worker emits per job.
  • Upgrading queues from 6.x — draining 6.x jobs before 7.0 takes over, and the calls a producer changes.
  • crates/nest-rs-queue/ — the contract: #[queue], #[processor], #[process], Queue, Jobs, JobProducer, PushOptions, PushReceipt, Checkpoint, Capability, and QueueModule with its QueueWorker.
  • crates/nest-rs-redis/ — the Redis storage: RedisModule and its RedisConnection, RedisQueueModule with its RedisQueueProducer and the consumer it binds.
  • Scheduling — recurring work driven by a clock rather than a producer.
  • Events — in-process fan-out, when the work need not outlive the request.
  • Correlation — the trace an enqueue hands to the attempt, across the process boundary.