Skip to content

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 forGo to
Job versus workflowOne minute
How restart reconstructs local variablesReplay
Why an activity can run twiceActivities
Which timeout to configureTimeouts
Human approval and cancellationMessages, cancellation
Changing code while runs are openVersioning
A real SDK example and a small SQL alternativeGo
Chains, batches and missed schedulesLaravel
Broker roles and limitsBroker differences
Recovery experimentsLab

Everything in one minute ​

PrimitiveDurable recordRestart behaviorMissing responsibility
Plain goroutine / PHP processNone unless application writes itStack disappearsEverything after the last external checkpoint
Persistent queue jobJob payload and delivery state, according to backend durabilityHandler may execute from its beginningBusiness progress inside the handler
Laravel chainSerialized successor jobs carried with queue workQueue retries current job; successors follow successful executionApplication checkpoints, branching and repair policy
Laravel batchJob messages plus batch metadataWorkers resume remaining deliveriesDomain correctness of outputs and callback effects
SQL checkpoint runnerRun row, step, version and absolute due timeLoad checkpoint; repeat uncertain step safelyYou implement concurrency, deadlines, recovery and evolution
Temporal / CadenceExecution history and engine persistenceReconstruct workflow state; redispatch unfinished workIdempotent activities, business failure policy and operations
DistinctionFirst sideSecond side
Workflow Task / Activity TaskCompute the next orchestration decisionsExecute an external operation
Replay / retryRebuild from recorded outcomesPerform another attempt whose outcome is not recorded as successful
Workflow ID / Run IDLogical business execution identityOne execution run in a chain of runs
Timer / scheduleResume an existing execution laterStart executions at calendar or interval times
Cancellation / terminationCooperative request, allowing cleanup codeServer-side stop; workflow cleanup is not executed
Durability / availabilityState remains recoverableWork can make progress now
Technical retry / business recoveryRetry a recoverable callResolve 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 choiceExtra obligation when the process grows
One handler performs all stepsEarlier side effects may repeat after a late failure
Put the next job on a queueCommit-to-publish gap can strand the run
Sleep inside a workerProcess death loses the wait and consumes capacity while alive
Save a step numberConcurrent resumes, version changes and remote ambiguity need rules
Adopt an engineOperate 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.

text
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.

ProductIdentity rule to configureApplication responsibility
TemporalConflict policy for an open execution; reuse policy for closed executionsMatch input and domain generation; retention is not an eternal dedup database
CadenceWorkflow ID uniqueness within a Domain; WorkflowIdReusePolicyUse Cadence's documented policy names and defaults
Laravel / SQL runnerUnique workflow_id in the business databaseNever 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.

text
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.

Worker ASchedule receiptTemporal / CadencePersist ordered historyActivity workerExternal idempotent effectHistoryReceipt done; timer pendingWorker B after restartReplay recorded outcomeReplay uses recorded results; an unrecorded effect may require another Activity attempt.

In Temporal workflow codeUse insteadWhy
time.Now() for a business decisionworkflow.Now(ctx)Replay must observe the recorded logical execution time
time.Sleep / native timerworkflow.Sleep / workflow.NewTimerWait survives worker loss
Native goroutine or channelworkflow.Go, workflow channels and selectorsSDK controls deterministic scheduling
Map iteration that emits commandsSorted keysGo map order is not deterministic
HTTP, SQL, file readsActivityExternal outcomes are not reproducible from code alone
Random value / configuration readActivity or carefully chosen SideEffectPersist 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.

text
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.
BoundaryCorrect protectionRemaining limit
Local DB change plus checkpointOne database transactionOnly covers that database connection
Remote API plus checkpointStable provider idempotency key and immutable parametersProvider key retention must cover recovery horizon
Provider lacks dedup but supports lookupStable external reference and reconciliationAmbiguous lookup may require human review
Provider supports neitherExplicit duplicate risk or manual approvalEngine 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 optionMeasuresDecision
ScheduleToStartTimeoutQueue wait before an attempt startsNon-retryable timeout; monitor capacity rather than repeatedly enqueueing onto the same unavailable fleet
StartToCloseTimeoutOne attempt after worker pickupMust exceed valid operation duration but detect a lost attempt promptly
ScheduleToCloseTimeoutEntire Activity Execution including retries and waitingOverall activity budget
HeartbeatTimeoutGap between reported heartbeatsDetect long-activity stalls and deliver cancellation
WorkflowTaskTimeoutOne Workflow TaskWorkflow code must yield promptly; not a business deadline
WorkflowRunTimeoutOne Workflow runIncludes its waits; a new run has a distinct budget
WorkflowExecutionTimeoutExecution chain across retries / Continue-As-NewUse only when a whole-chain deadline is truly required
text
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 / failureMeaning
InitialInterval, BackoffCoefficient, MaximumIntervalRetry delay policy; defaults are not an application budget
MaximumAttemptsIncludes the first attempt; 0 means unlimited for Temporal's Retry Policy
NonRetryableErrorTypes / nonretryable application errorReject invalid work without futile activity retries
Workflow Task failureEngine normally retries the task; execution may remain open and stuck
Activity failureWorkflow receives error after policy/budget resolution
Workflow failureBusiness 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.

SystemPersistent waitMissed occurrence behavior
Temporal / Cadence workflowSDK durable timerFire/resume after recovery, subject to service and worker availability
Temporal ScheduleSchedule specification and policyConfigure overlap, catchup window and explicit backfill
Laravel delayed jobDriver-specific delayed representationLimited by backend, retention and transport recovery
Laravel schedulerEvaluation when schedule:run / schedule:work runsNo generic durable ledger of every missed tick
SQL runnerwake_at persisted onceReconciler 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 familyMutates workflow state?Persisted processing significanceExample
SignalYes, in workflow handlerRecorded message; sender does not await handler resultApprover submits a decision
QueryNoRead-only observation; not a history eventDisplay current approval stage
UpdateYesAccepted update is tracked and can return a resultValidate and apply a changed delivery address
Signal-With-StartYesStart-if-needed and signal through one service operationEnsure 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.

text
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.
MechanismWhat it doesWhat it does not do
WaitForCancellationLets workflow wait for activity cancellation completionGuarantee an unresponsive external process stops
workflow.NewDisconnectedContextAllows bounded cleanup after parent cancellationTurn cleanup into an infallible rollback
TerminationImmediately closes execution at service levelRun deferred workflow cleanup
Laravel batch cancellationMarks batch cancelled; jobs must check / use skip middlewareUndo completed jobs or interrupt all active jobs
SQL status + version guardStops future checkpoint advancement from stale writersUndo 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 / concernSafe approachOperational cost
Add an activity before an old timerworkflow.GetVersion branch or compatible pinned workersRetain old path / fleet until no history requires it
Change activity internalsPreserve input/output contract and idempotency semanticsRetried old activity can run on new code
Change input schemaCompatible defaults or a versioned inputKeep decoding historical payloads possible
Endless signal processingContinue-As-New with explicit carried stateDrain handlers and retain request dedup state
Large fan-outBounded child workflowsParent still accumulates child lifecycle events
Giant activity resultStore artifact externally; return a referenceExternal 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.

text
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.

Business transactionCreate run before dispatchRun registry in SQLstep / version / wake_atWake-up queueFast advisory triggerPeriodic reconcilerFind due and never-startedReload and executeStable operation keyConditional checkpointExpected version + statusLost wake-up: registry still owns the obligation. Lost checkpoint: repeat the same operation key.

Required invariantWhy it matters
Register run before relying on a messageMakes first-dispatch loss discoverable
Persist absolute wake_at onceRestart cannot postpone the deadline indefinitely
Compare status and version when advancingStale workers cannot overwrite cancellation or newer progress
Bound failure count across queue messagesFresh deliveries must not reset the workflow's total retry budget
Scan fairly with pagination / partitionsOne poison page must not starve later runs
Mark blocked work explicitlyOperator repair is distinct from endless technical retry
Preserve original operation identity on repairManual 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 / componentResponsibilityFailure observation
Workflow Event HistoryDurable decisions and outcomesMissing completion means activity result is uncertain
Workflow TaskReplay plus new commandsRepeated task failures can leave an execution open
Activity TaskOne worker attemptTimeout or heartbeat gap can cause another attempt
Task Queue / Task ListMatch tasks to appropriate workersSchedule-to-start delay rises when no suitable worker polls
Worker sticky cacheAvoid replaying every task from the beginningCache loss affects cost, not correctness
Visibility / Search AttributesFind executions by business fieldsSearch is an operational index, not the domain transaction ledger
Payload converter / codecSerialize and optionally protect dataOld 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 / stateInterpretationResponse
WorkflowExecutionAlreadyStartedStart conflicts with existing identity/policyLook up intended execution; do not blindly generate another ID
TimeoutErrorA named activity/workflow clock expiredInspect timeout type and remote outcome before changing policy
ApplicationErrorApplication-classified failureRetry only eligible types within budget
CanceledErrorCooperative cancellation reached executionRun bounded cleanup if required; preserve cancellation semantics
Nondeterminism errorCommands no longer match historyRoll back / deploy compatible code, inspect history; retries alone cannot repair it
ResourceExhaustedService quota or capacity constraintReduce admission / concurrency and inspect configured limits
SQL ErrConflict in this sampleAnother checkpoint writer or terminal transition wonReload current state; do not overwrite it
Laravel blocked runApplication retry budget exhaustedInspect 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.

sql
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:

sql
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 ​

ProblemSolutionBenefitCost / limit
Activity succeeded but completion lostSame external idempotency keyRepeat without duplicate effectProvider contract and retention
Long wait lost on restartHistory timer or SQL absolute due timeWait survives process lossPersistence and scheduling latency
First queue publish lostRun registry reconciliation or transactional outboxNo permanently invisible runScan latency or relay operations
User cancels during remote callTerminal version guard plus provider reconciliationPrevent future progressionIn-flight effect may still finish
Bad deployment breaks replayCompatibility patch / restore old workerRecover open executionsMaintain multiple versions
Callback failed after batch completionDomain-output reconcilerRepair missing summary/actionAdditional authoritative output records
Repeated permanent errorMark blocked and retain evidenceStops retry amplificationExplicit 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 ​

WorkloadChooseAddReason
Resize one uploaded imageQueue jobIdempotent output pathOne recoverable operation
Three short ordered operationsLaravel chainPer-step idempotency and failure handlingLow orchestration complexity
Independent import chunksLaravel batchBatchable jobs, output ledger, callback repairParallel progress with bounded fan-out
A small fixed multiday flowSQL runner plus reconcilerVersion guard, due index, total retry budgetExplicit affordable state model
Human approval, branches, repeated callbacksTemporal / CadenceMessage dedup, replay testing, cancellation policyEngine manages durable coordination
Perpetual account coordinatorEngine with Continue-As-NewCarried dedup state and bounded historyKeeps lifecycle long and each history bounded
Audit/legal record of business eventsDomain event store / ledgerRetention and access rulesWorkflow 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.

go
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.

go
// 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)
}
go
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.

go
// 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)
}
go
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()
}
go
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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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 / APIUseBoundary
$tries, backoff, retryUntilPer-message retry policyFresh repair messages need a persisted workflow budget too
$timeout / worker --timeoutBound job executionKeep shorter than applicable retry_after or backend visibility timeout
delay()Driver-managed later dispatchSQS delay is limited to 15 minutes; long waits need another representation
dispatchAfterResponseSmall work after response in current processNot a durable background queue handoff
onOneServer()One scheduler owner per tick using shared cacheAll scheduler hosts must share supported lock-capable cache
Scheduler withoutOverlapping(5)Prevent another scheduled command for up to 5 minutesUnit differs from job middleware's second-based methods
queue:retry-batchRequeue failed batch jobsRequires retained metadata and idempotent effects
queue:prune-batchesBound batch metadata storageRetain 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.

go
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
<?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.

go
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
<?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.

go
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
<?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 ​

StageConcrete changeKeep invariant
1×One worker, indexed due rows, bounded scanRun registry exists before dispatch
10×More workers, per-provider task queues / queues, paginated scansDuplicate attempts use the same operation key
100×Tenant quotas, bounded child workflows, history rollover, partitioned reconciliationNo tenant or stuck page monopolizes progress

One independent operation?Queue job + idempotencyShort fixed sequence?Laravel chain / batchLong-lived coordination?Persist progress and waitsSmall fixed state machineSQL + due scan + version guardBranches / human decisionsTemporal or CadenceEvery option still needs safe external effects, compatible changes and observable recovery.

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 ​

sh
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.

sql
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 ​

sh
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 ​

BeliefReality
Replay recharges every completed paymentRecorded activity results are reused; unrecorded results can require retry
Engine means exactly-once external effectsExternal idempotency or reconciliation is still required
Every queue job is a workflowA job does not necessarily model multistep progress and waits
Laravel chains store no stateSuccessor jobs are serialized; full workflow replay/state is a different capability
Batch cancellation stops running code immediatelyJobs and external operations must cooperate
A timeout proves nothing happenedThe provider may have accepted the operation
A timer must keep a worker thread asleepEngine/due-time storage persists the wait
onOneServer recovers every missed tickIt coordinates currently evaluated scheduled runs
afterCommit is an outboxIt orders dispatch after commit but leaves a crash gap
New code can replay all old historiesCommand and payload compatibility must be tested
Continue-As-New preserves all local state automaticallyThe next run receives only deliberately carried state
Empty queue means all workflows are healthyLost triggers can leave overdue database/history work

Cheat sheet ​

TopicRemember
IdentityStable business Workflow ID, explicit generation for intentional reruns
ReplayReconstruct decisions from history; external I/O belongs in activities
ActivitiesRetry can repeat effects; preserve operation key and input
TimeoutsAttempt clock differs from total execution budget
HeartbeatReport progress, support cancellation, repeat uncertain chunk safely
TimerPersist due time; firing is not exact completion time
ScheduleDefine overlap, missed-period and backfill policy
Message APIsSignal changes asynchronously; Query reads; Update tracks a result
CancellationCooperative cleanup; termination bypasses cleanup
VersioningPreserve old command paths or route compatible workers
HistoryBound fan-out/data size; use Continue-As-New intentionally
LaravelChains order, batches group, application state records business progress
ReconcilerScan base runs, due waits and outputs; persist total failure budgets
BrokerWake-up delivery is not workflow state
TestingVirtual time/unit tests plus history replay and separately executed integration tests

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
Durable ExecutionRecoverable progress and waits across process loss
Workflow DefinitionCode specifying the orchestration
Workflow ExecutionA running or closed instance of that definition
Namespace / DomainTemporal / Cadence isolation and identity boundary
Workflow IDLogical identity chosen by the application
Run IDEngine-assigned identity of one execution run
Workflow ID conflict / reuse policyRules for open identity conflicts and closed identity reuse
Event HistoryPersisted ordered execution events used for reconstruction
CommandWorkflow request to schedule work, timers or other actions
DeterminismCompatibility of emitted commands with recorded history
ReplayReconstructing workflow state from history
Workflow TaskUnit of orchestration decision processing
Activity / Activity TaskExternal operation / one execution attempt
Task Queue / Task ListTemporal / Cadence task routing primitive
Worker / sticky cacheApplication executor / cached workflow state optimization
Idempotency keyStable identity that makes repeated business operations safe
CheckpointPersisted application progress marker
CAS / version guardConditional update requiring the expected version
Retry PolicyAttempt delay, limit and eligible-error rules
Start-To-CloseTimeout for one activity attempt
Schedule-To-StartTimeout waiting for an activity worker
Schedule-To-CloseTotal activity execution timeout
Heartbeat / HeartbeatTimeoutProgress report / bound on missing reports
WorkflowTaskTimeoutTime budget for one orchestration task
WorkflowRunTimeout / WorkflowExecutionTimeoutOne-run / whole execution-chain deadline
Timer / wake_atDurable future wake obligation / SQL absolute due time
Schedule / overlap policyRecurring start specification / behavior when earlier run remains open
Catchup window / backfillAutomatic missed-occurrence horizon / explicitly requested historical occurrences
Signal / Query / UpdateAsynchronous mutation / read-only inspection / tracked state-changing request
Signal-With-StartEnsure execution exists and send a signal through one service operation
Selector / AwaitWithTimeoutWorkflow-safe waiting for events / condition with a timeout
Cancellation / terminationCooperative stop request / service-side forced closure
WaitForCancellationWait for activity cancellation acknowledgement
Disconnected contextWorkflow context allowing cleanup after cancellation
CompensationExplicit business action addressing a previous effect
SideEffect / MutableSideEffectRecord nondeterministic value / record changed value with equality check
Local ActivityActivity run with workflow-worker affinity and reduced scheduling overhead
Patching / GetVersionRecorded version branch preserving old command paths
Worker Versioning / Deployment VersionRouting executions to compatible worker revisions
Continue-As-NewSuccessful rollover into a fresh run/history with carried input
Child Workflow / parent-close policySub-execution / rule for its lifecycle when parent closes
Visibility / Search AttributesExecution search system / indexed business metadata
Payload converter / codecSerialization / optional payload transformation or protection
Bus::chain / Bus::batchLaravel ordered jobs / grouped jobs with progress callbacks
Batchable / job_batchesBatch-participating job trait / default relational batch metadata
allowFailuresBatch option preventing automatic cancellation after a job failure
WithoutOverlapping / onOneServerJob/command overlap lock / scheduler tick coordination
afterCommit / dispatchAfterResponseDispatch ordering after SQL commit / work in the response process after sending
Reconciliation / blocked stateCompare and repair unfinished obligations / explicit work requiring intervention
PEL / XACK / XAUTOCLAIMRedis pending delivery list / acknowledgement / abandoned-entry recovery
Kafka offsetConsumer position in a partition, not workflow business progress
Publisher confirm / manual acknowledgementBroker publication acceptance / consumer settlement boundary

References ​

Built by Morteza Negahi