Durable Workflows
Part 2 · Laravel Rust. Write multi-day processes as one async function. Learn steps, sleeping, waiting for outside events, and when workflows beat plain queued jobs.
Some things in a café happen over days. A customer signs up for the Rusty Bean loyalty card. You want to send a welcome email now, wait three days, and then, only if they have not ordered yet, send a coupon. Doing that with queued jobs alone is awkward.
Durable workflows let you write that whole story as one function, and Laravel makes sure it survives restarts, deploys and crashes. In this lesson you will learn what they are, how to read one, and when to reach for them.
Note
Workflows are brand new in Laravel, and Laravel Rust is in beta. This lesson follows the official Workflows guide (opens in new tab). The café names and the helper methods on self are our own illustrations.
The problem: long stories are painful with jobs
Using queued jobs alone, the loyalty-card story needs:
- A job that sends the welcome email and dispatches another job delayed by three days.
- A column in your database remembering how far along each customer is.
- A scheduled “sweep” command that finds customers whose follow-up got lost.
That is a lot of plumbing for four lines of intent. Laravel’s own announcement describes exactly this pain.
What a workflow looks like
use laravel::queue::Queueable;use laravel::time::ToSpan;use laravel::workflow::{Run, workflow};
#[derive(Queueable)]pub struct WelcomeCustomer { pub customer_id: i64,}
#[workflow]impl WelcomeCustomer { async fn handle(self, run: &Run) -> laravel::Result<()> { run.step("send welcome email", self.send_welcome_email()).await?;
run.sleep(3.days()).await?;
if run.step("count orders", self.count_orders()).await? == 0 { run.step("send coupon", self.send_coupon()).await?; }
Ok(()) }}It reads like a normal function. Here is what each part means:
- A workflow is a struct deriving
Queueablewith a#[workflow]block, much like a job. The struct’s fields (customer_id) are the workflow’s input. Place each workflow in its own file undersrc/workflows/. runis a handle to this particular run: one customer’s journey through the workflow.run.step("name", work)executesworkonce and saves the result under that name.workis an async function that returnslaravel::Result<T>. (send_welcome_email,count_ordersandsend_couponare methods you would write on the struct.)run.sleep(3.days())pauses the run for three days.- Plain Rust
ifdecides what happens next, based on a saved result.
How it works under the hood
According to the guide, workflows run on your existing queue workers, so there is no separate service to deploy. Each time a run “advances”, it is really a queued job. The worker calls handle from the top, quickly replays every step that already has a saved result without redoing it, and runs the next unrecorded step.
When the run reaches a sleep (or a wait, or a retry delay), it suspends. The worker finishes and schedules the next advance for later. No worker sits idle, so a run sleeping for two weeks costs nothing while it waits. It also survives deployments and restarts, because its progress is stored, not held in memory.
Think of the café’s order board. Each ticket records which drinks are done. If the barista goes on a break, the next one reads the ticket and carries on from the first unfinished drink.
Setting up
Workflows need a queue worker on a connection that supports delays (database, redis or sqs). They also need five tables. Add a migration whose only line is a macro:
laravel::workflow::tables!();Then run laravel migrate. In tests, Laravel uses an in-memory store instead, so you do not need these tables there.
Starting a run
#[workflow] generates a start method, like dispatch for jobs:
use crate::workflows::WelcomeCustomer;
WelcomeCustomer { customer_id: customer.id }.start().await?;Awaiting it saves the run and queues its first advance. If a form might be submitted twice, you can prevent duplicate runs with .unique("loyalty.42").
Steps: retries and idempotency
By default a failing step is retried up to three times, with delays of 10 seconds and then 1 minute. You can tune that:
let receipt = run .step("charge card", self.charge_card()) .tries(5) .timeout(30.seconds()) .await?;Warning
If a worker crashes after a step did its outside work but before Laravel saved the result, the step runs again. Make steps safe to repeat. The guide shows passing workflow::current_step().key() as an idempotency key to payment APIs, so the same charge is never made twice.
The rules of handle
Because handle is replayed from the top, it must do the same thing every time. The guide lists these rules:
- Do all input and output (database queries, HTTP calls, reading the clock) inside steps.
- Branch only on the workflow’s inputs and on recorded results of steps, sleeps and waits.
- Keep step names unique within a run.
Important
Renaming a step makes Laravel run it again under the new name. Avoid renaming steps that have side effects (like sending an email) while runs are in flight.
Waiting for the outside world
A workflow can also stop and wait for something that happens elsewhere, such as a manager approving a catering order:
let decision = run .wait_for::<Decision>(format!("catering.{}.decision", self.order_id)) .timeout(3.days()) .await?;Elsewhere, a route handler wakes the run by calling workflow::resume(token, Decision::Approved).await?. With .timeout(3.days()) the wait returns an Option: None means nobody answered in time. The guide notes that a wait token is an identifier, not a secret, so protect resume routes with authorization.
Managing and testing runs
The CLI has workflow:list, workflow:show {id}, workflow:retry {id} and workflow:cancel {id}. The guide suggests scheduling workflow:recover and workflow:prune for housekeeping. In tests, app.workflow(..) starts a run, app.travel(3.days()) moves the clock, and run.advance().await wakes it. You will see this in Testing Your App.
When should you use a workflow?
| Situation | Use |
|---|---|
| One slow task, such as sending a receipt | A queued job |
| A tiny chore, fine to lose | task::background |
| Several steps over hours or days, with waiting, branching or approvals | A workflow |
Try it yourself
- Sketch a workflow
PickupReminder { order_id: i64 }that sends a reminder email, sleeps for 2 hours, then (using a step) checks if the order was picked up, and sends a second reminder if not. Method bodies can be left out. - Why must the “was it picked up?” check be inside a step?
Show solution
#[workflow]impl PickupReminder { async fn handle(self, run: &Run) -> laravel::Result<()> { run.step("first reminder", self.send_reminder()).await?; run.sleep(2.hours()).await?;
if !run.step("check pickup", self.was_picked_up()).await? { run.step("second reminder", self.send_reminder()).await?; }
Ok(()) }}handlereplays from the top on every advance. A database query outside a step could give a different answer on replay. Inside a step, the answer is recorded once and replayed unchanged.
Recap
- A workflow is a struct with
#[workflow]whosehandledescribes a long process as one async function. run.stepruns work once and saves its result.run.sleepandrun.wait_forsuspend the run without using a worker.- Workflows run on your existing queue workers and survive deploys and restarts.
handleis replayed from the top, so do all I/O inside steps and keep it deterministic.- Use jobs for single tasks and workflows for multi-step stories that wait.
What’s next
Next, a quick tour of three big features: email, realtime updates and Inertia. Continue to Mail, Broadcasting and Inertia.
0 of 35 lessons complete