Course › Week 6 · Laravel Go › Day 5 · lesson 40 of 42 · 30 min reading + 60 min practice
Workflows
A long process written as one method: each step runs once, and the flow survives restarts.
A booking request at Nordic Stays is a process, not a request: email the guest that the host was asked, wait up to 48 hours for the host, save the answer, email the guest again. In PHP Laravel that is a chain of jobs, a status column, and a scheduled command that finds the requests nobody answered. In Laravel Go it can be one method.
A workflow runs that method on the queue of the queues lesson. Each step runs once and its result is saved; when the method has to wait, the run stops and uses no worker until it has something to do. Today the booking request, from start to answer, through a restart and a timeout.
Setup
1. The tables, and the list
Runs are stored in five tables that workflow.CreateTables creates, so they need a migration, listed after the bookings one:
package migrations
import (
"context"
"go.laravel.com/workflow"
)
func createWorkflowTables(ctx context.Context) error {
return workflow.CreateTables(ctx)
}
workflow_runs holds each run, workflow_steps each step’s saved result, and the other three the waits, the values that resume them, and attributes. Like the queue, it is all rows in your Postgres.
2. Registering the workflow
A workflow is found by its name when a worker advances it, so it is listed like a job, in workflows.All, and the list goes into bootstrap/app.go:
package bootstrap
import (
laravel "go.laravel.com"
"go.laravel.com/auth"
"go.laravel.com/config"
"go.laravel.com/db"
"go.laravel.com/db/postgres"
"go.laravel.com/inertia"
"go.laravel.com/web"
"app/commands"
"app/database/migrations"
"app/database/schema"
"app/database/seeders"
"app/jobs"
"app/listeners"
"app/models"
"app/resources"
"app/routes"
"app/services"
"app/workflows"
)
func Options() laravel.Options {
return laravel.Options{
Routes: laravel.Routes{
Web: routes.Web,
API: routes.API,
Channels: routes.Channels,
Health: "/up",
},
Middleware: func(m *laravel.Middleware, cfg *config.Config) {
m.Web.Append(auth.Session[models.User]{})
m.Web.Append(inertia.Middleware{
Share: share,
ErrorPage: "Error",
})
},
Views: resources.Views,
Drivers: []db.Driver{postgres.Driver},
Migrations: migrations.All,
Schema: schema.Dumps,
Seeders: seeders.All,
Commands: commands.All,
Schedule: commands.Schedule,
Listeners: listeners.All,
Jobs: jobs.All,
Workflows: workflows.All,
Services: laravel.BuildServices(services.New),
}
}
func share(r *web.Request) (inertia.Props, error) {
return inertia.Props{
"name": config.From(r).App.Name,
"status": r.Session().Get("status"),
}, nil
}
Two lines: the import and Workflows: workflows.All. workflows/workflows.go holds var All = []any{ConfirmBooking{}}. The booking model gets a third status, Declined.
The workflow
3. Handle: the whole process in one method
A workflow is a struct whose fields are its input, stored as JSON when the run starts. Handle receives the *workflow.Run, whose methods are the steps that survive:
package workflows
import (
"context"
"fmt"
"time"
"go.laravel.com/db"
"go.laravel.com/httpclient"
"go.laravel.com/model"
"go.laravel.com/workflow"
"app/models"
"app/services"
)
type Decision string
const (
Approved Decision = "approved"
Declined Decision = "declined"
)
// ConfirmBooking asks the host to approve a booking request, and waits for the answer.
type ConfirmBooking struct {
BookingID int64 `json:"booking_id"`
DecideWithinSeconds int `json:"decide_within_seconds"`
}
// DecisionToken names the wait for a booking's decision, so a handler can resume it.
func DecisionToken(bookingID int64) workflow.Token[Decision] {
return workflow.Token[Decision](fmt.Sprintf("bookings.%d.decision", bookingID))
}
func (c ConfirmBooking) Handle(run *workflow.Run) (models.Status, error) {
if err := run.Do("tell the guest we asked", c.message("received")); err != nil {
return "", err
}
within := time.Duration(c.DecideWithinSeconds) * time.Second
decision, decided, err := run.WaitWithin(DecisionToken(c.BookingID), within)
if err != nil {
return "", err
}
status := models.Confirmed
if !decided || decision == Declined {
status = models.Declined
}
if err := run.Do("save the status", c.save(status)); err != nil {
return "", err
}
if err := run.Do("tell the guest the answer", c.message(string(status))); err != nil {
return "", err
}
return status, nil
}
func (c ConfirmBooking) save(status models.Status) func(context.Context) error {
return func(ctx context.Context) error {
booking, err := model.Find[models.Booking](ctx, c.BookingID)
if err != nil {
return err
}
return model.Update(ctx, &booking, db.Values{"status": status})
}
}
// message asks the Laravel app to email the guest, once: a retried step sends the same key.
func (c ConfirmBooking) message(kind string) func(context.Context) error {
return func(ctx context.Context) error {
url := fmt.Sprintf("%s/api/bookings/%d/reminders", services.From(ctx).LaravelURL, c.BookingID)
_, err := httpclient.EnsureSuccessful().
Header("Idempotency-Key", workflow.CurrentStep(ctx).Key).
JSON(map[string]string{"channel": "email", "template": "booking." + kind}).
Post(ctx, url)
return err
}
}
run.Do(name, fn) runs fn once and saves that it succeeded under its name; run.Step(name, fn) does the same for a function that returns a value. A failing step is tried 3 times by default, 10 s and then a minute apart, without holding a worker during the wait.
run.WaitWithin(token, within) suspends the run until another part of the app resumes the token with a Decision, or the time passes; decided says which. The token bookings.2.decision is a name, chosen so the decision handler can build the same one from the URL.
workflow.CurrentStep(ctx).Key is the run’s ID plus the step’s name: the same on every try of that step. Sent as an Idempotency-Key, it lets the Laravel app recognise a retry of a message it already sent (the service lesson built the same idea with a client reference).
4. The rules for Handle
Here is the part that is new. When the run wakes up, the worker calls Handle again from the top. Every step that already ran returns its saved result without running, and the first step that has not run, runs. So Handle must take the same path every time it reaches the same point:
| Rule | Because |
|---|---|
| Every query and HTTP call goes inside a step | outside a step it runs again on every advance, and may return something different |
| Branch only on the fields and on what steps and waits returned | time.Now() or a random number outside a step is different on the next advance |
| Each step has its own name | the name is how a saved result is found again |
| Configuration goes into the fields at the start | a setting changed by a deploy must not change a run in flight |
The last rule is why DecideWithinSeconds is a field, set by the handler from the services, and not read from the services inside Handle. Laravel checks what it can (a reused step name, a wait’s token reused) and fails the run with an error that names the rule.
Starting and resuming
5. Starting a run once
workflow.Start saves the run and queues its first advance. A form submitted twice would start two runs, so the handler uses StartOnce with a key: while a run holds the key, starting again returns that run.
package confirmations
import (
"fmt"
"net/http"
"go.laravel.com/model"
"go.laravel.com/web"
"go.laravel.com/workflow"
"app/models"
"app/services"
"app/workflows"
)
func Store(r *web.Request) *web.Response {
booking, err := model.FromRoute[models.Booking](r, "booking")
if err != nil {
return web.Fail(err)
}
key := fmt.Sprintf("bookings.%d.confirmation", booking.ID)
started, err := workflow.StartOnce(r, key, workflows.ConfirmBooking{
BookingID: booking.ID,
DecideWithinSeconds: services.From(r).DecideWithinSeconds,
})
if err != nil {
return web.Fail(err)
}
return web.JSON(map[string]workflow.RunID{"run": started.ID}).WithStatus(http.StatusAccepted)
}
StartOnce returns started.ID, the run’s ID, and started.Outcome, which says whether the run is new or already existed. The key is given up when the run completes, fails or is cancelled, so the same booking can be asked again later.
6. Resuming it
The host’s answer arrives as a request. workflow.Resume delivers the value to the run that waits for the token:
package decisions
import (
"net/http"
"go.laravel.com/model"
"go.laravel.com/validation"
"go.laravel.com/validation/rule"
"go.laravel.com/web"
"go.laravel.com/workflow"
"app/models"
"app/workflows"
)
type StoreDecision struct {
Decision workflows.Decision `json:"decision"`
}
func (f *StoreDecision) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.Decision, rule.Required, rule.In(workflows.Approved, workflows.Declined)),
)
}
func Store(r *web.Request) *web.Response {
booking, err := model.FromRoute[models.Booking](r, "booking")
if err != nil {
return web.Fail(err)
}
form, err := r.Validate[StoreDecision]()
if err != nil {
return web.Fail(err)
}
resumed, err := workflow.Resume(r, workflows.DecisionToken(booking.ID), form.Decision)
if err != nil {
return web.Fail(err)
}
if resumed == workflow.ResumeNotFound {
return web.Abortf(http.StatusConflict, "Booking %d is not waiting for a decision.", booking.ID)
}
return web.NoContent()
}
HTTP/1.1 202 Accepted
Content-Length: 46
Content-Type: application/json
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: faffc963c2d9eefdb0e88138b38bcafc
{"run":"01a23d67-be60-7024-8807-6aa8ba00c09c"}HTTP/1.1 202 Accepted
Content-Length: 46
Content-Type: application/json
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: faeb00d816230eb70723a964b597e150
{"run":"01a23d67-be60-7024-8807-6aa8ba00c09c"}3 s later:
HTTP/1.1 204 No Content
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: 4b75de8a2b9d05990f9ee75af261107e4 s later:
HTTP/1.1 409 Conflict
Content-Length: 54
Content-Type: application/json
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: ef577eee6343bdf09dc64e4db4bd3859
{"message":"Booking 2 is not waiting for a decision."}Server running at `http://127.0.0.1:8080`. Press Ctrl+C to stop.
POST 202 /api/bookings/2/confirmation 16.5ms
POST 202 /api/bookings/2/confirmation 1.6ms
POST 204 /api/bookings/2/decision 7.5ms
POST 409 /api/bookings/2/decision 2.3ms
Stopping. Waiting up to 20s for the work in progress.Processing jobs from `database:default`. Press Ctrl+C to stop.
laravel.workflow.advance 23.5ms
laravel.workflow.advance 15.4msRun 01a23d67-be60-7024-8807-6aa8ba00c09c
Workflow workflows.ConfirmBooking
Status completed
Queue database:default
Input {"booking_id":2,"decide_within_seconds":172800}
Started 2026-12-03 21:35:38
Finished 2026-12-03 21:35:43
Output "confirmed"
Kind Name Status Tries Took Error
step tell the guest we asked completed 1 9.2ms
wait bookings.2.decision completed 3.03s
step save the status completed 1 1.5ms
step tell the guest the answer completed 1 1.3msThe two confirmation requests answer the same run ID: StartOnce saw the key. The worker advanced the run, sent the first message and suspended at the wait. The decision resumed it: 204. A second decision finds no run waiting for the token, so ResumeNotFound and a 409; a late double click cannot decide anything.
workflow:show lists what the run did: three steps that ran once each, the wait and how long it took, the input, and the output "confirmed", the value Handle returned. The worker log has two advances, one before the wait and one after it.
A token is a name, not a secret: anyone who can reach this route can decide a booking. On the build day the route sits behind the API key of the routes lesson.
7. Through a restart
The same request, but while the run waits, the server and the worker both stop with Ctrl-C and start again, as in a deploy:
HTTP/1.1 202 Accepted
Content-Length: 46
Content-Type: application/json
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: d47fbb88d027ef20f4a91d123dcf1e25
{"run":"01a23d67-ecbf-7c4e-8b9a-7819c37cc39c"}3 s later:
Processing jobs from `database:default`. Press Ctrl+C to stop.
laravel.workflow.advance 12.1msServer running at `http://127.0.0.1:8080`. Press Ctrl+C to stop.
POST 202 /api/bookings/2/confirmation 11.6ms
Stopping. Waiting up to 20s for the work in progress.Started again, as after a deploy:
HTTP/1.1 204 No Content
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: 72a54eccf91d02500430d0605759c62e4 s later:
Server running at `http://127.0.0.1:8080`. Press Ctrl+C to stop.
POST 204 /api/bookings/2/decision 33.6ms
Stopping. Waiting up to 20s for the work in progress.Processing jobs from `database:default`. Press Ctrl+C to stop.
laravel.workflow.advance 16.1msRun 01a23d67-ecbf-7c4e-8b9a-7819c37cc39c
Workflow workflows.ConfirmBooking
Status completed
Queue database:default
Input {"booking_id":2,"decide_within_seconds":172800}
Started 2026-12-03 21:35:50
Finished 2026-12-03 21:35:56
Output "declined"
Kind Name Status Tries Took Error
step tell the guest we asked completed 1 2.0ms
wait bookings.2.decision completed 4.24s
step save the status completed 1 1.4ms
step tell the guest the answer completed 1 1.5msNothing in memory survived, and nothing needed to: the run, its first step and its wait are rows. The new worker took the resumed run, skipped the step that had already run (the message was not sent twice), and went on. This is what the service lesson had to build with a status column and a resume at startup.
8. No answer in time
With BOOKING_DECIDE_WITHIN_SECONDS=3 and no decision at all:
HTTP/1.1 202 Accepted
Content-Length: 46
Content-Type: application/json
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: ba3f0a6e8648a6638f2de9b3888c40d5
{"run":"01a23d68-1f63-7d53-b2d0-9280027d7e64"}9 s later:
Server running at `http://127.0.0.1:8080`. Press Ctrl+C to stop.
POST 202 /api/bookings/2/confirmation 12.0ms
Stopping. Waiting up to 20s for the work in progress.Processing jobs from `database:default`. Press Ctrl+C to stop.
laravel.workflow.advance 17.2ms
laravel.workflow.advance 14.4msRun 01a23d68-1f63-7d53-b2d0-9280027d7e64
Workflow workflows.ConfirmBooking
Status completed
Queue database:default
Input {"booking_id":2,"decide_within_seconds":3}
Started 2026-12-03 21:36:03
Finished 2026-12-03 21:36:08
Output "declined"
Kind Name Status Tries Took Error
step tell the guest we asked completed 1 1.8ms
wait bookings.2.decision completed 3.03s
step save the status completed 1 1.9ms
step tell the guest the answer completed 1 1.2msworkflow:show lists the wait as completed after 3 s with no value: WaitWithin returned decided false, so the booking was declined and the guest told, with no scheduled command looking for old requests. The timeout is a delayed job on the queue, so it needs a running worker; a worker that was down at that moment picks it up when it starts.
Coming from PHP
<?php
namespace App\Jobs;
use App\Models\Booking;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
// Step 1 of 3. Step 2 is the host's request to /decision, which updates the status
// and dispatches NotifyGuest. Step 3 is a scheduled command that declines every
// pending booking older than 48 hours and dispatches NotifyGuest for each.
class AskHost implements ShouldQueue
{
use Queueable;
public function __construct(public Booking $booking) {}
public function handle(): void
{
$this->booking->update(['status' => 'awaiting_host']);
NotifyGuest::dispatch($this->booking, 'received');
}
}
The PHP version spreads one process over a job, a controller, a scheduled command and a status column whose values are the states. Each piece is simple; the process exists only in your head and in the comments. Laravel Go’s workflow keeps it in one method that reads in order, and stores the state for you.
The price is the rules of section 4: Handle is replayed, so it must be deterministic, and a change to a workflow with runs in flight needs care (rename a step and its runs run it again). PHP Laravel has no workflows in the framework itself; the Durable Workflow package (formerly Laravel Workflow) adds them on Laravel’s queues.
PracticeThe workflows guide; a reminder before check-in
Read workflows.md in the app’s bundled docs: “Steps”, “Rules for Handle”, “Sleeping”, and “Waiting and resuming”.
Exercise: remind the guest
After a confirmed booking, make the workflow sleep until 09:00 UTC on the day before the check-in with run.SleepUntil, then send a reminder step. Compute the time from the booking’s check_in inside a step (run.Step("reminder time", …)), not in Handle directly: which rule of section 4 would the other way break? Test it with a check-in tomorrow and a running worker, and read workflow:show while it sleeps.
Remember
Handleis replayed from the top: all I/O inside steps, branches only on fields and step results.- Settings that shape a run go into its fields when it starts.
- Start with
StartOnceand a key; a token names a wait, it is not a secret.
Tomorrow: the build day: the analysis service of Week 5, on Laravel Go.