Workflows
- Introduction
- Setup
- Defining workflows
- Starting runs
- Steps
- Rules for
Handle - Sleeping
- Waiting and resuming
- Inspecting and cancelling runs
- Events
- Writing a store
- Testing
Introduction
Some processes in your application span days rather than seconds. Onboarding a new user might mean sending a welcome email, waiting three days, and then sending getting-started tips if the user hasn't created a project yet. Building that flow from queued jobs alone means chaining delayed jobs, tracking progress in status columns, and sweeping for users who got stuck along the way.
A workflow lets you write the whole flow as one Go method. Laravel runs each step once, saves what it returned, and carries the run across sleeps, webhooks, deploys, and worker restarts:
// workflows/onboard_user.go
package workflows
import (
"context"
"time"
"go.laravel.com/workflow"
)
type OnboardUser struct {
UserID int64 `json:"user_id"`
}
func (o OnboardUser) Handle(run *workflow.Run) error {
if err := run.Do("send welcome email", o.sendWelcomeEmail); err != nil {
return err
}
if err := run.Sleep(3 * 24 * time.Hour); err != nil {
return err
}
projects, err := run.Step("count projects", o.countProjects)
if err != nil || projects > 0 {
return err
}
return run.Do("send tips", o.sendTips)
}
func (o OnboardUser) sendWelcomeEmail(ctx context.Context) error {
// Send the welcome email...
return nil
}
func (o OnboardUser) countProjects(ctx context.Context) (int, error) {
// Count the user's projects...
return 0, nil
}
func (o OnboardUser) sendTips(ctx context.Context) error {
// Send the tips...
return nil
}How a run advances
Workflows run on your existing queue workers and connections, so there's nothing new to deploy. Each advance of a run is a queued job. The worker calls Handle from the top, returns the recorded result of every step that already ran, and runs the first step that hasn't.
When the run reaches a sleep, a wait, or a step's retry backoff, it suspends. The operation never returns, the worker finishes the job, and Laravel queues the next advance for when the run has something to do. No worker sits idle while a workflow sleeps, so a run that waits two weeks uses nothing in the meantime.
Setup
Workflows need a queue worker on a connection that can delay jobs, such as database, redis, or sqs.
Laravel finds a run's workflow by its name when the worker advances it, so register a value of each workflow type with your application. Create workflows/workflows.go with a list of your workflows:
// workflows/workflows.go
package workflows
var All = []any{
OnboardUser{},
ApproveExpense{},
}Then pass the list to your application in bootstrap/app.go:
return laravel.Options{
// ...
Jobs: jobs.All,
Workflows: workflows.All,
}The workflow tables
The database workflow store keeps runs in five tables on your default database connection. New applications don't have these tables, so create them with workflow.CreateTables in a migration before you start a workflow:
// database/migrations/2026_01_01_000000_create_workflow_tables.go
package migrations
import (
"context"
"go.laravel.com/workflow"
)
func createWorkflowTables(ctx context.Context) error {
return workflow.CreateTables(ctx)
}workflow.CreateTables creates workflow_runs, workflow_steps, workflow_waits, workflow_resumes, and workflow_attributes with their indexes. Add the migration to migrations.All, then run laravel migrate. To keep these tables on another database connection, set DB_WORKFLOW_CONNECTION to that connection's name.
Choosing a store
By default, Laravel keeps workflow runs in the database store, and switches to the memory store in tests, so your workflow tests need no tables. Set WORKFLOW_STORE to choose another store. The memory store loses every run when the process exits, so never use it in production.
Register a store you wrote by name in the Register option of bootstrap/app.go, then select it with WORKFLOW_STORE=dynamodb:
return laravel.Options{
// ...
Workflows: workflows.All,
Register: func(app *laravel.Registrar) error {
app.WorkflowStore("dynamodb", dynamo.NewStore(
app.Env().String("DYNAMO_WORKFLOWS_TABLE", "workflows"),
))
return nil
},
}Because WORKFLOW_STORE chooses the store, your tests stay on the memory store they select for you. A package registers a store the same way with app.WorkflowStore inside its Register method.
Defining workflows
Like a job, a workflow is a struct whose fields are its input. Its Handle method does the work. Place each workflow in its own file in the workflows directory, and register a value of it in workflows.All.
Handle receives the *workflow.Run, whose methods are the workflow's durable operations: steps, sleeps, and waits. It returns an error, or a value and an error. A returned value is the run's output, which workflow.Find and workflow:show show. A returned error fails the run.
Laravel encodes the workflow's fields as JSON when the run starts and decodes them on every advance, so give the fields json tags and keep them to plain data, such as IDs. Inside a step, read your services and database through the step's ctx, as in services.From(ctx). For example, here is a complete workflow file that charges an order, emails the receipt, and returns the receipt as the run's output:
// workflows/checkout.go
package workflows
import (
"context"
"go.laravel.com/mail"
"go.laravel.com/model"
"go.laravel.com/workflow"
"app/mails"
"app/models"
"app/services"
)
type Receipt struct {
ChargeID string `json:"charge_id"`
}
type Checkout struct {
OrderID int64 `json:"order_id"`
}
func (c Checkout) Handle(run *workflow.Run) (Receipt, error) {
receipt, err := run.Step("charge card", c.chargeCard)
if err != nil {
return Receipt{}, err
}
if err := run.Do("send receipt", c.sendReceipt(receipt)); err != nil {
return Receipt{}, err
}
return receipt, nil
}
func (c Checkout) chargeCard(ctx context.Context) (Receipt, error) {
order, err := model.Find[models.Order](ctx, c.OrderID)
if err != nil {
return Receipt{}, err
}
chargeID, err := services.From(ctx).Billing.Charge(ctx, order)
if err != nil {
return Receipt{}, err
}
return Receipt{ChargeID: chargeID}, nil
}
func (c Checkout) sendReceipt(receipt Receipt) func(context.Context) error {
return func(ctx context.Context) error {
order, err := model.Find[models.Order](ctx, c.OrderID)
if err != nil {
return err
}
return mail.To(mail.Addr(order.Email)).Send(ctx, mails.OrderReceipt{
Order: order,
ChargeID: receipt.ChargeID,
})
}
}Laravel names a workflow after its package path and type, such as app/workflows.Checkout, and stores that name with each run. Renaming or moving the type would leave its runs with a name that nothing answers to, so give a workflow you might move a WorkflowName method. To send a workflow's jobs to a queue of their own, add a WorkflowOptions method too:
func (Checkout) WorkflowName() string {
return "orders.checkout"
}
func (Checkout) WorkflowOptions() workflow.Options {
return workflow.Options{Queue: "workflows"}
}A workflow may also have a Failed method, which Laravel calls once after the run fails for good, such as to mark the order as failed so your support team sees it:
func (c Checkout) Failed(ctx context.Context, err error) error {
_, updateErr := db.Table("orders").
WhereEq("id", c.OrderID).
Update(ctx, db.Values{"status": "failed"})
return updateErr
}Laravel reports an error that Failed returns to your error reporting. To act on every run that fails, rather than one workflow's, listen for workflow.RunFailed.
Starting runs
To start a run, pass the workflow to workflow.Start, as you'd dispatch a job. Start saves the run, queues its first advance, and returns the run's ID:
package registration
import (
"go.laravel.com/web"
"go.laravel.com/workflow"
"app/models"
"app/workflows"
)
func Store(r *web.Request) *web.Response {
user := models.CurrentUser(r)
if _, err := workflow.Start(r, workflows.OnboardUser{UserID: user.ID}); err != nil {
return web.Fail(err)
}
return web.Redirect("/dashboard")
}You may send the run's jobs to a specific queue connection or queue, or delay when the run starts. The connection and queue you choose at the start apply for the run's whole life:
id, err := workflow.OnConnection("redis").
OnQueue("workflows").
Delay(time.Hour).
Start(r, workflows.OnboardUser{UserID: user.ID})To start the run at a set time, such as when a team's trial ends, use DelayUntil:
id, err := workflow.DelayUntil(team.TrialEndsAt).
Start(r, workflows.ConvertTrial{TeamID: team.ID})A run started inside db.Transaction waits for the transaction to commit, and doesn't start at all if it rolls back, as dispatching a job does. Laravel also keeps the request's context values, such as the active tenant, and restores them on every advance of the run.
Starting a run once
A form submitted twice, or a webhook delivered twice, could start the same workflow twice. To prevent a second run, start it with workflow.StartOnce and a key. If an unfinished run already holds the key, StartOnce saves nothing and returns that run:
func Submit(r *web.Request) *web.Response {
expenseID, err := r.PathInt("expense")
if err != nil {
return web.Abort(http.StatusNotFound)
}
key := fmt.Sprintf("expenses.%d", expenseID)
started, err := workflow.StartOnce(r, key, workflows.ApproveExpense{ExpenseID: expenseID})
if err != nil {
return web.Fail(err)
}
if started.Outcome == workflow.StartedExisting {
slog.InfoContext(r, "The expense is already waiting for approval.", "run", started.ID)
}
return web.Redirect("/expenses")
}started.Outcome is workflow.StartedNew or workflow.StartedExisting, and started.ID is the new run's ID or the ID of the run that holds the key. A run gives up its key once it completes, fails, or is cancelled, so submitting an expense again after it was rejected starts a new run. Inside db.Transaction, StartOnce returns workflow.StartedOnCommit and checks the key when the transaction commits.
Attributes
Attributes are short labels on a run, such as its tenant or the stage it's in. You may select runs by their attributes with workflow:list --attribute, and read them in workflow:show and RunInfo.Attributes. To give a run attributes when it starts, use workflow.Attribute:
id, err := workflow.Attribute("tenant", "acme").
Attribute("plan", "pro").
Start(r, workflows.OnboardUser{UserID: user.ID})You may also change a run's attributes as it progresses, so the people running your application can see what stage a run is in without reading its steps. Setting an attribute again replaces its value:
if _, err := run.Step("charge card", c.chargeCard); err != nil {
return err
}
run.SetAttribute("phase", "shipping")Laravel saves the attributes whenever an advance ends, by sleeping, waiting, completing, or failing. Keep attribute values short and free of sensitive data, since they stay with the run for as long as you keep it.
Deleting a run's data
A run keeps its input, its steps' outputs, and its own output until workflow:prune deletes it. For a workflow that handles sensitive data, such as bank details, start the run with PurgeWhenFinished, which deletes that data as soon as the run completes, fails, or is cancelled:
id, err := workflow.PurgeWhenFinished().
Start(r, workflows.VerifyBankAccount{AccountID: account.ID})The run keeps its ID, status, attributes, and the names and times of its steps, so workflow:list and workflow:show still show it, with <data deleted> in place of its input. Its RunInfo.Purged is true and its Output is empty, so save any output you need from inside a step. A purged run that failed can't be retried.
Steps
run.Step runs a function once and saves what it returns under the step's name. On later advances, Step returns the saved value without calling the function again. The function receives a ctx of its own and returns a value and an error, so it may be a method of the workflow or an inline function:
receipt, err := run.Step("charge card", c.chargeCard)
if err != nil {
return err
}
total, err := run.Step("total the order", func(ctx context.Context) (int64, error) {
order, err := model.Find[models.Order](ctx, c.OrderID)
if err != nil {
return 0, err
}
return order.Total, nil
})The value goes through JSON on every advance, the first one included, so return a type that survives encoding to JSON and back, such as a struct with json tags. For a step that returns nothing but an error, use run.Do:
if err := run.Do("send receipt", c.sendReceipt(receipt)); err != nil {
return err
}Step names identify the saved results across advances, show in workflow:show, and let tests replace a step's output. Each name must be unique within a run, so include an index or a key when you call a step in a loop:
for _, day := range []int{1, 3, 7} {
if err := run.Sleep(time.Duration(day) * 24 * time.Hour); err != nil {
return err
}
if err := run.Do(fmt.Sprintf("send reminder %d", day), o.sendReminder(day)); err != nil {
return err
}
}Retries and timeouts
By default, Laravel tries a failing step up to three times. It waits 10 seconds before the second try and a minute before the third, and a panic counts as a failed try. You may change a step's tries, its backoff, and how long one try may run:
receipt, err := run.Step("charge card", c.chargeCard,
workflow.Tries(5),
workflow.Backoff(10*time.Second, time.Minute, 10*time.Minute),
workflow.Timeout(30*time.Second),
)The run suspends during each backoff, so no worker is held while it waits. When the backoff runs out of waits, the last one repeats. A try that outlives its timeout fails, and its ctx ends.
Some services tell you when to try again, such as an API whose 429 response has a Retry-After header. To wait that long in place of the step's backoff, return the error through workflow.RetryAfter, or workflow.RetryAt with a time. The try still counts toward the step's tries:
func (s SyncContacts) syncContacts(ctx context.Context) error {
res, err := httpclient.Post(ctx, "https://crm.example.com/contacts/sync")
if err != nil {
return err
}
if wait, ok := res.RetryAfter(ctx); ok {
return workflow.RetryAfter(wait, errors.New("the CRM is busy"))
}
return res.EnsureSuccessful()
}res.RetryAfter reports a wait only for a 429 or 503 response with a Retry-After header. Any other failed response fails the try through EnsureSuccessful, and the step tries again after its backoff.
If a worker crashes after a step's work is done but before Laravel saves its result, the step runs again, so make your steps safe to repeat. Inside a step, workflow.CurrentStep(ctx) returns the try in progress. Its Key combines the run's ID and the step's name, and stays the same across tries, so you may pass it to a payment provider as an idempotency key to keep a retry from charging twice:
func (c Checkout) chargeCard(ctx context.Context) (Receipt, error) {
res, err := httpclient.Header("Idempotency-Key", workflow.CurrentStep(ctx).Key).
JSON(map[string]int64{"order_id": c.OrderID}).
EnsureSuccessful().
Post(ctx, "https://payments.example.com/charges")
if err != nil {
return Receipt{}, err
}
return res.JSON[Receipt]()
}CurrentStep(ctx).Number is the try's number, starting at 1, such as to change what the step does on its last try.
Permanent step failures
Some errors won't go away with another try, such as a card that the bank declined. To fail the step at once, return the error through workflow.Fatal:
receipt, err := gateway.Charge(ctx, c.OrderID)
if errors.Is(err, gateway.ErrDeclined) {
return Receipt{}, workflow.Fatal(err)
}When a step runs out of tries or returns a Fatal error, Step returns a *workflow.StepFailedError, which holds the step's name and its last error. Returning it from Handle fails the run. On every later advance, the step returns the same error, so code that checks it takes the same branch each time.
That lets you write compensating steps in plain Go. For example, a travel booking workflow may cancel the flight when booking the hotel fails:
flight, err := run.Step("book flight", t.bookFlight)
if err != nil {
return err
}
if _, err := run.Step("book hotel", t.bookHotel); err != nil {
if cancelErr := run.Do("cancel flight", t.cancelFlight(flight)); cancelErr != nil {
return cancelErr
}
return err
}"cancel flight" is an ordinary step, so Laravel retries it and saves its result as it does for "book flight" and "book hotel".
Parallel steps
run.Go runs a step in a goroutine of its own, so several steps run at the same time on the current worker. It returns a task, and the task's Wait returns what the step returned:
projects := run.Go("count projects", o.countProjects)
teammates := run.Go("count teammates", o.countTeammates)
p, err := projects.Wait()
if err != nil {
return err
}
t, err := teammates.Wait()
if err != nil {
return err
}Wait for every task before the next operation. When one task's step must wait to be tried again, the run suspends once the other tasks finish, and their results are kept for the next advance.
To spread work across many queue workers and wait for all of it, dispatch a job batch inside a step, and wait for a token that the batch's Then callback resumes. Laravel runs the callback as a queued job, so list its type in jobs.All:
// jobs/import_finished.go
type ImportFinished struct {
Token workflow.Token[bool] `json:"token"`
}
func (c ImportFinished) Then(ctx context.Context, batch *queue.Batch) error {
_, err := workflow.Resume(ctx, c.Token, true)
return err
}func (i ImportContacts) Handle(run *workflow.Run) error {
token := workflow.Token[bool](fmt.Sprintf("imports.%d.done", i.ImportID))
if err := run.Do("dispatch batch", func(ctx context.Context) error {
chunks := make([]jobs.ImportCSV, len(i.Chunks))
for n, rows := range i.Chunks {
chunks[n] = jobs.ImportCSV{Rows: rows}
}
_, err := queue.NewBatch(chunks).
Then(jobs.ImportFinished{Token: token}).
Dispatch(ctx)
return err
}); err != nil {
return err
}
if _, err := run.WaitFor(token); err != nil {
return err
}
return run.Do("mark import complete", i.markComplete)
}Rules for Handle
Handle runs from the top on every advance, so it must take the same path each time it reaches the same point. Laravel checks what it can, and fails the run with an error that names the rule:
- Do all I/O inside steps. A query or an HTTP call outside a step may return something different on the next advance.
- Branch only on the workflow's fields and on what steps, sleeps, and waits returned. Read the time and random values inside steps.
run.ID()andrun.StartedAt()return the same values on every advance, so you may use them anywhere. - Give each step and sleep its own name, and wait for each token once. Reusing a step's name or a wait's token fails the run, as does reading one token's inbox through two inboxes.
- Run steps in goroutines only through
run.Go, and wait for each task before you sleep or generate a token. An unnamed sleep or arun.NewTokencall while a task is outstanding fails the run, since its number could change on the next advance.
When an operation suspends the run, it doesn't return, and code after it doesn't run in that advance. Deferred functions in Handle still run, so don't defer work that should happen once, such as sending an email.
Changing a workflow with runs in flight
Workflows sleep and wait for days, so you'll often deploy a change to a workflow while some of its runs are in flight. When a sleeping run wakes, the worker runs your new Handle, and matches each step against the steps the run saved, by name. Adding and removing steps is safe, but renaming a step or changing what it returns needs care:
| Change | What happens to runs in flight |
|---|---|
| Add a step | The run runs the new step once it reaches the step. |
| Remove a step | The run ignores the step's saved result. |
| Rename a step | The run runs the step again under its new name, so don't rename a step that has side effects. |
| Change a step's type | The run fails, naming the step, unless the saved JSON still decodes as the new type. |
| Rewrite the flow | Write a new workflow type, and keep the old one until its runs finish. |
Sleeping
Call run.Sleep to suspend a run for a while, or run.SleepUntil to suspend it until a time. Laravel numbers a run's sleeps in the order it reaches them, so workflow:show lists them as sleep 1, sleep 2, and so on. You may name a sleep with workflow.Named instead:
if err := run.Sleep(3 * 24 * time.Hour); err != nil {
return err
}
if err := run.Sleep(time.Hour, workflow.Named("trial grace period")); err != nil {
return err
}
if err := run.SleepUntil(t.TrialEndsAt); err != nil {
return err
}Sleeps are delayed queue jobs, so they need a queue connection that can delay jobs. SQS FIFO queues can't, and the sync connection runs each job as it's dispatched, so a run on it stops at its first sleep until a test or workflow:recover advances it.
Waiting and resuming
Some workflows wait for a person or another service, such as a manager who approves an expense. run.WaitFor suspends the run until another part of your application gives the run's token a value with workflow.Resume. For example, this workflow waits for a manager's decision:
// workflows/approve_expense.go
package workflows
import (
"fmt"
"go.laravel.com/workflow"
)
type Decision string
const (
Approved Decision = "approved"
Rejected Decision = "rejected"
)
type ApproveExpense struct {
ExpenseID int64 `json:"expense_id"`
}
func (a ApproveExpense) Handle(run *workflow.Run) error {
if err := run.Do("ask the manager", a.askManager); err != nil {
return err
}
token := workflow.Token[Decision](fmt.Sprintf("expenses.%d.decision", a.ExpenseID))
decision, err := run.WaitFor(token)
if err != nil {
return err
}
if decision == Approved {
return run.Do("pay out", a.payOut)
}
return run.Do("notify the employee", a.notifyRejected)
}When the run reaches WaitFor, it claims expenses.42.decision and owns the token until the run completes, fails, or is cancelled. In this example, the email to the manager links to a route whose handler resumes the run:
func Approve(r *web.Request) *web.Response {
token := workflow.Token[workflows.Decision](
"expenses." + r.PathValue("expense") + ".decision",
)
resumed, err := workflow.Resume(r, token, workflows.Approved)
if err != nil {
return web.Fail(err)
}
if resumed == workflow.ResumeNotFound {
return web.Redirect("/expenses").With(
"status",
"This expense was already decided.",
)
}
return web.Redirect("/expenses")
}workflow.Resume returns workflow.ResumeDelivered when an unfinished run owns the token and receives the value. When no unfinished run owns the token, Laravel stores nothing and returns workflow.ResumeNotFound, so a second click on an expense that was already decided cannot affect a later run. Inside db.Transaction, Resume waits for the transaction to commit and returns workflow.ResumeOnCommit.
A token is an identifier, not a secret. Anyone who can reach the route can resume the run, so protect the route with a policy (for example, checking that the signed-in user manages the expense) or a signed URL.
A token such as expenses.42.decision targets whichever unfinished run currently owns it, so an approval page left open in an old tab could still decide a newer run. If a page should only resume the run that rendered it, include the run's ID in the token and pass that token in the page's form or link (a resume URL carries its token automatically):
token := workflow.Token[Decision](
fmt.Sprintf("expenses.%d.decision.%s", a.ExpenseID, run.ID()),
)
decision, err := run.WaitFor(token)Only one unfinished run may own a token at a time. If a second run waits for a token that another unfinished run already owns, the second run fails with an error naming the owner. Include the record's ID in your tokens, and use StartOnce when a record should have at most one unfinished run at a time.
To stop waiting after a while, use run.WaitWithin with a timeout. It reports false when the time passes before a resume arrives:
decision, decided, err := run.WaitWithin(token, 3*24*time.Hour)
if err != nil {
return err
}
if !decided {
return run.Do("escalate", a.escalate)
}To inspect the run waiting for a token before resuming it, such as reading its attributes, call workflow.WaitingFor. It reports false when no run is currently waiting for the token, including a run that has claimed the token but has not reached its wait yet:
run, found, err := workflow.WaitingFor(r, token)
if err != nil {
return web.Fail(err)
}
if !found {
return web.Abort(http.StatusNotFound)
}
// Check run.Attributes before resuming...Early resumes
Sometimes a resume arrives before the run reaches its wait. For example, a step might ask a payment provider to charge a card, and the provider's webhook might reach your application before the step finishes and the run reaches WaitFor. Because no run owns the token yet, workflow.Resume returns workflow.ResumeNotFound.
To capture early resumes, claim the token when you start the run with workflow.ClaimToken. The run owns the token immediately, and any values sent before it reaches WaitFor are queued in arrival order:
id, err := workflow.ClaimToken(workflows.ChargedFor(order.ID)).
Start(r, workflows.ChargeOrder{OrderID: order.ID})Starting the run fails with a *workflow.TokenOwnedError if another unfinished run already owns the token. You may chain ClaimToken for each token the run will wait on.
If you do not know the token when the run starts, respond to the webhook with a non-2xx status when workflow.Resume returns workflow.ResumeNotFound so the provider retries once the run is waiting. Webhook URLs return 404 Not Found automatically; in your own route, check the outcome:
func Charged(r *web.Request) *web.Response {
charge, err := r.JSON[workflows.Charge]()
if err != nil {
return web.Fail(err)
}
orderID, err := r.PathInt("order")
if err != nil {
return web.Abort(http.StatusNotFound)
}
resumed, err := workflow.Resume(r, workflows.ChargedFor(orderID), charge)
if err != nil {
return web.Fail(err)
}
if resumed == workflow.ResumeNotFound {
return web.Abort(http.StatusNotFound)
}
return web.NoContent().WithStatus(http.StatusAccepted)
}Typed tokens
A workflow.Token[T] is a string that also names the type of its value. The workflow and the handler that resumes it share one token, so the compiler checks that the handler sends a Decision, and nothing fails when the run decodes the value. Define a function that returns the token, and call it from both sides:
func DecisionFor(expenseID int64) workflow.Token[Decision] {
return workflow.Token[Decision](fmt.Sprintf("expenses.%d.decision", expenseID))
}// In the workflow...
decision, err := run.WaitFor(DecisionFor(a.ExpenseID))
// In the route's handler...
_, err := workflow.Resume(r, workflows.DecisionFor(expenseID), workflows.Approved)A token is a string, so a model or a workflow struct may keep one.
When no code of yours needs to know the token, such as for a wait that only a resume URL reaches, run.NewToken generates one from the run's ID:
decision := run.NewToken[Decision]()Resume URLs
When a route exists only to resume a workflow, like the Approve handler above, Laravel can make signed URLs that resume the run for you.
workflow.ResumeURL returns a signed link that resumes the run with a fixed value, such as an "Approve" button in an email. Build the URL inside the step that sends the email:
token := DecisionFor(a.ExpenseID)
if err := run.Do("email the manager", func(ctx context.Context) error {
approve, err := workflow.ResumeURL(
ctx,
token,
Approved,
workflow.Expires(3*24*time.Hour),
)
if err != nil {
return err
}
return mail.To(mail.Addr(a.ManagerEmail)).Send(ctx, mails.ApproveExpense{ApproveURL: approve})
}); err != nil {
return err
}
decision, err := run.WaitFor(token)The URL answers GET and POST requests with 202 Accepted, or 404 Not Found when no unfinished run owns the token. HEAD requests resume nothing so link checkers cannot approve the expense, and requests with an invalid or expired signature receive 403.
Webhook URLs
workflow.WebhookURL returns a signed URL that another service may POST JSON to, and the run takes the request's body as its value. For example, this step sends a receipt to a scanning service with a callback URL, and the workflow waits for the scanner to POST back the receipt's total:
type Scan struct {
TotalCents int64 `json:"total_cents"`
}token := workflow.Token[Scan](fmt.Sprintf("expenses.%d.scan", a.ExpenseID))
if err := run.Do("request receipt scan", func(ctx context.Context) error {
callback, err := workflow.WebhookURL(ctx, token)
if err != nil {
return err
}
_, err = httpclient.JSON(map[string]string{
"receipt_url": a.ReceiptURL,
"callback_url": callback,
}).
EnsureSuccessful().
Post(ctx, "https://scanner.example.com/scans")
return err
}); err != nil {
return err
}
scan, err := run.WaitFor(token)A request whose body isn't JSON gets a 400, and the run keeps waiting. The run decodes the body as the token's type on its next advance, and fails if the body doesn't decode.
Customizing the response
To answer with a page of your own in place of the 202 Accepted, such as a "Thanks, the expense is approved" view, point the URL at one of your routes with workflow.Through, and give the route's parameters as names and values. The route's handler resumes the run with workflow.Accept, which checks the signature and returns the value:
approve, err := workflow.ResumeURL(ctx, token, Approved,
workflow.Expires(3*24*time.Hour),
workflow.Through("expenses.decided", "expense", a.ExpenseID),
)// routes/web.go
route.Get("/expenses/{expense}/decided", expenses.Decided).Name("expenses.decided")func Decided(r *web.Request) *web.Response {
resume, err := workflow.Accept[workflows.Decision](r)
if err != nil {
return web.Fail(err)
}
return web.View("expenses.decided", map[string]any{
"expense": r.PathValue("expense"),
"approved": resume.Value == workflows.Approved,
"alreadyDecided": resume.Outcome == workflow.ResumeNotFound,
})
}Accept returns an error that responds with 403 when the signature is invalid or expired, so web.Fail sends the right response. resume.Outcome is workflow.ResumeNotFound when no unfinished run owns the token, such as when a manager clicks the link again after the run finished. Route middleware run before the handler, so placing Authenticate on the route ensures only a signed-in user can resume the run.
The signature proves only that your application made the URL, not who opened it, so anyone with the link can resume the run, including an email provider's link scanner. For a sensitive approval, put the route behind Authenticate, or link to a page whose form calls workflow.Resume.
Inboxes
run.WaitFor waits for one value. To receive many values over time, such as votes or replies, open an inbox for the token with run.Inbox. Each call to the inbox's Next suspends the run until the next value arrives, and returns the values in the order they arrived.
For example, a large expense might need two managers to approve it. This workflow asks the approvers, then reads their votes. It rejects the expense as soon as anyone votes no, approves it once two different managers vote yes, and expires it when five days pass without a vote:
type Vote struct {
ApproverID int64 `json:"approver_id"`
Approve bool `json:"approve"`
}
type Outcome string
type ApproveLargeExpense struct {
ExpenseID int64 `json:"expense_id"`
}
func VotesFor(expenseID int64) workflow.Token[Vote] {
return workflow.Token[Vote](fmt.Sprintf("expenses.%d.votes", expenseID))
}
func (a ApproveLargeExpense) Handle(run *workflow.Run) (Outcome, error) {
if err := run.Do("ask the approvers", a.askApprovers); err != nil {
return "", err
}
votes := run.Inbox(VotesFor(a.ExpenseID))
approvers := map[int64]bool{}
for len(approvers) < 2 {
vote, ok, err := votes.NextWithin(5 * 24 * time.Hour)
switch {
case err != nil:
return "", err
case !ok:
return "expired", nil
case !vote.Approve:
return "rejected", nil
}
approvers[vote.ApproverID] = true
}
return "approved", nil
}Each vote reaches the inbox through workflow.Resume with the inbox's token, as a single wait's value does. The loop ends when your code returns, or when five days pass and NextWithin reports false.
Laravel records a read that timed out, so every later advance leaves the loop at the same read, even when a vote arrives afterward. A late vote isn't lost. The timeout applies only to that read, so a later NextWithin on the same inbox returns the vote at once.
You may also build resume and webhook URLs for an inbox's token, such as "Approve" and "Reject" links in each approver's email:
approve, err := workflow.ResumeURL(
ctx,
VotesFor(a.ExpenseID),
Vote{ApproverID: approver.ID, Approve: true},
)Every request to the URL adds another value to the inbox, so an approver who clicks the link twice votes twice. Count distinct approvers rather than values, as the approvers map above does.
The first Next or NextWithin claims the token for the run, like WaitFor, and the inbox then receives every value sent to the token, including values that arrive while the run is executing a step. To capture values sent before the first read, claim the token when starting the run. A run may read an inbox at most 1,000 times, so hand a longer conversation to a new run.
Inspecting and cancelling runs
workflow.Find returns a run's status, its steps, and its output or error. workflow.RunInfo encodes as JSON, so a handler may return it for a progress page:
func Show(r *web.Request) *web.Response {
run, found, err := workflow.Find(r, workflow.RunID(r.PathValue("run")))
if err != nil {
return web.Fail(err)
}
if !found {
return web.Abort(http.StatusNotFound)
}
return web.JSON(run)
}A RunInfo has the run's Status, its Steps with their tries and times, its Output as JSON, its Error, and its Attributes. Its WaitingFor method returns the tokens the run waits for, and a wait's StepInfo.TimedOut tells a wait that timed out from one that a resume answered.
To stop a run, call workflow.Cancel, which workflow:cancel calls too. A step that's running finishes, and no step starts after it. Laravel dispatches workflow.RunCancelled with the reason you give, which also shows in workflow:show and RunInfo.Error:
cancelled, err := workflow.Cancel(ctx, id, "the customer closed their account")Cancel reports false when the run doesn't exist or has already ended.
You may keep a run's ID on a model to find or cancel the run later, such as the onboarding run of each user. Add a nullable onboarding_run_id column in a migration, as a uuid column or a string of 36 characters, then add a *workflow.RunID field to your model:
type User struct {
ID int64 `db:"id"`
OnboardingRunID *workflow.RunID `db:"onboarding_run_id"`
}Save the ID when you start the run, and read it back when you need the run:
// When starting the workflow...
id, err := workflow.Start(r, workflows.OnboardUser{UserID: user.ID})
if err != nil {
return web.Fail(err)
}
if err := model.Update(r, user, db.Values{"onboarding_run_id": id}); err != nil {
return web.Fail(err)
}
// Later, when inspecting or cancelling the run...
if user.OnboardingRunID != nil {
run, found, err := workflow.Find(r, *user.OnboardingRunID)
}Commands
| Command | Description |
|---|---|
workflow:list | Lists runs, newest first. Select them with --status failed, --name orders.checkout, and --attribute tenant=acme. |
workflow:show ID | Shows a run's input, status, attributes, and output or error, and each step's tries, time, and error. |
workflow:retry ID | Continues a failed run from the step that failed. The steps before it keep their results, and the failed step gets its tries back. |
workflow:cancel ID | Cancels unfinished runs. Pass --reason to say why. |
workflow:recover | Queues runs whose sleep, timeout, retry, or resume is due but have no wake-up queued. |
workflow:prune | Deletes runs that finished more than 24 hours ago, with their steps and resume values. Change the age with --hours 72. |
Pass --json to workflow:list or workflow:show to print one line of JSON, for scripts and dashboards.
Without IDs, workflow:cancel cancels the unfinished runs that --status, --name, and --attribute select, up to --limit, which is 50 by default. It asks before it cancels them, unless you pass --force:
laravel workflow:cancel --attribute tenant=acme --reason "the tenant closed their account"Wake-ups are delayed queue jobs, so a worker that crashes between saving a run and queueing its wake-up, or a queue that someone cleared, can leave a run stranded. Schedule workflow:recover and workflow:prune in commands/schedule.go to recover stranded runs and keep your workflow tables small:
func Schedule(ctx context.Context, s *schedule.Schedule) {
s.Command("workflow:recover").EveryFiveMinutes()
s.Command("workflow:prune").Daily()
}Events
Laravel dispatches events as runs end: workflow.RunCompleted when a workflow returns, workflow.RunFailed after a run fails for good and its Failed method has run, and workflow.RunCancelled with its Reason when a run is cancelled. Laravel also reports a failed run's error to your error reporting. Listeners receive the context values the run started with, such as the active tenant, so their log entries include them:
// listeners/log_failed_workflow.go
package listeners
import (
"context"
"log/slog"
"go.laravel.com/workflow"
)
func LogFailedWorkflow(ctx context.Context, e workflow.RunFailed) error {
slog.ErrorContext(ctx, "A workflow run failed.", "run", e.RunID, "error", e.Err)
return nil
}Each advance of a run gets a tracing span named after the workflow, such as workflow orders.checkout, and each try of a step gets a child span, such as step charge card. The spans record the run's ID, the step's name, and the try's number. A span is marked failed when its advance or try fails. When a request starts or resumes a run, the advance it queues continues the request's trace, so the request and the work it set off appear in the same trace.
Writing a store
To store runs in another backend, such as DynamoDB, implement workflow.Store. Laravel replays runs, retries steps, encodes values, and dispatches jobs, so your store only persists runs and coordinates four atomic operations: claiming a run's lease with a fresh workflow.Lease token, assigning each token to one unfinished run, numbering the values a token's owner keeps, and matching a wait with a resume. Each write during an advance (Record, Wait, StopWaiting, SetAttributes, Renew, and Release) receives that workflow.Lease and must return workflow.ErrLeaseLost without mutating state if the lease is no longer active. When no unfinished run owns a token, Resume stores nothing. The workflow.Store documentation describes each method's full contract:
package dynamo
import (
"context"
"time"
"go.laravel.com/workflow"
)
type Store struct {
table string
// DynamoDB client...
}
func NewStore(table string) *Store {
return &Store{table: table}
}
func (s *Store) Create(
ctx context.Context,
run workflow.NewRun,
) (workflow.RunID, error) {
// Save the run and claim its tokens unless unique or taken...
return "", nil
}
func (s *Store) Claim(
ctx context.Context,
id workflow.RunID,
lease time.Duration,
) (workflow.Claim, error) {
// Acquire the lease with a fresh workflow.Lease and return the run...
return workflow.Claim{State: workflow.Ended}, nil
}
func (s *Store) Record(
ctx context.Context,
id workflow.RunID,
lease workflow.Lease,
entry workflow.Entry,
) error {
// Save the step, sleep, or wait entry while lease is active...
return nil
}
func (s *Store) Wait(
ctx context.Context,
id workflow.RunID,
lease workflow.Lease,
token string,
number int,
) (string, bool, error) {
// Claim the token, record the wait, or return a value while lease is active...
return "", false, nil
}
func (s *Store) StopWaiting(
ctx context.Context,
id workflow.RunID,
lease workflow.Lease,
token string,
) error {
// Clear the run's wait for the token after a timeout while lease is active...
return nil
}
func (s *Store) Resume(
ctx context.Context,
token, value string,
) (workflow.RunID, bool, error) {
// Queue the value for the token's owner, or ignore if unowned...
return "", false, nil
}
func (s *Store) Waiting(
ctx context.Context,
token string,
) (workflow.RunID, bool, error) {
// Return the run currently waiting for the token...
return "", false, nil
}
func (s *Store) SetAttributes(
ctx context.Context,
id workflow.RunID,
lease workflow.Lease,
attributes map[string]string,
) error {
// Replace the run's attributes while lease is active...
return nil
}
func (s *Store) Renew(
ctx context.Context,
id workflow.RunID,
lease workflow.Lease,
duration time.Duration,
) error {
// Extend the run's lease while lease is active...
return nil
}
func (s *Store) Release(
ctx context.Context,
id workflow.RunID,
lease workflow.Lease,
outcome workflow.Outcome,
now time.Time,
) error {
// Save the outcome, clear the lease, and free tokens while lease is active...
return nil
}
func (s *Store) Find(
ctx context.Context,
id workflow.RunID,
) (workflow.RunRecord, bool, error) {
// Load the run by ID...
return workflow.RunRecord{}, false, nil
}
func (s *Store) Entries(
ctx context.Context,
id workflow.RunID,
) ([]workflow.Entry, error) {
// Load the run's entries in order...
return nil, nil
}
func (s *Store) List(
ctx context.Context,
filter workflow.Filter,
) ([]workflow.RunRecord, error) {
// Return matching runs, newest first...
return nil, nil
}
func (s *Store) Cancel(
ctx context.Context,
id workflow.RunID,
reason string,
now time.Time,
) (bool, error) {
// Cancel an unfinished run and release its unique key and tokens...
return false, nil
}
func (s *Store) Retry(
ctx context.Context,
id workflow.RunID,
now time.Time,
) (bool, error) {
// Mark a failed run pending again without its failed entries...
return false, nil
}
func (s *Store) Overdue(
ctx context.Context,
now time.Time,
) ([]workflow.RunRecord, error) {
// Return runs with an overdue wake-up, lease, or resume...
return nil, nil
}
func (s *Store) Prune(
ctx context.Context,
before time.Time,
) (int64, error) {
// Delete runs finished before the cutoff, with entries and values...
return 0, nil
}workflowtest.StoreContract checks a store against that contract. Run it in a test against an empty store:
func TestDynamoStore(t *testing.T) {
workflowtest.StoreContract(t, t.Context(), dynamo.NewStore(testTable(t)))
}Then use the store. Register it by name in your options' Register function (or a package's Register method) with app.WorkflowStore so WORKFLOW_STORE may name it, as choosing a store shows.
Testing
In tests, Laravel uses the memory workflow store and the sync queue connection by default, so your workflow tests need neither database tables nor a worker.
Faking starts
When you test a handler and only need to know that it started a workflow, call workflowtest.New. The fake records the runs your application starts, without saving or running them:
func TestRegisteringStartsOnboarding(t *testing.T) {
client := tests.New(t)
started := workflowtest.New(client)
client.Post("/register", url.Values{"email": {"taylor@laravel.com"}}).
AssertRedirect("/dashboard")
started.AssertStarted[workflows.OnboardUser]()
started.AssertStarted(func(w workflows.OnboardUser) bool { return w.UserID == 1 })
}The fake also has AssertStartedTimes, AssertNotStarted, and AssertNothingStarted. To fake only some workflows and let the others start, pass workflowtest.Only or workflowtest.Except.
Running a workflow in a test
workflowtest.Start starts a run and advances it until it completes or suspends. You may then move the clock with client.Travel, and call the run's Advance as a worker that wakes the run would:
func TestOnboardingSendsTipsWhenTheUserHasNoProjects(t *testing.T) {
client := tests.New(t)
sent := mailtest.New(client)
user := client.Create(factories.User)
run := workflowtest.Start(client, workflows.OnboardUser{UserID: user.ID})
sent.AssertSent[mails.Welcome]()
run.AssertSleeping()
client.Travel(3 * 24 * time.Hour)
run.Advance()
sent.AssertSent[mails.GettingStartedTips]()
run.AssertCompleted()
}The run also has AssertCompletedWith, AssertFailed, AssertFailedWith, AssertCancelled, AssertRetrying, AssertStepRan, AssertStepNotRan, and AssertStepTries. Each returns the run, so you may chain them.
Steps have names, so a test may replace a step's output with workflowtest.WithStep instead of faking the service the step calls:
run := workflowtest.Start(client, workflows.Checkout{OrderID: 1},
workflowtest.WithStep("charge card", workflows.Receipt{ChargeID: "ch_1"}),
)A replaced step records as completed after 0 tries, so run.AssertStepTries("charge card", 0) checks that the test's output was used.
Testing waits and resumes
When a workflow waits with WaitFor or reads an inbox, check its token with run.AssertWaitingFor, then call run.Resume with a value. Resume gives the token the value and advances the run at once:
func TestApprovedExpensesArePaidOut(t *testing.T) {
client := tests.New(t)
token := workflows.DecisionFor(42)
run := workflowtest.Start(client, workflows.ApproveExpense{ExpenseID: 42})
run.AssertWaitingFor(token)
run.Resume(token, workflows.Approved).AssertStepRan("pay out").AssertCompleted()
}For an inbox, call run.Resume once for each value, in order:
token := workflows.VotesFor(42)
run := workflowtest.Start(client, workflows.ApproveLargeExpense{ExpenseID: 42})
run.AssertWaitingFor(token)
run.Resume(token, workflows.Vote{ApproverID: 1, Approve: true}).
AssertWaitingFor(token)
run.Resume(token, workflows.Vote{ApproverID: 2, Approve: true}).
AssertCompletedWith(workflows.Outcome("approved"))To test an early resume that arrives before the run reaches its wait, claim the token when starting the test run with workflowtest.ClaimToken:
run := workflowtest.Start(
client,
workflows.ChargeOrder{OrderID: 42},
workflowtest.ClaimToken(workflows.ChargedFor(42)),
)To test what happens when a WaitWithin times out, travel past the timeout and advance the run without resuming it:
run := workflowtest.Start(client, workflows.ApproveExpense{ExpenseID: 42})
client.Travel(4 * 24 * time.Hour)
run.Advance().AssertCompleted()