Durable Workflows & Jobs
“A Workflow Definition must be deterministic because Temporal reruns it to rebuild state after a failure.” — Temporal, Understanding Temporal
Summary: A durable workflow remembers progress, decisions and waits after the process executing it disappears. Focus: Temporal/Cadence execution, deterministic replay, activity boundaries, timers, cancellation, safe deployments, Laravel chains/batches and database reconciliation. Learning goal: Choose between a job, a persisted state machine and a workflow engine, then explain what happens at every crash boundary.
This page owns the lifecycle of work that lasts longer than one process. Saga owns compensation, Outbox owns atomic state-to-message publication, and Delivery guarantees explains end-to-end effects. Those mechanisms support a workflow; none replaces its progress model.
Page map
| Looking for | Go to |
|---|---|
| Job versus workflow | One minute |
| How restart reconstructs local variables | Replay |
| Why an activity can run twice | Activities |
| Which timeout to configure | Timeouts |
| Human approval and cancellation | Messages, cancellation |
| Changing code while runs are open | Versioning |
| A real SDK example and a small SQL alternative | Go |
| Chains, batches and missed schedules | Laravel |
| Broker roles and limits | Broker differences |
| Recovery experiments | Lab |
Everything in one minute
| Primitive | Durable record | Restart behavior | Missing responsibility |
|---|---|---|---|
| Plain goroutine / PHP process | None unless application writes it | Stack disappears | Everything after the last external checkpoint |
| Persistent queue job | Job payload and delivery state, according to backend durability | Handler may execute from its beginning | Business progress inside the handler |
| Laravel chain | Serialized successor jobs carried with queue work | Queue retries current job; successors follow successful execution | Application checkpoints, branching and repair policy |
| Laravel batch | Job messages plus batch metadata | Workers resume remaining deliveries | Domain correctness of outputs and callback effects |
| SQL checkpoint runner | Run row, step, version and absolute due time | Load checkpoint; repeat uncertain step safely | You implement concurrency, deadlines, recovery and evolution |
| Temporal / Cadence | Execution history and engine persistence | Reconstruct workflow state; redispatch unfinished work | Idempotent activities, business failure policy and operations |
| Distinction | First side | Second side |
|---|---|---|
| Workflow Task / Activity Task | Compute the next orchestration decisions | Execute an external operation |
| Replay / retry | Rebuild from recorded outcomes | Perform another attempt whose outcome is not recorded as successful |
| Workflow ID / Run ID | Logical business execution identity | One execution run in a chain of runs |
| Timer / schedule | Resume an existing execution later | Start executions at calendar or interval times |
| Cancellation / termination | Cooperative request, allowing cleanup code | Server-side stop; workflow cleanup is not executed |
| Durability / availability | State remains recoverable | Work can make progress now |
| Technical retry / business recovery | Retry a recoverable call | Resolve rejected, ambiguous or obsolete business work |
Where it comes from
Queue frameworks made background jobs practical: persist work, give it to a worker, retry failures. A multiday process adds a different problem: the application must remember which operations finished, which decisions were taken and which future deadlines remain outstanding.
Cadence calls its model a fault-oblivious stateful workflow. Temporal uses the term Durable Execution. Both separate deterministic orchestration from activities that perform I/O, and rebuild orchestration state from a persisted history. Their SDKs, configuration defaults and versioning features are separate products; copying a Temporal timeout policy into Cadence without checking its SDK is unsafe. Cadence workflows and activities describe that boundary.
Laravel's queue framework provides a useful middle ground: persistent job delivery, composition and scheduling. It does not promise Temporal-style replay of arbitrary PHP local variables.
Why this exists
An order confirmation runs in milliseconds; a review request may wait three days. A deployment occurs between them. Saving only the final result leaves the restarted program unable to distinguish “not sent” from “sent, but the success response was lost.” The same issue occurs during account provisioning, document approval, exports and subscription renewal.
| Simpler choice | Extra obligation when the process grows |
|---|---|
| One handler performs all steps | Earlier side effects may repeat after a late failure |
| Put the next job on a queue | Commit-to-publish gap can strand the run |
| Sleep inside a worker | Process death loses the wait and consumes capacity while alive |
| Save a step number | Concurrent resumes, version changes and remote ambiguity need rules |
| Adopt an engine | Operate persistence, compatible workers, quotas and recovery procedures |
Three misunderstandings to discard early: durability does not make remote calls exactly-once; a durable timer does not guarantee execution at its exact timestamp; and a workflow engine does not infer the business meaning of cancellation.
An everyday picture
A permit office keeps a case file. Each completed inspection has a signed result; a reminder has a due date; an approval has an identifiable author. Another clerk can resume the case after a staff change. Re-reading the file does not repeat the inspection. An inspection whose result never reached the office may need verification or repetition. A clerk also checks overdue files instead of assuming every reminder was delivered.
What it is really about
A workflow is a recoverable coordination process. Its state includes control flow, stable identity, input and decisions, outstanding work and future obligations. Its effects usually live elsewhere. Durable execution ties those pieces together without pretending they share one transaction.
Workflow identity and admission Must-know
In plain words: “Run this order's fulfillment” needs an identity that survives HTTP retries and worker restarts.
Common misunderstanding: A fresh random Workflow ID on every request makes starts safe. It actually turns a retried request into a second execution.
Definition: Temporal identifies an execution using Namespace, Workflow ID and Run ID. A logical Workflow ID may span runs created by retry or Continue-As-New. A workflow definition is the code; an execution is an instance; a Workflow Task is one opportunity to advance that instance.
1 Client sends Start(order:42); response is lost.
2 Client retries Start(order:42), with the same business input.
3 Conflict policy chooses existing execution or rejects the duplicate.
4 Client queries that execution instead of creating order:42-copy.Real scenarios: webhook retries, double-clicked provisioning, monthly invoices whose identity includes the billing period.
| Product | Identity rule to configure | Application responsibility |
|---|---|---|
| Temporal | Conflict policy for an open execution; reuse policy for closed executions | Match input and domain generation; retention is not an eternal dedup database |
| Cadence | Workflow ID uniqueness within a Domain; WorkflowIdReusePolicy | Use Cadence's documented policy names and defaults |
| Laravel / SQL runner | Unique workflow_id in the business database | Never reset an existing completed row on duplicate submission |
How to use it: save an immutable input snapshot or a versioned reference before dispatch. Include a deliberate business generation in the identity when rerunning is intended. A transport attempt ID is useful for logs, not as the business idempotency key.
Event History and deterministic replay Must-know
In plain words: The engine replays recorded facts to reconstruct where the program was, then schedules only work that still needs an outcome.
Common misunderstanding: Replay reruns successful activity HTTP calls. Recorded activity results are supplied from history; the activity implementation is not called just to replay them.
Definition: Workflow code must emit a sequence of Commands compatible with its Event History. Scheduling an Activity or Timer is a Command; its recorded scheduling/completion/firing is an Event. An in-memory worker cache improves performance but is not the source of truth.
1 Worker A emits ScheduleActivity(receipt); service persists scheduling.
2 Activity completes; service records its result.
3 Workflow starts Timer(72h); worker A disappears.
4 Worker B replays: receipt returns recorded result, existing timer is reconstructed.
5 Timer fires; worker B schedules review, rather than sending receipt again.| In Temporal workflow code | Use instead | Why |
|---|---|---|
time.Now() for a business decision | workflow.Now(ctx) | Replay must observe the recorded logical execution time |
time.Sleep / native timer | workflow.Sleep / workflow.NewTimer | Wait survives worker loss |
| Native goroutine or channel | workflow.Go, workflow channels and selectors | SDK controls deterministic scheduling |
| Map iteration that emits commands | Sorted keys | Go map order is not deterministic |
| HTTP, SQL, file reads | Activity | External outcomes are not reproducible from code alone |
| Random value / configuration read | Activity or carefully chosen SideEffect | Persist the chosen value; do not reread changing configuration |
Real scenarios: replay after a deployment, eviction from the sticky cache, recovery on another host.
How to use it: keep workflow logic small and use workflow.GetLogger for replay-aware logging. SideEffect records a small nondeterministic value; its function can execute again if the Workflow Task fails before the marker is committed. It is not a safe place for a payment, email or other irreversible effect. MutableSideEffect supports recorded changing values with an equality check, not unrestricted I/O.
Activities and idempotent steps Must-know
In plain words: An activity does the actual work, but a missing completion record can make the engine ask for it again.
Common misunderstanding: “The workflow resumed at the right line, so a card cannot be charged twice.” Correct control flow cannot resolve an unrecorded external result by itself.
Definition: An Activity Execution may contain multiple Activity Task attempts. Activity state is not reconstructed like workflow state. The external system must make repeated operations safe or expose a way to look up the original result.
1 Worker sends receipt with key order:42:receipt:v1.
2 Provider persists result; worker dies before reporting completion.
3 Activity times out; another worker repeats the same operation and key.
4 Provider returns the original result; engine records completion.| Boundary | Correct protection | Remaining limit |
|---|---|---|
| Local DB change plus checkpoint | One database transaction | Only covers that database connection |
| Remote API plus checkpoint | Stable provider idempotency key and immutable parameters | Provider key retention must cover recovery horizon |
| Provider lacks dedup but supports lookup | Stable external reference and reconciliation | Ambiguous lookup may require human review |
| Provider supports neither | Explicit duplicate risk or manual approval | Engine cannot manufacture exactly-once effects |
Real scenarios: charge capture, label creation, cloud VM creation, emailing a receipt. See Inbox and idempotent consumers for dedup storage mechanics.
How to use it: derive the operation key from business identity plus logical step and generation, not attempt number or Run ID. A local “done” check alone cannot close the external-effect-to-checkpoint gap. Local Activities reduce scheduling overhead but still need idempotency and are a poor fit for long remote operations requiring independent routing or heartbeats.
Timeouts, retries and heartbeats Must-know
In plain words: Different clocks answer different questions: waiting for capacity, executing one attempt, or exhausting the total activity budget.
Common misunderstanding: Increasing every timeout makes work more reliable. It can merely hide dead workers and let stale attempts overlap new ones.
Definition: Temporal Activity options bound scheduling and execution; retries are governed by the Retry Policy within those bounds. At least StartToCloseTimeout or ScheduleToCloseTimeout must be supplied. Temporal Activity timeouts defines their separate meanings.
| Temporal option | Measures | Decision |
|---|---|---|
ScheduleToStartTimeout | Queue wait before an attempt starts | Non-retryable timeout; monitor capacity rather than repeatedly enqueueing onto the same unavailable fleet |
StartToCloseTimeout | One attempt after worker pickup | Must exceed valid operation duration but detect a lost attempt promptly |
ScheduleToCloseTimeout | Entire Activity Execution including retries and waiting | Overall activity budget |
HeartbeatTimeout | Gap between reported heartbeats | Detect long-activity stalls and deliver cancellation |
WorkflowTaskTimeout | One Workflow Task | Workflow code must yield promptly; not a business deadline |
WorkflowRunTimeout | One Workflow run | Includes its waits; a new run has a distinct budget |
WorkflowExecutionTimeout | Execution chain across retries / Continue-As-New | Use only when a whole-chain deadline is truly required |
1 Activity scheduled; fleet is busy (Schedule-To-Start interval).
2 Worker starts; operation hangs (Start-To-Close interval).
3 Timeout records failure; Retry Policy schedules attempt two.
4 Total Schedule-To-Close budget expires; workflow receives failure.Real scenarios: a 20-second HTTP call, a 30-minute video export, a batch whose queue delay consumes its SLA.
How to use it: give remote clients their own connect/read deadlines. A Temporal timeout cannot forcibly stop external work already accepted by another service. Long activities periodically call activity.RecordHeartbeat; retry uses GetHeartbeatDetails to resume after the last reported chunk. Repeating the last unconfirmed chunk must be safe because heartbeats may be throttled.
| Retry parameter / failure | Meaning |
|---|---|
InitialInterval, BackoffCoefficient, MaximumInterval | Retry delay policy; defaults are not an application budget |
MaximumAttempts | Includes the first attempt; 0 means unlimited for Temporal's Retry Policy |
NonRetryableErrorTypes / nonretryable application error | Reject invalid work without futile activity retries |
| Workflow Task failure | Engine normally retries the task; execution may remain open and stuck |
| Activity failure | Workflow receives error after policy/budget resolution |
| Workflow failure | Business execution closes failed; Workflow retry is a separate opt-in policy |
For delay formulas, jitter and retry budgets see Retry and backoff. Do not stack unlimited HTTP retries, activity retries and workflow retries around the same operation.
Durable timers and schedules Must-know
In plain words: A timer remembers a future obligation even when no worker is running.
Common misunderstanding: A durable timer means a thread sleeps for days, or that an action happens exactly at the due time. The engine stores the wait; worker availability still determines completion latency.
Definition: A timer resumes an existing execution; a schedule initiates occurrences according to a calendar or interval. An absolute business deadline and a relative “72 hours after completion” wait are different requirements.
Real scenarios: review reminders, approval expiry, nightly reconciliation, periodic subscription renewal.
| System | Persistent wait | Missed occurrence behavior |
|---|---|---|
| Temporal / Cadence workflow | SDK durable timer | Fire/resume after recovery, subject to service and worker availability |
| Temporal Schedule | Schedule specification and policy | Configure overlap, catchup window and explicit backfill |
| Laravel delayed job | Driver-specific delayed representation | Limited by backend, retention and transport recovery |
| Laravel scheduler | Evaluation when schedule:run / schedule:work runs | No generic durable ledger of every missed tick |
| SQL runner | wake_at persisted once | Reconciler reads all overdue rows |
How to use it: store due times in UTC and keep calendar business rules explicit. Temporal Schedule overlap policies include Skip, BufferOne, BufferAll, CancelOther, TerminateOther and AllowAll; select based on whether missed periods can merge or must each run. Backfill can trigger historical periods, so occurrence identity must prevent accidental duplicate billing. Laravel onOneServer coordinates a tick; withoutOverlapping limits concurrent executions; neither catches up a missed business period. DST can skip or repeat local clock times. Temporal schedules and Laravel scheduling document the mechanisms.
Signals, Queries, Updates and human work Important
In plain words: A waiting workflow can receive a decision without holding an HTTP request open.
Common misunderstanding: Successfully sending an approval signal proves the approval operation finished. It proves admission of the message, not every downstream effect.
Definition: Temporal offers asynchronous Signals, read-only Queries and tracked Updates that can validate and return a result. Cadence has its own signals and queries; do not assume API parity for every Temporal feature.
| Temporal API family | Mutates workflow state? | Persisted processing significance | Example |
|---|---|---|---|
| Signal | Yes, in workflow handler | Recorded message; sender does not await handler result | Approver submits a decision |
| Query | No | Read-only observation; not a history event | Display current approval stage |
| Update | Yes | Accepted update is tracked and can return a result | Validate and apply a changed delivery address |
| Signal-With-Start | Yes | Start-if-needed and signal through one service operation | Ensure customer coordinator exists before sending event |
Real scenarios: manual fraud review, an external callback, user-edited shipping instructions.
How to use it: authenticate at the API boundary and validate business state in the workflow. Carry a business request ID for deduplication across separate sends. Use a timer plus a selector / AwaitWithTimeout for approval expiry. Decide which outcome wins when approval races the timer; the recorded ordering makes the decision replayable, not automatically correct for your policy. Finish active handlers before completing or continuing the workflow. Go message passing covers handler constraints.
Cancellation, termination and cleanup Important
In plain words: “Please stop” and “this execution is now closed” are different operations.
Common misunderstanding: Cancelling a workflow reverses its previous effects or instantly kills an HTTP request already accepted by a provider.
Definition: Cancellation is cooperative and propagates through SDK contexts; termination closes an execution without running workflow cleanup. Compensation is an explicit business action, explained in Saga.
1 Operator requests cancellation while export activity is running.
2 Activity heartbeats and learns of cancellation; stops at a safe boundary.
3 Workflow waits for cancellation acknowledgement if configured.
4 Cleanup activity uses a disconnected context; failure remains observable.| Mechanism | What it does | What it does not do |
|---|---|---|
WaitForCancellation | Lets workflow wait for activity cancellation completion | Guarantee an unresponsive external process stops |
workflow.NewDisconnectedContext | Allows bounded cleanup after parent cancellation | Turn cleanup into an infallible rollback |
| Termination | Immediately closes execution at service level | Run deferred workflow cleanup |
| Laravel batch cancellation | Marks batch cancelled; jobs must check / use skip middleware | Undo completed jobs or interrupt all active jobs |
| SQL status + version guard | Stops future checkpoint advancement from stale writers | Undo a remote operation already in flight |
Real scenarios: cancelled data export, user-closing an account during provisioning, operator stopping a broken rollout.
How to use it: document remaining external effects and reconcile them after cancellation. Cleanup needs its own timeout, retry budget and escalation path. Never hide a cleanup failure behind a “cancelled successfully” business status. Go cancellation shows the SDK boundary.
Versioning, history growth and Continue-As-New Must-know
In plain words: Today's deployment must still understand yesterday's unfinished processes.
Common misunderstanding: Pure refactoring is always replay-safe because the new code compiles. Reordering an activity and a timer can change the command sequence while all ordinary unit tests pass.
Definition: Workflow versioning preserves compatibility with existing histories. Patching records a version marker at a change point; Worker Versioning routes work to appropriate deployment versions. Continue-As-New ends a run successfully and starts another with the same Workflow ID, new Run ID and fresh history.
| Change / concern | Safe approach | Operational cost |
|---|---|---|
| Add an activity before an old timer | workflow.GetVersion branch or compatible pinned workers | Retain old path / fleet until no history requires it |
| Change activity internals | Preserve input/output contract and idempotency semantics | Retried old activity can run on new code |
| Change input schema | Compatible defaults or a versioned input | Keep decoding historical payloads possible |
| Endless signal processing | Continue-As-New with explicit carried state | Drain handlers and retain request dedup state |
| Large fan-out | Bounded child workflows | Parent still accumulates child lifecycle events |
| Giant activity result | Store artifact externally; return a reference | External object lifecycle must outlast replay needs |
Real scenarios: a month-long approval running across ten deployments, perpetual subscription coordinators, imports with millions of rows.
How to use it: run replay tests against representative exported histories before rollout. GetVersion(ctx, "change-id", workflow.DefaultVersion, 1) selects the old path for histories predating the marker and records the new path for new execution through that point. Do not remove the old branch merely because new starts look healthy. Current Temporal Worker Versioning differs from legacy build-ID APIs; consult the current rollout documentation rather than mixing generations. Our pinned SDK sample does not configure that deployment feature. Versioning and Continue-As-New explain those lifecycles.
Continue-As-New is not arbitrary garbage collection: carry pending business state, dedup keys and intended deadlines explicitly. Wait for handlers to finish and resolve child-workflow parent-close behavior. GetContinueAsNewSuggested can guide rollover; history event and byte limits depend on deployment/service limits. Do not hard-code an assumed unlimited history.
Reconciliation and checkpoints Must-know
In plain words: Periodically compare what should be true with what is actually recorded, then safely repair the gap.
Common misunderstanding: Scanning only existing step rows finds every stalled workflow. A crash before step one creates no step row to scan.
Definition: A reconciliation loop derives unfinished obligations from an authoritative run registry, including never-started runs and overdue waits. A checkpoint stores progress; a wake-up message merely reduces the time before checking it again.
1 Commit workflow_runs(order:42, step=0).
2 Process dies before queue dispatch; no step row or message exists.
3 Reconciler scans running base rows and dispatches / executes step 0.
4 Effect succeeds; version-checked checkpoint advances; duplicate wakes become safe.| Required invariant | Why it matters |
|---|---|
| Register run before relying on a message | Makes first-dispatch loss discoverable |
Persist absolute wake_at once | Restart cannot postpone the deadline indefinitely |
| Compare status and version when advancing | Stale workers cannot overwrite cancellation or newer progress |
| Bound failure count across queue messages | Fresh deliveries must not reset the workflow's total retry budget |
| Scan fairly with pagination / partitions | One poison page must not starve later runs |
| Mark blocked work explicitly | Operator repair is distinct from endless technical retry |
| Preserve original operation identity on repair | Manual retry must not duplicate a completed remote effect |
Real scenarios: lost initial dispatch, callback failure after a batch, missing delayed message, deployment during a checkpoint update.
How to use it: reconcile domain outputs as well as technical job counts. A completed batch does not prove an external export artifact exists. A zero queue backlog does not prove every due workflow has a message. For atomic publication use Outbox; for a deliberate polling design publish loss is tolerated only because the full recovery path exists and its delay is acceptable.
Mechanics: from command to next decision
Temporal's service persists history and schedules tasks; application workers run workflow and activity code. Cadence calls its routing primitive a Task List; Temporal calls it a Task Queue. These are engine-managed mechanisms, not RabbitMQ queues or Kafka topics supplied by the application.
| Record / component | Responsibility | Failure observation |
|---|---|---|
| Workflow Event History | Durable decisions and outcomes | Missing completion means activity result is uncertain |
| Workflow Task | Replay plus new commands | Repeated task failures can leave an execution open |
| Activity Task | One worker attempt | Timeout or heartbeat gap can cause another attempt |
| Task Queue / Task List | Match tasks to appropriate workers | Schedule-to-start delay rises when no suitable worker polls |
| Worker sticky cache | Avoid replaying every task from the beginning | Cache loss affects cost, not correctness |
| Visibility / Search Attributes | Find executions by business fields | Search is an operational index, not the domain transaction ledger |
| Payload converter / codec | Serialize and optionally protect data | Old histories must remain readable after upgrades |
History inputs and results have retention and privacy consequences. Keep large files and secrets out of history where possible; use references and controlled codecs. Namespace isolation and access control do not replace application authorization. See Messaging security for the broader policy.
| Error / state | Interpretation | Response |
|---|---|---|
WorkflowExecutionAlreadyStarted | Start conflicts with existing identity/policy | Look up intended execution; do not blindly generate another ID |
TimeoutError | A named activity/workflow clock expired | Inspect timeout type and remote outcome before changing policy |
ApplicationError | Application-classified failure | Retry only eligible types within budget |
CanceledError | Cooperative cancellation reached execution | Run bounded cleanup if required; preserve cancellation semantics |
| Nondeterminism error | Commands no longer match history | Roll back / deploy compatible code, inspect history; retries alone cannot repair it |
ResourceExhausted | Service quota or capacity constraint | Reduce admission / concurrency and inspect configured limits |
SQL ErrConflict in this sample | Another checkpoint writer or terminal transition won | Reload current state; do not overwrite it |
Laravel blocked run | Application retry budget exhausted | Inspect provider result and repair explicitly |
Solving classic problems
Save the run before the first trigger
For the SQL example, the business transaction inserts the run. A stable identifier is already chosen by the caller. Do not create a fresh run when the same request is retried.
BEGIN;
-- Write the associated business change here, on this same connection.
INSERT INTO workflow_runs(workflow_id, definition)
VALUES ('order:42', 1)
ON CONFLICT (workflow_id) DO NOTHING;
COMMIT;
-- Dispatch a wake-up after commit. A missing wake-up is repaired by the scan.A local side effect can share a checkpoint transaction. A remote one cannot, so repeat it with the same key and advance only with the expected version:
UPDATE workflow_runs
SET current_step = 1, version = version + 1, updated_at = now()
WHERE workflow_id = 'order:42' AND version = 0 AND status = 'running';
-- Exactly one updated row wins. Zero rows means reload, not force overwrite.Match the repair to the uncertainty
| Problem | Solution | Benefit | Cost / limit |
|---|---|---|---|
| Activity succeeded but completion lost | Same external idempotency key | Repeat without duplicate effect | Provider contract and retention |
| Long wait lost on restart | History timer or SQL absolute due time | Wait survives process loss | Persistence and scheduling latency |
| First queue publish lost | Run registry reconciliation or transactional outbox | No permanently invisible run | Scan latency or relay operations |
| User cancels during remote call | Terminal version guard plus provider reconciliation | Prevent future progression | In-flight effect may still finish |
| Bad deployment breaks replay | Compatibility patch / restore old worker | Recover open executions | Maintain multiple versions |
| Callback failed after batch completion | Domain-output reconciler | Repair missing summary/action | Additional authoritative output records |
| Repeated permanent error | Mark blocked and retain evidence | Stops retry amplification | Explicit operator / business intervention |
Make the retry horizon visible
Track run age, current step age, next due time, attempts per business operation, heartbeat age, schedule-to-start latency, blocked count and overdue duration. Alert on “overdue with no progress” separately from “waiting until tomorrow.” A workflow that has no due work is healthy even if its age is months. A queue that is empty can coexist with a stranded workflow.
Choosing the mechanism
| Workload | Choose | Add | Reason |
|---|---|---|---|
| Resize one uploaded image | Queue job | Idempotent output path | One recoverable operation |
| Three short ordered operations | Laravel chain | Per-step idempotency and failure handling | Low orchestration complexity |
| Independent import chunks | Laravel batch | Batchable jobs, output ledger, callback repair | Parallel progress with bounded fan-out |
| A small fixed multiday flow | SQL runner plus reconciler | Version guard, due index, total retry budget | Explicit affordable state model |
| Human approval, branches, repeated callbacks | Temporal / Cadence | Message dedup, replay testing, cancellation policy | Engine manages durable coordination |
| Perpetual account coordinator | Engine with Continue-As-New | Carried dedup state and bounded history | Keeps lifecycle long and each history bounded |
| Audit/legal record of business events | Domain event store / ledger | Retention and access rules | Workflow history is not automatically the domain source of truth |
Go
Before
A function's call stack is the only progress record. Restarting from its entry point repeats receipt creation; sleeping holds resources and disappears with the process.
package main
import "time"
func fulfil(reserve, receipt, review func() error) error {
if err := reserve(); err != nil {
return err
}
if err := receipt(); err != nil {
return err
}
time.Sleep(72 * time.Hour) // A restart loses both progress and this timer.
return review()
}
func main() {}After: real Temporal SDK
The workflow calls a real go.temporal.io/sdk Activity and durable timer. Gateway is an application port supplied by the host; it must implement the stated provider idempotency contract. It is not a substitute Temporal API. Register activities and workflow on the same task queue, and reuse the client within the process.
// Package temporalflow uses the real Temporal Go SDK, not local stand-ins.
package temporalflow
import (
"context"
"time"
"go.temporal.io/sdk/temporal"
"go.temporal.io/sdk/workflow"
)
type Input struct{ OrderID string }
type Operation struct{ OrderID, Key, Step string }
// Gateway must atomically deduplicate Key and reject changed parameters for it.
// The provider must retain the key throughout retries, reset and recovery.
type Gateway interface {
Apply(context.Context, Operation) error
}
type Activities struct{ Gateway Gateway }
func (a *Activities) Apply(ctx context.Context, op Operation) error {
return a.Gateway.Apply(ctx, op)
}
func OrderWorkflow(ctx workflow.Context, in Input) error {
ctx = workflow.WithActivityOptions(ctx, workflow.ActivityOptions{
StartToCloseTimeout: 30 * time.Second,
ScheduleToCloseTimeout: 10 * time.Minute,
RetryPolicy: &temporal.RetryPolicy{
InitialInterval: time.Second, BackoffCoefficient: 2,
MaximumInterval: time.Minute, MaximumAttempts: 5,
NonRetryableErrorTypes: []string{"InvalidOrder"},
},
})
var a *Activities
for _, step := range []string{"reserve", "receipt"} {
// Business identity survives Activity attempts and Workflow Run IDs.
op := Operation{in.OrderID, "order:" + in.OrderID + ":" + step + ":v1", step}
if err := workflow.ExecuteActivity(ctx, a.Apply, op).Get(ctx, nil); err != nil {
return err
}
}
// This persists a timer. No worker thread is occupied for three days.
if err := workflow.Sleep(ctx, 72*time.Hour); err != nil {
return err
}
return workflow.ExecuteActivity(ctx, a.Apply,
Operation{in.OrderID, "order:" + in.OrderID + ":review:v1", "review"}).Get(ctx, nil)
}package temporalflow
import (
"context"
enumspb "go.temporal.io/api/enums/v1"
"go.temporal.io/sdk/client"
"go.temporal.io/sdk/worker"
)
const TaskQueue = "order-workflows"
// The caller owns client.Dial, credentials, namespace and process shutdown.
func RunWorker(c client.Client, g Gateway, stop <-chan interface{}) error {
w := worker.New(c, TaskQueue, worker.Options{})
w.RegisterWorkflow(OrderWorkflow)
w.RegisterActivity(&Activities{Gateway: g})
return w.Run(stop)
}
func Start(ctx context.Context, c client.Client, orderID string) (client.WorkflowRun, error) {
return c.ExecuteWorkflow(ctx, client.StartWorkflowOptions{
ID: "order:" + orderID, TaskQueue: TaskQueue,
WorkflowIDReusePolicy: enumspb.WORKFLOW_ID_REUSE_POLICY_REJECT_DUPLICATE,
WorkflowIDConflictPolicy: enumspb.WORKFLOW_ID_CONFLICT_POLICY_USE_EXISTING,
}, OrderWorkflow, Input{OrderID: orderID})
}The sample pins SDK v1.33.0 for the Go 1.24 module and demonstrates stable workflow/activity APIs. It is not a prescription for current Worker Deployment configuration. No Temporal server is started by unit tests.
After: explicit SQL checkpoint alternative
This deliberately small runner advances one transition per wake. It models a fixed versioned sequence, not Temporal replay. A wait transition persists wake_at once. Duplicate remote calls remain possible; the Run callback must deduplicate the stable business operation key.
// Package workflow demonstrates a small checkpoint runner, not deterministic replay.
package workflow
import (
"context"
"errors"
"fmt"
"time"
)
var ErrWaiting = errors.New("workflow waiting")
var ErrConflict = errors.New("workflow changed concurrently")
type State struct {
ID string
Definition int
Step int
Version int64
Status string
WakeAt time.Time
}
type Store interface {
Load(context.Context, string) (State, error)
// CAS replaces only a still-running row at the expected version.
CAS(context.Context, State, State) error
Due(context.Context, time.Time, int) ([]string, error)
}
type Step struct {
Name string
Wait time.Duration
// Run may execute concurrently or again after a lost checkpoint.
// It must use key for provider-side idempotency, including parameter checks.
Run func(ctx context.Context, key string) error
}
type Runner struct {
Store Store
Steps []Step
Now func() time.Time
Definition int
}
// Tick performs at most one transition. Trigger delivery is only a wake-up hint.
func (r Runner) Tick(ctx context.Context, id string) error {
if r.Now == nil || r.Store == nil {
return errors.New("runner requires Store and Now")
}
seen := map[string]bool{}
for _, step := range r.Steps {
if step.Name == "" || seen[step.Name] || step.Wait < 0 {
return errors.New("invalid or duplicate step name/wait")
}
seen[step.Name] = true
}
s, err := r.Store.Load(ctx, id)
if err != nil {
return err
}
if s.Status != "running" {
return nil
}
if s.Definition != r.Definition {
return errors.New("unsupported workflow definition")
}
if s.Step < 0 || s.Step >= len(r.Steps) {
return errors.New("invalid checkpoint")
}
step := r.Steps[s.Step]
next := s
now := r.Now()
if step.Wait > 0 {
if s.WakeAt.IsZero() {
next.WakeAt = now.Add(step.Wait)
return r.Store.CAS(ctx, s, next)
}
if now.Before(s.WakeAt) {
return ErrWaiting
}
} else {
if step.Run == nil {
return errors.New("missing step handler")
}
key := fmt.Sprintf("%s:%s:v%d", s.ID, step.Name, s.Definition)
if err = step.Run(ctx, key); err != nil {
return err
}
}
next.Step++
next.WakeAt = time.Time{}
if next.Step == len(r.Steps) {
next.Status = "completed"
}
return r.Store.CAS(ctx, s, next)
}package workflow
import (
"context"
"database/sql"
"time"
)
// Create the run before publishing any wake-up; the reconciler also finds runs
// for which the first publish never happened. Immutable input belongs with it.
const Schema = `CREATE TABLE workflow_runs (
workflow_id text PRIMARY KEY,
definition integer NOT NULL,
current_step integer NOT NULL DEFAULT 0,
version bigint NOT NULL DEFAULT 0,
status text NOT NULL DEFAULT 'running',
wake_at timestamptz,
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX workflow_due ON workflow_runs (wake_at, workflow_id)
WHERE status='running';`
type Postgres struct{ DB *sql.DB }
func (p Postgres) Load(ctx context.Context, id string) (State, error) {
var s State
var wake sql.NullTime
err := p.DB.QueryRowContext(ctx, `SELECT workflow_id,definition,current_step,version,status,wake_at
FROM workflow_runs WHERE workflow_id=$1`, id).Scan(&s.ID, &s.Definition, &s.Step, &s.Version, &s.Status, &wake)
if wake.Valid {
s.WakeAt = wake.Time
}
return s, err
}
func (p Postgres) CAS(ctx context.Context, old, next State) error {
var wake any
if !next.WakeAt.IsZero() {
wake = next.WakeAt
}
res, err := p.DB.ExecContext(ctx, `UPDATE workflow_runs
SET current_step=$3,status=$4,wake_at=$5,version=version+1,updated_at=now()
WHERE workflow_id=$1 AND version=$2 AND status='running'`, old.ID, old.Version, next.Step, next.Status, wake)
if err != nil {
return err
}
n, err := res.RowsAffected()
if err != nil {
return err
}
if n != 1 {
return ErrConflict
}
return nil
}
func (p Postgres) Due(ctx context.Context, now time.Time, limit int) ([]string, error) {
rows, err := p.DB.QueryContext(ctx, `SELECT workflow_id FROM workflow_runs
WHERE status='running' AND (wake_at IS NULL OR wake_at<=$1)
ORDER BY updated_at,workflow_id LIMIT $2`, now, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var ids []string
for rows.Next() {
var id string
if err := rows.Scan(&id); err != nil {
return nil, err
}
ids = append(ids, id)
}
return ids, rows.Err()
}package workflow
import (
"context"
"errors"
)
// Reconcile directly advances a bounded page. Publishing a wake-up instead is
// also valid, but must not mark the workflow complete or clear its due time.
// In production paginate fairly and record next_attempt_at + blocked failures;
// otherwise poison runs can monopolize the first page indefinitely.
func (r Runner) Reconcile(ctx context.Context, limit int) error {
if r.Now == nil || r.Store == nil || limit <= 0 {
return errors.New("reconciler requires Store, Now and positive limit")
}
ids, err := r.Store.Due(ctx, r.Now(), limit)
if err != nil {
return err
}
var failures []error
for _, id := range ids {
if err := ctx.Err(); err != nil {
return err
}
err := r.Tick(ctx, id)
if err != nil && !errors.Is(err, ErrWaiting) && !errors.Is(err, ErrConflict) {
failures = append(failures, err)
}
}
return errors.Join(failures...)
}Construct the runner with Runner{Store: Postgres{DB: db}, Steps: steps, Now: time.Now, Definition: 1}; step names must be nonempty and unique because they participate in the operation key.
The host supplies a PostgreSQL database/sql connection, immutable run input and actual step handlers. For production, extend the small Go scan with fair pagination, persisted next_attempt_at, a total failure budget and blocked-state handling; the Laravel alternative below shows those fields. Do not expose the Go teaching runner as an unrestricted production engine.
The Go angle
Standard context.Context cancels a process-local call; workflow.Context participates in deterministic orchestration. A time.Duration is fine as an input value, but native timers and goroutines are not substitutes for workflow timers and concurrency APIs. The SDK's test environment skips durable waiting time; that tests orchestration quickly, not server failover or broker persistence.
Laravel
Before
A giant job has no durable boundary between its operations. Queue retries start its handler again; the 72-hour sleep also exceeds ordinary worker timeouts.
<?php
namespace App\Jobs;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Http;
final class GiantJob implements ShouldQueue
{
use Queueable;
public function __construct(public string $id) {}
public function handle(): void
{
Http::post(config('services.workflow.url').'/receipt', ['id' => $this->id])->throw();
sleep(72 * 3600); // Blocks a worker; the queue timeout normally kills it first.
Http::post(config('services.workflow.url').'/review', ['id' => $this->id])->throw();
}
}Chains and batches are useful composition
Laravel 13 lists “the database, Amazon SQS, Redis, and Beanstalkd drivers” and also synchronous and null drivers. RabbitMQ and Kafka require integrations; Redis Streams is separate from the built-in Redis queue implementation. Laravel queues documents the drivers and composition APIs.
Bus::chain runs successor jobs after successful predecessor execution. Remaining jobs are serialized with queue work: it is incorrect to say a chain stores no state at all. What it lacks is a durable, queryable application workflow model with arbitrary branching and history replay. Deleting a job does not stop its chain; a failure does. catch handles chain failure, not transaction rollback.
Bus::batch groups jobs, tracks progress and supports before, progress, then, catch and finally callbacks. Multiple workers make jobs parallel. All batch jobs use the same connection and queue. Jobs need Batchable; cancellation is cooperative. catch handles the first failure; allowFailures changes automatic cancellation. Callback completion is not an atomic business transaction with every output. Do not capture $this in serialized callbacks. Laravel batching is the API reference.
<?php
namespace App\Jobs;
use Illuminate\Bus\Batchable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Http;
// A portable chain/batch member. The external endpoint owns durable key dedup.
final class OperationJob implements ShouldQueue
{
use Batchable, Queueable;
public int $tries = 5;
public int $timeout = 30;
public array $backoff = [5, 30, 120];
public function __construct(public string $runId, public string $operation) {}
public function handle(): void
{
if ($this->batch()?->cancelled()) { return; }
Http::connectTimeout(3)->timeout(20)
->withHeaders(['Idempotency-Key' => "{$this->runId}:{$this->operation}:v1"])
->post(config('services.workflow.url').'/operations', [
'run_id' => $this->runId, 'operation' => $this->operation,
])->throw();
}
}<?php
namespace App\Services;
use App\Jobs\OperationJob;
use Illuminate\Bus\Batch;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\Log;
use Throwable;
final class QueueExamples
{
// Short fixed sequence: durable queue payloads, no application checkpoint model.
public function chain(string $runId): void
{
Bus::chain([
new OperationJob($runId, 'reserve'),
new OperationJob($runId, 'receipt'),
// Relative delay starts when this chained job is dispatched.
(new OperationJob($runId, 'review'))->delay(72 * 3600),
])->onConnection('redis')->onQueue('workflows')
->catch(static function (Throwable $e) use ($runId) {
Log::error('Chain failed', ['workflow_id' => $runId, 'error' => $e->getMessage()]);
})->dispatch();
}
public function batch(string $runId): string
{
$batch = Bus::batch([
new OperationJob($runId, 'warehouse-a'),
new OperationJob($runId, 'warehouse-b'),
])->name('Notify warehouses')->onConnection('redis')->onQueue('workflows')
->then(static function (Batch $batch) use ($runId) {
// A business reconciler should independently verify both outputs.
OperationJob::dispatch($runId, 'warehouse-summary');
})->catch(static function (Batch $batch, Throwable $e) use ($runId) {
Log::error('Batch failed', ['workflow_id' => $runId, 'batch' => $batch->id]);
})->finally(static function (Batch $batch) {
Log::info('Batch settled', ['batch' => $batch->id]);
})->dispatch();
return $batch->id;
}
}This chain/batch demonstration uses independent operation keys and does not write the SQL runner's rows. The two examples are alternatives. Supply the configured external operations endpoint; it must enforce atomic idempotency and reject changed parameters for an existing key.
After: application progress with reconciliation
For the small multiday flow, create a run row, use ResumeWorkflow for one transition, and let the scheduled scan recover lost wake-ups. This variant sends a receipt, records a three-day wait and sends a review. It stores the workflow budget across fresh queue messages and moves repeatedly failing runs to blocked.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
public function up(): void
{
Schema::create('workflow_runs', function (Blueprint $table) {
$table->string('workflow_id')->primary();
$table->unsignedInteger('definition')->default(1);
$table->unsignedInteger('current_step')->default(0);
$table->unsignedBigInteger('version')->default(0);
$table->string('status')->default('running');
$table->timestampTz('wake_at')->nullable();
$table->timestampTz('next_attempt_at')->nullable();
$table->unsignedInteger('failures')->default(0);
$table->text('last_error')->nullable();
$table->timestampsTz();
$table->index(['status', 'next_attempt_at', 'workflow_id']);
});
}
public function down(): void { Schema::dropIfExists('workflow_runs'); }
};<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
final class WorkflowRun extends Model
{
protected $primaryKey = 'workflow_id';
public $incrementing = false;
protected $keyType = 'string';
protected $guarded = [];
protected function casts(): array
{
return ['wake_at' => 'immutable_datetime', 'next_attempt_at' => 'immutable_datetime',
'current_step' => 'integer', 'version' => 'integer', 'definition' => 'integer', 'failures' => 'integer'];
}
}<?php
namespace App\Services;
use App\Jobs\ResumeWorkflow;
use App\Models\WorkflowRun;
final class StartWorkflow
{
public function start(string $workflowId): void
{
// Commit this row with the originating business change when they share a DB.
// firstOrCreate preserves the original identity; it never resets a finished run.
WorkflowRun::firstOrCreate(['workflow_id' => $workflowId]);
ResumeWorkflow::dispatch($workflowId)->onQueue('workflows')->afterCommit();
// afterCommit avoids reading uncommitted rows; it is not a transactional outbox.
}
}<?php
namespace App\Jobs;
use App\Models\WorkflowRun;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Middleware\WithoutOverlapping;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use RuntimeException;
use Throwable;
// This state-driven runner is a separate alternative to QueueExamples::chain.
final class ResumeWorkflow implements ShouldQueue
{
use Queueable;
public int $tries = 5;
public int $timeout = 30;
public array $backoff = [10, 30, 120];
public function __construct(public string $workflowId) {}
public function middleware(): array
{
return [(new WithoutOverlapping($this->workflowId))->shared()->releaseAfter(10)->expireAfter(90)];
}
public function handle(): void
{
$run = WorkflowRun::findOrFail($this->workflowId);
if ($run->status !== 'running' || $run->next_attempt_at?->isFuture()) { return; }
$version = $run->version;
try {
if ($run->definition !== 1 || ! in_array($run->current_step, [0, 1, 2], true)) {
throw new RuntimeException('Unsupported workflow definition or checkpoint');
}
if ($run->current_step === 1 && $run->wake_at === null) {
// Persist the absolute due time once. Restart cannot move it forward.
WorkflowRun::whereKey($run->getKey())->where('version', $version)->where('status', 'running')
->update(['wake_at' => now()->addDays(3), 'version' => DB::raw('version + 1')]);
return;
}
if ($run->current_step === 1 && $run->wake_at->isFuture()) { return; }
if ($run->current_step !== 1) {
$step = $run->current_step === 0 ? 'receipt' : 'review';
Http::connectTimeout(3)->timeout(20)
->withHeaders(['Idempotency-Key' => "{$this->workflowId}:{$step}:v1"])
->post(config('services.workflow.url').'/operations', [
'run_id' => $this->workflowId, 'operation' => $step,
])->throw();
}
$advanced = WorkflowRun::whereKey($run->getKey())->where('version', $version)->where('status', 'running')
->update(['current_step' => $run->current_step + 1, 'version' => DB::raw('version + 1'),
'status' => $run->current_step === 2 ? 'completed' : 'running',
'wake_at' => null, 'next_attempt_at' => null, 'failures' => 0, 'last_error' => null]);
} catch (Throwable $e) {
// Count failures in the workflow row, across fresh queue messages too.
WorkflowRun::whereKey($run->getKey())->where('version', $version)->where('status', 'running')
->update(['failures' => $run->failures + 1, 'version' => DB::raw('version + 1'),
'status' => $run->failures + 1 >= 5 ? 'blocked' : 'running',
'next_attempt_at' => now()->addMinute(), 'last_error' => $e::class]);
throw $e;
}
// Lost dispatch cannot strand the run: the reconciler scans base rows.
if ($advanced === 1 && $run->current_step !== 2) {
self::dispatch($this->workflowId)->onQueue('workflows');
}
}
}<?php
namespace App\Console\Commands;
use App\Jobs\ResumeWorkflow;
use App\Models\WorkflowRun;
use Illuminate\Console\Command;
final class ReconcileWorkflows extends Command
{
protected $signature = 'workflows:reconcile';
protected $description = 'Wake due unfinished workflow runs, including never-started runs';
public function handle(): int
{
WorkflowRun::where('status', 'running')
->where(fn ($q) => $q->whereNull('wake_at')->orWhere('wake_at', '<=', now()))
->where(fn ($q) => $q->whereNull('next_attempt_at')->orWhere('next_attempt_at', '<=', now()))
->chunkById(100, function ($runs) {
foreach ($runs as $run) {
ResumeWorkflow::dispatch($run->workflow_id)->onQueue('workflows');
}
}, 'workflow_id');
// No touch(), completion marker or clearing wake_at on dispatch.
return self::SUCCESS;
}
}<?php
// routes/console.php; all scheduler hosts must use the same lock-capable cache.
use Illuminate\Support\Facades\Schedule;
Schedule::command('workflows:reconcile')->everyMinute()->onOneServer()->withoutOverlapping(5);
Schedule::command('queue:prune-batches --hours=168 --unfinished=336 --cancelled=336')->daily();
// The durations are application choices; retain workflow state separately.afterCommit() avoids a worker seeing an uncommitted run; it does not atomically commit SQL and the broker. Here reconciliation closes that intentional gap. The version predicate is the correctness guard when locks expire or duplicate deliveries overlap. WithoutOverlapping reduces contention but is not the business correctness proof. Its release consumes queue attempts; different job classes require shared() for a shared lock key.
The Laravel angle
| Setting / API | Use | Boundary |
|---|---|---|
$tries, backoff, retryUntil | Per-message retry policy | Fresh repair messages need a persisted workflow budget too |
$timeout / worker --timeout | Bound job execution | Keep shorter than applicable retry_after or backend visibility timeout |
delay() | Driver-managed later dispatch | SQS delay is limited to 15 minutes; long waits need another representation |
dispatchAfterResponse | Small work after response in current process | Not a durable background queue handoff |
onOneServer() | One scheduler owner per tick using shared cache | All scheduler hosts must share supported lock-capable cache |
Scheduler withoutOverlapping(5) | Prevent another scheduled command for up to 5 minutes | Unit differs from job middleware's second-based methods |
queue:retry-batch | Requeue failed batch jobs | Requires retained metadata and idempotent effects |
queue:prune-batches | Bound batch metadata storage | Retain business workflow evidence independently |
Broker differences
These brokers carry triggers or external events around a workflow. They do not replace Temporal/Cadence persistence or execute deterministic workflow code. The examples consume advisory wake-ups only after loading SQL state. A recorded future wait counts as safely handled: the database owns the future obligation, so the wake can be acknowledged. A failed checkpoint must leave the wake unsettled.
RabbitMQ
Manual acknowledgement controls redelivery; durable/quorum queues and persistent publication affect transport durability. Neither stores a workflow call stack. TTL/DLX can implement delay buckets, but expiry and dead-letter safety have constraints; a long business wait is clearer as an engine timer or SQL due time. See RabbitMQ and delayed delivery.
package brokers
import (
"context"
amqp "github.com/rabbitmq/amqp091-go"
)
// Configure the channel with manual acknowledgements and bounded prefetch.
// wake reloads authoritative state and returns nil for a safely recorded wait.
// On error leave this delivery unacked and close/reconnect the consumer channel
// under the application's bounded retry/parking policy; never hot-loop requeue.
func RabbitWake(ctx context.Context, d amqp.Delivery, wake func(context.Context, string) error) error {
if err := wake(ctx, string(d.Body)); err != nil {
return err
}
return d.Ack(false)
}For Laravel, WakePublishers::rabbit uses the verified vladimir-yuldashev/laravel-queue-rabbitmq integration through normal dispatch. A missing wake is recoverable here because the run row remains pending. For reliable domain-event publication use the confirmed Outbox publisher instead of assuming a successful dispatch proves every routing/durability property.
<?php
namespace App\Services;
use App\Jobs\ResumeWorkflow;
use Illuminate\Support\Facades\Redis;
use Junges\Kafka\Facades\Kafka;
use Junges\Kafka\Message\Message;
use RuntimeException;
final class WakePublishers
{
// Requires vladimir-yuldashev/laravel-queue-rabbitmq and a configured connection.
// An advisory wake-up: SQL remains authoritative if publishing is lost.
public function rabbit(string $id): void
{
ResumeWorkflow::dispatch($id)->onConnection('rabbitmq')->onQueue('workflows');
}
// Requires mateusjunges/laravel-kafka + ext-rdkafka. No claim of native delay.
public function kafka(string $id): void
{
$reported = false; $error = null;
$sent = Kafka::publish()->onTopic('workflow-wakes')
->withConfigOptions(['enable.idempotence' => 'true', 'delivery.timeout.ms' => '5000'])
->withDrMsgCb(static function ($producer, $report) use (&$reported, &$error) {
$reported = true;
if ($report->err !== RD_KAFKA_RESP_ERR_NO_ERROR) { $error = $report->errstr(); }
})->withMessage(new Message(body: ['workflow_id' => $id], key: $id))->send();
if (! $sent || ! $reported || $error !== null) { throw new RuntimeException($error ?? 'No delivery confirmation'); }
}
// Raw Redis command forwarding works with the configured Redis connection.
// This stream is separate from Laravel's built-in redis queue driver.
public function redis(string $id): string
{
return Redis::command('xadd', ['workflow:wakes', '*', 'workflow_id', $id]);
}
}Kafka
A workflow ID as key aligns records with partition ordering, but offsets represent stream progress, not business execution state. Kafka has no native per-record “deliver at” timestamp; waiting in a consumer risks blocking a partition. Keep multiday timers in the engine or due-time store. Kafka design explains the log/consumer model.
package brokers
import (
"context"
"errors"
"github.com/twmb/franz-go/pkg/kgo"
)
// Construct cl with ConsumerGroup and DisableAutoCommit. This serial loop polls
// one record, records the checkpoint, then commits. On any error exit and close
// the client; do not poll past an uncommitted failed record.
func KafkaWakes(ctx context.Context, cl *kgo.Client, wake func(context.Context, string) error) error {
defer cl.Close() // This loop owns the client; never resume an advanced cursor after failure.
for {
fetches := cl.PollRecords(ctx, 1)
var failures []error
for _, failure := range fetches.Errors() {
failures = append(failures, failure.Err)
}
if len(failures) > 0 {
return errors.Join(failures...)
}
for _, rec := range fetches.Records() {
if err := wake(ctx, string(rec.Key)); err != nil {
return err
}
if err := cl.CommitRecords(ctx, rec); err != nil {
return err
}
}
}
}Construct the client with DisableAutoCommit; process serially and exit/close on any processing or commit error. Returning an error does not rewind franz-go's fetched position. A rebalance can still create overlap; SQL version guards and external idempotency remain necessary. The handler must be bounded so shutdown/rebalance does not wait behind multiday work.
The Laravel kafka method in the shared publisher uses mateusjunges/laravel-kafka and a delivery callback; flushing a producer queue alone is not enough proof of record success. It publishes a wake immediately, not a delayed workflow. Its consumer must reload the same SQL run and settle only after safe handling.
<?php
namespace App\Services;
use App\Jobs\ResumeWorkflow;
use Illuminate\Support\Facades\Redis;
use Junges\Kafka\Facades\Kafka;
use Junges\Kafka\Message\Message;
use RuntimeException;
final class WakePublishers
{
// Requires vladimir-yuldashev/laravel-queue-rabbitmq and a configured connection.
// An advisory wake-up: SQL remains authoritative if publishing is lost.
public function rabbit(string $id): void
{
ResumeWorkflow::dispatch($id)->onConnection('rabbitmq')->onQueue('workflows');
}
// Requires mateusjunges/laravel-kafka + ext-rdkafka. No claim of native delay.
public function kafka(string $id): void
{
$reported = false; $error = null;
$sent = Kafka::publish()->onTopic('workflow-wakes')
->withConfigOptions(['enable.idempotence' => 'true', 'delivery.timeout.ms' => '5000'])
->withDrMsgCb(static function ($producer, $report) use (&$reported, &$error) {
$reported = true;
if ($report->err !== RD_KAFKA_RESP_ERR_NO_ERROR) { $error = $report->errstr(); }
})->withMessage(new Message(body: ['workflow_id' => $id], key: $id))->send();
if (! $sent || ! $reported || $error !== null) { throw new RuntimeException($error ?? 'No delivery confirmation'); }
}
// Raw Redis command forwarding works with the configured Redis connection.
// This stream is separate from Laravel's built-in redis queue driver.
public function redis(string $id): string
{
return Redis::command('xadd', ['workflow:wakes', '*', 'workflow_id', $id]);
}
}Redis Streams
XREADGROUP assigns new entries, the Pending Entries List tracks unsettled deliveries, and XACK settles them. Recovery also processes abandoned pending entries through XAUTOCLAIM; reading only > strands them after consumer failure. Neither stream IDs nor the PEL describe the workflow's next business step. Redis Streams documents the delivery lifecycle.
package brokers
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
)
// msg may come from XREADGROUP (new work) or XAUTOCLAIM (abandoned PEL entries).
// The group is created separately. Acknowledgement never deletes workflow state.
func RedisWake(ctx context.Context, cl *redis.Client, stream, group string, msg redis.XMessage, wake func(context.Context, string) error) error {
id, ok := msg.Values["workflow_id"].(string)
if !ok || id == "" {
return fmt.Errorf("message %s has no workflow_id", msg.ID)
}
if err := wake(ctx, id); err != nil {
return err
}
return cl.XAck(ctx, stream, group, msg.ID).Err()
}The Laravel redis publisher uses raw Redis::command('xadd', ...), not Laravel's Redis queue payload format. Keep stream retention long enough for recovery and account for Redis persistence/failover policy. A sorted set can index timer due times, but removing an entry before enqueue creates a loss gap; use the authoritative SQL due row shown here, or an atomic transfer with explicit persistence and error handling. Do not rank durability by product name alone.
<?php
namespace App\Services;
use App\Jobs\ResumeWorkflow;
use Illuminate\Support\Facades\Redis;
use Junges\Kafka\Facades\Kafka;
use Junges\Kafka\Message\Message;
use RuntimeException;
final class WakePublishers
{
// Requires vladimir-yuldashev/laravel-queue-rabbitmq and a configured connection.
// An advisory wake-up: SQL remains authoritative if publishing is lost.
public function rabbit(string $id): void
{
ResumeWorkflow::dispatch($id)->onConnection('rabbitmq')->onQueue('workflows');
}
// Requires mateusjunges/laravel-kafka + ext-rdkafka. No claim of native delay.
public function kafka(string $id): void
{
$reported = false; $error = null;
$sent = Kafka::publish()->onTopic('workflow-wakes')
->withConfigOptions(['enable.idempotence' => 'true', 'delivery.timeout.ms' => '5000'])
->withDrMsgCb(static function ($producer, $report) use (&$reported, &$error) {
$reported = true;
if ($report->err !== RD_KAFKA_RESP_ERR_NO_ERROR) { $error = $report->errstr(); }
})->withMessage(new Message(body: ['workflow_id' => $id], key: $id))->send();
if (! $sent || ! $reported || $error !== null) { throw new RuntimeException($error ?? 'No delivery confirmation'); }
}
// Raw Redis command forwarding works with the configured Redis connection.
// This stream is separate from Laravel's built-in redis queue driver.
public function redis(string $id): string
{
return Redis::command('xadd', ['workflow:wakes', '*', 'workflow_id', $id]);
}
}In production systems
- Temporal explicitly separates application workers from the service that persists histories and schedules tasks. Worker replacement therefore does not require transferring the original process memory. Understanding Temporal
- Cadence documents activity heartbeat progress and retries, while distinguishing activity state from recoverable workflow state. A media export can resume from reported chunk progress, with idempotency for the last uncertain chunk. Cadence activities
- Laravel stores batch metadata and supplies pruning and failed-batch retry commands. Keeping only queue payloads is insufficient for long-lived operational recovery after metadata deletion. Laravel queues
In architecture: from a single process to a distributed system
Monolith: one process, one database
A report service can put a run row and report request in one SQL transaction, then process a single job. Local output metadata and progress can share a later transaction. Add a due-row scan before introducing a workflow engine. Example: an export transitions requested → generated → published; artifact existence is verified on reconciliation.
Modular monolith: explicit ownership
The Billing module owns invoice state; Notifications owns delivery. A workflow stores IDs and stable contracts instead of loading arbitrary mutable models at every retry. Example: invoice amount/currency are frozen at admission, while a receipt operation uses invoice:42:receipt:v1. Shared deployment does not justify silently changing old workflow input semantics.
Microservices: orchestration survives service boundaries
An onboarding workflow asks Accounts to create an account, Identity to provision access and Notifications to deliver a welcome message. Each activity reaches a service-owned API or messaging adapter. The workflow history records outcomes, but the services own their effects. Rollback/compensation is a Saga decision; reliable emitted events use Outbox. A broker subscription can signal an existing workflow after deduplicating the event identity.
Distributed data: replicas, caches and regions
Read recovery state from a consistency path suitable for decisions. A stale replica can falsely show an unfinished step and increase duplicate attempts; a conditional write on the primary plus provider idempotency protects correctness. Cache state is advisory. Example: during regional failover, resume only after the chosen authoritative database/history store is available and compatible workers are deployed. Durable execution does not mean progress continues through every partition or that every replication configuration has zero data loss.
Scaling path
| Stage | Concrete change | Keep invariant |
|---|---|---|
| 1× | One worker, indexed due rows, bounded scan | Run registry exists before dispatch |
| 10× | More workers, per-provider task queues / queues, paginated scans | Duplicate attempts use the same operation key |
| 100× | Tenant quotas, bounded child workflows, history rollover, partitioned reconciliation | No tenant or stuck page monopolizes progress |
Scale on runnable work and queue wait, not merely the count of workflows sleeping for months. NATS JetStream, Pulsar and SQS are other transports around this architecture; their delivery primitives also do not supply arbitrary deterministic workflow replay. Choose their role through Broker comparison.
Lab: inspect the recovery boundaries
Broker/database/Temporal integration experiments below are expected, not run. No Docker or server cluster is required for the host-only tests. A real integration lab needs an existing Temporal service, PostgreSQL or Laravel 13 app, configured clients, registered workers and the external idempotent operations endpoint; those services are not bundled here.
1. Host-only tests
cd docs/snippets/messaging/durable-workflows-jobs/go
gofmt -l .
go vet ./...
go test ./...
# Expected: clean formatting; SDK orchestration and checkpoint tests pass.The SDK tests simulate retry, cancellation and 72-hour timer advancement. Checkpoint tests inject a lost write, verify stable keys, preserve a deadline after restart and find a never-started run. These tests do not prove real broker acknowledgement, PostgreSQL locking or Temporal failover behavior.
2. Lose the initial dispatch
Use Postgres.Schema to create the Go runner table; the Laravel migration is an alternative schema with additional operational fields. Insert a run with no step execution and intentionally omit publication. Terminal A runs the reconciler; terminal B reads its checkpoint.
INSERT INTO workflow_runs(workflow_id, definition) VALUES ('lab:missing-wake', 1);
SELECT workflow_id, current_step, status, version FROM workflow_runs
WHERE workflow_id='lab:missing-wake';
-- Before reconciliation: step 0, running, version 0.
-- After one successful non-timer Tick: step 1 and version 1.Expected: a run without any broker message is still discoverable. Scanning only completed/started step rows would fail this experiment.
3. Crash after effect, before checkpoint
Have the gateway persist an operation key and then drop its reply. Retry the activity or SQL step. Inspect the provider operation ledger and run history separately. Expected: more than one attempt, one business operation, eventually one recorded completion. Repeat with provider key retention intentionally too short; the lost guarantee should be visible.
4. Stop workers during a durable wait
Start the Temporal workflow on a disposable test order, wait until the timer is recorded, stop workers, then restart compatible workers after the due time. Expected: completed activities are replayed from history, the review runs after service/worker recovery, and no exact execution-time guarantee is implied. The test suite uses virtual time instead of waiting three real days.
5. Break compatibility and cancel
Export a representative history and replay it offline against a definition that reorders the first activity and timer. Expected: nondeterminism; restore the old order or use a tested version branch. Separately cancel during a wait, then during an activity. Expected: the wait cancels promptly when handled; activity stopping depends on heartbeat/context cooperation and the external provider. Termination does not execute workflow cleanup.
6. Verify Laravel recovery and batch retention
php artisan migrate
php artisan make:queue-batches-table
php artisan migrate
php artisan workflows:reconcile
php artisan queue:work --queue=workflows --timeout=30
# Expected: due running rows advance; future wake_at and blocked rows do not.
# Configure retry_after / backend visibility longer than the worker timeout.Run scheduling on two hosts with the same supported cache, then stop both for several minutes. Expected: onOneServer coordinates active ticks; restarted reconciliation finds overdue rows independently of missed ticks. Verify failure count survives fresh wake messages, cancelled status cannot be overwritten by a stale version and pruned batch metadata is not your only business record.
Common misconceptions
| Belief | Reality |
|---|---|
| Replay recharges every completed payment | Recorded activity results are reused; unrecorded results can require retry |
| Engine means exactly-once external effects | External idempotency or reconciliation is still required |
| Every queue job is a workflow | A job does not necessarily model multistep progress and waits |
| Laravel chains store no state | Successor jobs are serialized; full workflow replay/state is a different capability |
| Batch cancellation stops running code immediately | Jobs and external operations must cooperate |
| A timeout proves nothing happened | The provider may have accepted the operation |
| A timer must keep a worker thread asleep | Engine/due-time storage persists the wait |
onOneServer recovers every missed tick | It coordinates currently evaluated scheduled runs |
afterCommit is an outbox | It orders dispatch after commit but leaves a crash gap |
| New code can replay all old histories | Command and payload compatibility must be tested |
| Continue-As-New preserves all local state automatically | The next run receives only deliberately carried state |
| Empty queue means all workflows are healthy | Lost triggers can leave overdue database/history work |
Cheat sheet
| Topic | Remember |
|---|---|
| Identity | Stable business Workflow ID, explicit generation for intentional reruns |
| Replay | Reconstruct decisions from history; external I/O belongs in activities |
| Activities | Retry can repeat effects; preserve operation key and input |
| Timeouts | Attempt clock differs from total execution budget |
| Heartbeat | Report progress, support cancellation, repeat uncertain chunk safely |
| Timer | Persist due time; firing is not exact completion time |
| Schedule | Define overlap, missed-period and backfill policy |
| Message APIs | Signal changes asynchronously; Query reads; Update tracks a result |
| Cancellation | Cooperative cleanup; termination bypasses cleanup |
| Versioning | Preserve old command paths or route compatible workers |
| History | Bound fan-out/data size; use Continue-As-New intentionally |
| Laravel | Chains order, batches group, application state records business progress |
| Reconciler | Scan base runs, due waits and outputs; persist total failure budgets |
| Broker | Wake-up delivery is not workflow state |
| Testing | Virtual time/unit tests plus history replay and separately executed integration tests |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — A provider succeeded but the worker died before reporting. What can the engine safely assume? Must-know
Answer
Answer: It cannot assume failure or success of the external effect. It may retry the activity; stable provider idempotency or lookup/reconciliation resolves the ambiguity.
2 — Why is workflow.Now allowed where time.Now is not? Important
Answer
Answer: Workflow time follows replay semantics. A fresh wall-clock read could choose a different command sequence when rebuilding old history.
3 — Which timeout limits all activity attempts together? Important
Answer
Answer: Schedule-To-Close; Start-To-Close limits one attempt. The remote client still needs its own I/O timeouts.
4 — Does a successful Signal call prove that an approval email was sent? Important
Answer
Answer: No. Signal admission is distinct from handler execution and its downstream activity outcomes.
5 — What survives Continue-As-New, and what must be passed explicitly? Important
Answer
Answer: The Workflow ID continues, but Run ID/history change. Business state, pending obligations and dedup data required by the next run must be carried explicitly.
6 — Why can a database reconciler miss a workflow if it scans only step rows? Good to know
Answer
Answer: The initial trigger may be lost before any step row exists. An authoritative run registry is necessary.
7 — Does WithoutOverlapping replace version checks and idempotency? Must-know
Answer
Answer: No. Lease expiry, process stalls and duplicate deliveries can overlap; version guards protect progress and idempotency protects effects.
8 — Why is retrying a nondeterminism error indefinitely unhelpful? Important
Answer
Answer: The same incompatible code emits the same incompatible commands. Restore compatibility or route a compatible worker.
9 — When may an advisory wake-up for a future wait be acknowledged? Good to know
Answer
Answer: After the future obligation is durably recorded elsewhere and a working recovery path will discover it. A process-local timer alone is insufficient.
10 — What evidence distinguishes host-only checks from durable integration validation? Good to know
Answer
Answer: Unit tests validate code paths, retry keys and virtual-time decisions. Real integration experiments inspect server history, database writes and broker settlement across process/service failure; those experiments are labeled expected, not run here.
Glossary
| Term | Meaning |
|---|---|
| Durable Execution | Recoverable progress and waits across process loss |
| Workflow Definition | Code specifying the orchestration |
| Workflow Execution | A running or closed instance of that definition |
| Namespace / Domain | Temporal / Cadence isolation and identity boundary |
| Workflow ID | Logical identity chosen by the application |
| Run ID | Engine-assigned identity of one execution run |
| Workflow ID conflict / reuse policy | Rules for open identity conflicts and closed identity reuse |
| Event History | Persisted ordered execution events used for reconstruction |
| Command | Workflow request to schedule work, timers or other actions |
| Determinism | Compatibility of emitted commands with recorded history |
| Replay | Reconstructing workflow state from history |
| Workflow Task | Unit of orchestration decision processing |
| Activity / Activity Task | External operation / one execution attempt |
| Task Queue / Task List | Temporal / Cadence task routing primitive |
| Worker / sticky cache | Application executor / cached workflow state optimization |
| Idempotency key | Stable identity that makes repeated business operations safe |
| Checkpoint | Persisted application progress marker |
| CAS / version guard | Conditional update requiring the expected version |
| Retry Policy | Attempt delay, limit and eligible-error rules |
| Start-To-Close | Timeout for one activity attempt |
| Schedule-To-Start | Timeout waiting for an activity worker |
| Schedule-To-Close | Total activity execution timeout |
| Heartbeat / HeartbeatTimeout | Progress report / bound on missing reports |
| WorkflowTaskTimeout | Time budget for one orchestration task |
| WorkflowRunTimeout / WorkflowExecutionTimeout | One-run / whole execution-chain deadline |
Timer / wake_at | Durable future wake obligation / SQL absolute due time |
| Schedule / overlap policy | Recurring start specification / behavior when earlier run remains open |
| Catchup window / backfill | Automatic missed-occurrence horizon / explicitly requested historical occurrences |
| Signal / Query / Update | Asynchronous mutation / read-only inspection / tracked state-changing request |
| Signal-With-Start | Ensure execution exists and send a signal through one service operation |
| Selector / AwaitWithTimeout | Workflow-safe waiting for events / condition with a timeout |
| Cancellation / termination | Cooperative stop request / service-side forced closure |
| WaitForCancellation | Wait for activity cancellation acknowledgement |
| Disconnected context | Workflow context allowing cleanup after cancellation |
| Compensation | Explicit business action addressing a previous effect |
SideEffect / MutableSideEffect | Record nondeterministic value / record changed value with equality check |
| Local Activity | Activity run with workflow-worker affinity and reduced scheduling overhead |
Patching / GetVersion | Recorded version branch preserving old command paths |
| Worker Versioning / Deployment Version | Routing executions to compatible worker revisions |
| Continue-As-New | Successful rollover into a fresh run/history with carried input |
| Child Workflow / parent-close policy | Sub-execution / rule for its lifecycle when parent closes |
| Visibility / Search Attributes | Execution search system / indexed business metadata |
| Payload converter / codec | Serialization / optional payload transformation or protection |
Bus::chain / Bus::batch | Laravel ordered jobs / grouped jobs with progress callbacks |
Batchable / job_batches | Batch-participating job trait / default relational batch metadata |
allowFailures | Batch option preventing automatic cancellation after a job failure |
WithoutOverlapping / onOneServer | Job/command overlap lock / scheduler tick coordination |
afterCommit / dispatchAfterResponse | Dispatch ordering after SQL commit / work in the response process after sending |
| Reconciliation / blocked state | Compare and repair unfinished obligations / explicit work requiring intervention |
PEL / XACK / XAUTOCLAIM | Redis pending delivery list / acknowledgement / abandoned-entry recovery |
| Kafka offset | Consumer position in a partition, not workflow business progress |
| Publisher confirm / manual acknowledgement | Broker publication acceptance / consumer settlement boundary |
References
- Temporal: Understanding Temporal, Workflow Definition, Activities, Tasks.
- Temporal Go: Activity timeouts and heartbeats, Message passing, Cancellation, Schedules, Versioning, Continue-As-New.
- Go SDK APIs: workflow, client, testsuite, pinned SDK module.
- Cadence: Workflows, Activities.
- Laravel 13: Queues, Scheduling, Database, HTTP client, Redis.
- Brokers: RabbitMQ confirms and acknowledgements, RabbitMQ TTL, Kafka design, Redis Streams, XACK.
- Go clients: amqp091-go, franz-go, go-redis.
- Laravel integrations: RabbitMQ README, Laravel Kafka README, Kafka producer builder, Kafka message.