Docs / Digging Deeper / Workflows
Workflows
Introduction
A workflow is a long-lived process written in a single class: it can charge a card, sleep for three days, wait for a manager's decision or a webhook, and pick up where it left off after a deploy or a crash.
// app/Workflows/OnboardUser.ts
import { Workflow, type Run } from '@laraflare/workflow';
export class OnboardUser extends Workflow {
constructor(public userId: number) {
super();
}
async handle(run: Run): Promise<void> {
await run.step('send welcome email', () => this.sendWelcomeEmail());
await run.sleep({ days: 3 });
if (await run.step('count projects', () => this.countProjects()) === 0) {
await run.step('send tips', () => this.sendTips());
}
}
}
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.
Note
Cloudflare Queues delay a message by at most twelve hours. A run that sleeps longer is woken every twelve hours and goes back to sleep until it is due.
Installation
Workflows are a package of their own. Install it, then tell the queue worker where your workflows live, as it already knows where your jobs live:
npm install @laraflare/workflow
// bootstrap/app.ts
.withJobs(
(name) => import(`../app/Jobs/${name}.ts`),
(name) => import(`../app/Models/${name}.ts`),
(name) => import(`../app/Workflows/${name}.ts`),
)
The Workflow Tables
Runs are kept in five tables: workflow_runs, workflow_steps, workflow_waits, workflow_resumes and workflow_attributes. Publish the migration that creates them, then migrate:
npx artisan vendor:publish --tag=workflow-migrations
npx artisan migrate
To store these tables on a separate database connection, set DB_WORKFLOW_CONNECTION.
Choosing a Store
By default, runs are stored in the database store, switching to the memory store while APP_ENV is testing, 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. To change the stores, publish the configuration file:
npx artisan vendor:publish --tag=workflow-config
Defining Workflows
A workflow is a class that extends Workflow and has a handle method, which receives the Run. The workflow's properties are its input: they are serialized as a queued job's properties are, so models are stored by their keys and fetched again. Its name in the store is its class name, unless the class gives one in workflowName. A failed method is called once if the run fails:
import { Workflow, type Run } from '@laraflare/workflow';
export class Checkout extends Workflow {
static override workflowName = 'orders.checkout';
constructor(public orderId: number) {
super();
}
async handle(run: Run): Promise<void> {
await run.step('charge card', () => Payments.charge(this.orderId));
}
async failed(error: unknown): Promise<void> {
await Slack.alert(`checkout ${this.orderId} failed: ${error}`);
}
}
Starting Runs
Call start on a workflow to start a run. It answers the run's ID:
import { OnboardUser } from '../app/Workflows/OnboardUser';
const runId = await new OnboardUser(user.id).start();
Like a job, a run may be sent to another connection or queue, or delayed:
const runId = await new OnboardUser(user.id)
.start()
.onConnection('database')
.onQueue('workflows')
.delay({ hours: 1 });
Starting a Run Once
unique starts the run only if no active run has the same key. The await then answers a Started, which says whether the run is new or the one that was already running:
const started = await new ApproveExpense(expenseId).start().unique(`expenses.${expenseId}`);
if (started.isExisting()) {
Log.info(`the expense is already waiting for approval (${started.id})`);
}
Attributes
Attributes label a run, so you can find and cancel runs by them:
const runId = await new OnboardUser(user.id)
.start()
.attribute('tenant', 'acme')
.attribute('plan', 'pro');
A run may change its attributes as it goes:
await run.step('charge card', () => this.chargeCard());
run.setAttribute('phase', 'shipping');
Deleting a Run's Data
purgeWhenFinished deletes the run's input, steps and resume values as soon as it finishes. A purged run can no longer be found or retried:
const runId = await new VerifyBankAccount(accountId).start().purgeWhenFinished();
Steps
A step runs a function once and records its result; when the run replays, the step answers the recorded result without running the function again. Its name must be unique within the run:
const receipt = await run.step('charge card', () => this.chargeCard());
const total = await run.step('total the order', async () => {
const order = await Order.findOrFail(this.orderId);
return order.total();
});
Names may be built from the workflow's own values:
for (const day of [1, 3, 7]) {
await run.sleep({ days: day });
await run.step(`send reminder ${day}`, () => this.sendReminder(day));
}
A step's result is serialized as a queued job's properties are: dates, models and other values come back as they were stored.
Retries and Timeouts
A step is tried once unless you say otherwise. backoff gives the waits between tries, in seconds or as an interval; the last one is used for every try after it:
const receipt = await run
.step('charge card', () => this.chargeCard())
.tries(5)
.backoff([10, 60, 600])
.timeout(30);
A step may choose when it is tried next, for example from a Retry-After header:
const response = await Http.post('https://crm.example.com/contacts/sync');
if (response.status() === 429) {
throw Workflow.retryAfter(Number(response.header('retry-after')) || 60, new Error('the CRM is busy'));
}
Workflow.currentStep() gives the running step: its key() is the same on every try, ready for an idempotency key, and attempt says which try this is:
await Http.withHeaders({ 'Idempotency-Key': Workflow.currentStep().key() })
.post('https://payments.example.com/charges', { order_id: this.orderId });
Permanent Step Failures
An error wrapped in Workflow.fatal fails the step at once, however many tries are left:
try {
return await this.gateway.charge(this.orderId);
} catch (error) {
throw Workflow.fatal(error);
}
A step that fails for good throws a StepFailed into handle, on this advance and on every replay. Catch it to compensate:
const flight = await run.step('book flight', () => this.bookFlight());
try {
await run.step('book hotel', () => this.bookHotel());
} catch (error) {
await run.step('cancel flight', () => this.cancelFlight(flight));
throw error;
}
Parallel Steps
Steps may run side by side. If one of them backs off, the others still finish and keep their results:
const [projects, teammates] = await Promise.all([
run.step('count projects', () => this.countProjects()),
run.step('count teammates', () => this.countTeammates()),
]);
Rules for Handle
Because handle replays from the top on every advance, it must follow deterministic control flow:
- Perform all I/O inside steps. A database query or HTTP call outside a step may return different results on replay.
- Branch only on workflow inputs and recorded step, sleep, or wait results. Read the current time and random values inside steps.
run.id()andrun.startedAt()are the same on every replay and safe to call anywhere. - Keep step names and wait tokens unique within a run. Reusing a step name, a sleep name or a wait token fails the run, as does opening the same inbox twice.
- Don't race a wait against a sleep. To expire a wait after a duration, chain
timeoutonwaitFor.
Note
JavaScript cannot see what
handleawaits, so an await outside a step is not detected: it is up to you. Atry/catcharound a step cannot swallow a suspension: once the run has suspended, every later operation on the run suspends too.
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, your newly deployed handle method runs and each run.step call is matched against the step names already recorded for that run.
| 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 result | Replays answer the result as it was stored |
| Rewrite the flow | Introduce a new workflow class and keep the old one until existing runs finish |
Renaming a workflow class that has no workflowName orphans its runs: the worker can no longer find the class.
Sleeping
await run.sleep({ days: 3 });
await run.sleep({ hours: 1 }).named('trial grace period');
await run.sleepUntil(this.trialEndsAt);
Because sleeps are delayed queue jobs, they need a queue connection that supports delays. The sync connection executes jobs immediately, so a run on it pauses at its first sleep until a test or workflow:recover advances it.
Waiting and Resuming
waitFor suspends the run until a value is sent to a token:
type Decision = { approved: true } | { approved: false; reason: string };
export class ApproveExpense extends Workflow {
constructor(public expenseId: number) {
super();
}
async handle(run: Run): Promise<void> {
await run.step('ask the manager', () => this.askManager());
const decision = await run.waitFor<Decision>(`expenses.${this.expenseId}.decision`);
if (decision.approved) {
await run.step('pay out', () => this.payOut());
} else {
await run.step('notify the employee', () => this.reject(decision.reason));
}
}
}
Workflow.resume sends the value, from a route or anywhere else. It answers Resumed.Delivered when a run was waiting, Resumed.Pending when the run owns the token but isn't waiting yet (the value is kept for it), and Resumed.NotFound when no run owns the token:
import { Resumed, Workflow } from '@laraflare/workflow';
Route.post('/expenses/{expense}/approve', async (request: Request) => {
const resumed = await Workflow.resume(`expenses.${request.route('expense')}.decision`, { approved: true });
if (resumed === Resumed.NotFound) {
return redirect('/expenses').with('status', 'This expense was already decided.');
}
return redirect('/expenses');
});
A token is owned by one active run at a time. To let several runs wait on the same thing, put the run's ID in the token:
const decision = await run.waitFor<Decision>(`expenses.${this.expenseId}.decision.${run.id()}`);
Timeouts
With timeout, the wait answers null once the span passes without a value:
const decision = await run.waitFor<Decision>(`expenses.${this.expenseId}.decision`).timeout({ days: 3 });
if (decision === null) {
// ...
}
Workflow.waitingFor finds the run that owns a token, so you can check it before resuming:
const waiting = await Workflow.waitingFor(`expenses.${expenseId}.decision`);
if (waiting?.attributes.tenant === 'acme') {
// ...
}
Early Resumes
A value may arrive before the run reaches its wait, such as a payment webhook that beats the run to it. Claim the token when starting the run, and values sent before the wait are kept for it:
const runId = await new ChargeOrder(orderId).start().claim(`orders.${orderId}.charged`);
Typed Tokens
A Token carries the type of its value, so one function names it for the workflow and the route alike:
import { Token } from '@laraflare/workflow';
export const decision = (expenseId: number) => new Token<Decision>(`expenses.${expenseId}.decision`);
// In the workflow...
const decided = await run.waitFor(decision(this.expenseId));
// In the route...
await Workflow.resume(decision(expenseId), { approved: true });
Resume URLs
A resume URL is a signed link that sends a fixed value to a token when it is opened, such as the "Approve" button of an email. Make it inside a step, so the same link is sent on every replay:
const token = `expenses.${this.expenseId}.decision`;
await run.step('email the manager', async () => {
const approvalUrl = Workflow.resumeUrl<Decision>(token, { approved: true }).expires({ days: 3 }).toString();
await Mail.to(this.managerEmail).send(new ApproveExpenseMail(approvalUrl));
});
const decision = await run.waitFor<Decision>(token);
The link opens a small page that says the response was recorded, or that it was already recorded. A link that was changed or has expired is refused with a 403.
Webhook URLs
A webhook URL takes the JSON body POSTed to it as the value, for a service that calls back when its work is done. It answers 202 when the value was taken and 404 when no run owns the token:
type Scan = { totalCents: number };
const token = `expenses.${this.expenseId}.scan`;
await run.step('request receipt scan', async () => {
const callbackUrl = Workflow.webhookUrl(token).toString();
(await Http.post('https://scanner.example.com/scans', { receipt_url: this.receiptUrl, callback_url: callbackUrl })).throw();
});
const scan = await run.waitFor<Scan>(token);
Customizing the Response
respond signs one of your own routes instead of the package's page. Its handler calls Resume.from, which checks the signature, sends the value, and answers the value with the outcome:
import { Resume, Resumed } from '@laraflare/workflow';
Route.get('/expenses/{expense}/decided', async (request: Request) => {
const resume = await Resume.from<Decision>(request);
return Inertia.render('expenses/Decided', {
expenseId: request.route('expense'),
approved: resume.value.approved,
alreadyDecided: resume.outcome === Resumed.NotFound,
});
}).name('expenses.decided');
const approvalUrl = Workflow.resumeUrl<Decision>('expenses.42.decision', { approved: true })
.expires({ days: 3 })
.respond('expenses.decided', { expense: 42 })
.toString();
Inboxes
An inbox reads every value sent to a token, in order:
type Vote = { approverId: number; approve: boolean };
async handle(run: Run): Promise<string> {
const votes = run.inboxFor<Vote>(`expenses.${this.expenseId}.votes`);
await run.step('ask the approvers', () => this.askApprovers());
const approvers = new Set<number>();
let vote: Vote | null;
while ((vote = await votes.next().timeout({ days: 5 })) !== null) {
if (!vote.approve) return 'rejected';
approvers.add(vote.approverId);
if (approvers.size === 2) return 'approved';
}
return 'expired';
}
Once a read times out, the timeout is recorded, so replays leave the loop at the same point even if late values arrive afterwards. Calling next again after a timeout keeps listening and receives any values that arrived later. Because values replay on every advance, a run may read from one inbox at most 1,000 times.
Inspecting and Cancelling Runs
Workflow.find answers a RunInfo: the run's status, attributes, output or error, the tokens it waits for, and its steps. It is null when there is no such run:
Route.get('/runs/{run}', async (request: Request) => {
const run = await Workflow.find(request.route('run'));
return run ?? abort(404);
});
Workflow.cancel cancels an active run:
await Workflow.cancel(runId).reason('the customer closed their account');
Store a run's ID on your own model to inspect or cancel it later. The package's commands manage runs from the console:
| Command | Description |
|---|---|
workflow:list |
Lists runs, newest first. Filter with --status=failed, --name=orders.checkout, and --attribute tenant=acme |
workflow:show {id} |
Displays a run's input, status, attributes, output or error, and each step's tries, timing, and errors |
workflow:retry {id} |
Resumes a failed run from the failing step while keeping earlier recorded steps and resetting the step's tries |
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 |
npx artisan workflow:cancel --attribute tenant=acme --reason="the tenant closed their account"
Schedule workflow:recover and workflow:prune:
// routes/console.ts
Schedule.command('workflow:recover').everyFiveMinutes();
Schedule.command('workflow:prune').daily();
Events
Runs dispatch RunCompleted, RunFailed and RunCancelled:
import { RunFailed } from '@laraflare/workflow';
Event.listen(RunFailed, (event: RunFailed) => {
Log.error('A workflow run failed', { run: event.runId, error: String(event.error) });
});
Writing a Store
To keep runs somewhere else, implement the Store interface. The package handles replay, step retries, serialization and dispatching, so a store only handles persistence and coordination: every write made under a lease checks that the lease is still the run's. MemoryStore is the shortest example. Register the driver, then name it in config/workflow.ts:
import { WorkflowManager } from '@laraflare/workflow';
WorkflowManager.extend('kv', (config) => new KvStore(config.binding as string));
The package's own stores pass a contract of tests, and so should yours: give it a function that makes an empty store, and it registers the tests in your test file:
// tests/KvStoreTest.ts
import { storeContract } from '@laraflare/workflow/Testing/StoreContract';
storeContract('KvStore', () => new KvStore(fakeKvBinding()));
Testing
Faking Starts
Workflow.fake records the runs that are started instead of starting them:
const workflows = Workflow.fake();
await post('/register', { email: 'taylor@example.com' }).assertRedirect();
workflows.assertStarted(OnboardUser);
workflows.assertStartedWhere(OnboardUser, (run) => run.userId === 1);
Running a Workflow in a Test
Workflow.test starts a run and advances it at once, without the queue. Move the clock with travel, then advance the run:
const mail = Mail.fake();
const user = await User.factory().create();
const run = await Workflow.test(new OnboardUser(user.id));
mail.assertSent(Welcome);
run.assertSleeping();
travel(3).days();
await run.advance();
mail.assertSent(GettingStartedTips);
run.assertCompleted();
withStep answers a step's result without running it, and claim claims a token from the start:
const run = await Workflow.test(new Checkout(1)).withStep('charge card', { id: 're_1' });
Testing Waits and Resumes
const run = await Workflow.test(new ApproveExpense(42));
run.assertWaitingFor(decision(42));
(await run.resume(decision(42), { approved: true }))
.assertStepRan('pay out')
.assertCompleted();
The other assertions are assertCompletedWith, assertFailed, assertFailedWith, assertRetrying, assertStepNotRan and assertStepTries.