Expand description
Builder types for composing and building workers.
The WorkerBuilder component is the recommended
way to construct Worker instances in a flexible and
composable manner.
The builder pattern enables customization of various parts of a worker, in the following order:
- Setting a backend that implements the
Backendtrait - Adding application state via
Data - Decorating the service pipeline with middleware
- Handling lifecycle events with
on_event - Providing task processing logic using
buildthat implementsIntoWorkerService.
The IntoWorkerService trait can be used to convert a function or a service into a worker service. The following implementations are provided:
- For async functions via
task_fn - For any type that implements the
Servicetrait forT: Task - For workflows via
apalis-workflow
§Basic usage
async fn task(job: u32, count: Data<usize>, worker: WorkerContext) {
println!("Received job: {job:?}");
worker.stop().unwrap();
}
let worker = WorkerBuilder::new("rango-tango")
.backend(in_memory)
.data(0usize)
.on_event(|worker, ev| {
println!("On Event = {:?}", ev);
})
.build(task);
worker.run().await.unwrap();§Order
The order in which you add layers affects how tasks are processed. Layers added earlier are wrapped by those added later.
§Why does order matter?
Each layer wraps the previous one, so the outermost layer is applied last. This means that middleware added later can observe or modify the effects of earlier layers. For example, tracing added before retry will see all retries as a single operation, while tracing added after retry will log each retry attempt separately.
For example:
WorkerBuilder::new()
.enable_tracing()
.retry(RetryPolicy::retries(3))
.build(task);In this case, tracing is applied before retry. The tracing span may not reflect the correct attempt count.
Reversing the order:
WorkerBuilder::new()
.retry(RetryPolicy::retries(3))
.enable_tracing()
.build(task);Now, retry is applied first, and tracing wraps around it. The tracing span will correctly capture retries.
Tip: Add layers in the order you want them to wrap task processing.
Structs§
- Worker
Builder - Declaratively builds a
Worker