Go SDK (preview)
Go SDK v0.2.0 is a preview for development and evaluation. The API may change before v1. Cross-release replay, full decode recovery, and the installed worker lifecycle matrix remain gates for leaving preview. Preview qualification.
The Go SDK writes workflows, activities and workers in Go against the
same durable execution model and public protocol as the other SDKs. Workflow
code is plain Go: one input struct, one result, a workflow.Context, and
errors returned to the caller. The SDK replays every workflow task from
history, checks it against the recorded commands, and reports drift as a
typed failure.
- Module path:
go.durable-workflow.com/sdk - Documentation site: go.durable-workflow.com
- Source: durable-workflow/sdk-go
- Go versions: the two most recent major releases, Go 1.26 and Go 1.27
- Runtime: a self-hosted native Server, or
dw server:start-dev, that advertises worker protocol1.20
Use the 2.0 Capability Index to compare SDKs. This page covers only what the Go SDK supports today.
Packages
| Import path | Contents |
|---|---|
go.durable-workflow.com/sdk | Typed references (Workflow, Activity, Signal, Query, Update), Unit and ApplicationError. The package name is durableworkflow; the examples import it as dw. |
go.durable-workflow.com/sdk/workflow | Replay-safe workflow operations and workflow.Context. |
go.durable-workflow.com/sdk/worker | The registry, the managed Worker, activity helpers and the offline replayer. |
go.durable-workflow.com/sdk/client | Starting runs and sending signals, queries, updates and cancellation requests. The client never imports worker code. |
go.durable-workflow.com/sdk/metrics | The Recorder interface and the shared metric names. |
go.durable-workflow.com/sdk/otel | A separate module that adapts an OpenTelemetry meter to metrics.Recorder. |
go.durable-workflow.com/sdk/workflowtest | A separate module that starts an isolated development server for tests. |
The core module depends only on the Go standard library. Payloads use the
shared Avro Value format, so a Go worker exchanges inputs and results with
PHP, Python and Rust workers.
Install
Install the published preview from your Go module:
go get go.durable-workflow.com/[email protected]
Run your first workflow
You need Go 1.26 or 1.27, curl, and the
Durable Workflow CLI, which provides the development server. Use
CLI 2.16.0 for this example. Start the server in one terminal with a private token file:
workdir=$(mktemp -d)
printf '%s\n' "$workdir"
(umask 077; openssl rand -hex 24 > "$workdir/token")
dw server:start-dev --host=127.0.0.1 --port=0 --db=sqlite \
--data-dir="$workdir/data" --token-file="$workdir/token"
In a second terminal, open an empty directory. Replace PORT with the port announced by the Server and /path/to/workdir with the directory printed in the first terminal:
curl -fsSLo main.go https://raw.githubusercontent.com/durable-workflow/sdk-go/v0.2.0/examples/firstworkflow/main.go
go mod init hello-workflow
go get go.durable-workflow.com/[email protected]
DW_ENDPOINT="http://127.0.0.1:PORT" DW_AUTH_TOKEN="$(cat /path/to/workdir/token)" go run .
The example registers a Go worker, starts a run, completes its workflow task
and prints Hello, Durable Workflow!.
The repository quickstart also shows how to run the example from a checkout.
Name workflows and activities
Every workflow, activity, signal, query and update has an explicit wire name, bound to its Go types through a typed reference. Names never come from Go function symbols, so renaming a function does not change history. A workflow or activity written in another SDK is called by the same name.
The SDK trims names using the Server’s rules before using them on the wire.
package orders
import dw "go.durable-workflow.com/sdk"
type OrderInput struct {
OrderID string
}
type ChargeInput struct {
OrderID string
}
type Approval struct {
Approved bool
}
var (
ProcessOrder = dw.Workflow[OrderInput, string]("orders.process")
ChargeCard = dw.Activity[ChargeInput, string]("orders.charge")
Approve = dw.Signal[Approval]("orders.approve")
Status = dw.Query[dw.Unit, string]("orders.status")
SetNote = dw.Update[Note, string]("orders.set-note")
)
type Note struct {
Text string
}
Each input is one struct. Use dw.Unit when an operation takes no input or
returns no result.
Workflows
A workflow is a function that takes a workflow.Context and the input
struct. Durable operations are functions in the workflow package:
| Operation | Behavior |
|---|---|
workflow.CallActivity(ctx, ref, input) | Schedules a remote activity and waits for its typed result. |
workflow.CallActivityWithOptions(ctx, ref, input, options) | Sets the activity queue, deadlines and retry policy for this call. |
workflow.Sleep(ctx, duration) | Waits on a durable timer. The duration is a positive whole number of seconds. |
workflow.AwaitSignal(ctx, ref) | Waits for the next input of a signal. |
workflow.AwaitCondition(ctx, options, predicate) | Waits until a predicate over workflow state is true, with an optional timeout. |
workflow.SideEffect(ctx, callback) | Records a nondeterministic value once and reuses it on replay. |
workflow.ContinueAsNew(ctx, input) | Closes the run and starts a fresh run of the same workflow on the same queue. |
ctx.Now() | Returns the replayed workflow time. |
workflow.WithValue(ctx, key, value) | Attaches a workflow-scoped value that signal and update handlers can read. |
package orders
import (
"time"
"go.durable-workflow.com/sdk/workflow"
)
func processOrder(ctx workflow.Context, input OrderInput) (string, error) {
approval, err := workflow.AwaitSignal(ctx, Approve)
if err != nil {
return "", err
}
if !approval.Approved {
return "rejected", nil
}
if err := workflow.Sleep(ctx, 30*time.Second); err != nil {
return "", err
}
return workflow.CallActivity(ctx, ChargeCard, ChargeInput{OrderID: input.OrderID})
}
Return the error from every durable operation straight away. The SDK uses it to suspend the workflow at the operation and resume it on the next task.
Workflow code must be deterministic. Read the time with ctx.Now(), generate
random values inside workflow.SideEffect, and do I/O in activities. Do not
start goroutines, use channels or select across durable operations, or read
the wall clock. The worker owns the goroutines of each workflow task and
replays the task cold from history.
AwaitCondition takes a stable Key, a Revision that changes when the
predicate's replay behavior changes, and an optional whole-second Timeout.
It returns false when the timeout expires before the predicate becomes
true. Signal handlers registered with worker.RegisterSignal run before each
re-evaluation:
type approvedKey struct{}
func waitForApproval(ctx workflow.Context, _ dw.Unit) (bool, error) {
approved := false
ctx = workflow.WithValue(ctx, approvedKey{}, &approved)
return workflow.AwaitCondition(ctx, workflow.ConditionOptions{
Key: "orders.approved", Revision: "r1", Timeout: time.Hour,
}, func() bool { return approved })
}
func applyApproval(ctx workflow.Context, input Approval) error {
*ctx.Value(approvedKey{}).(*bool) = input.Approved
return nil
}
The preview replays one operation at a time. See Not yet supported for the remaining limits.
Activities
An activity is an ordinary Go function that takes a context.Context and an
input struct. It can do I/O, call other services and block.
func chargeCard(ctx context.Context, input ChargeInput) (string, error) {
worker.ActivityLogger(ctx).Info("charging card", "order", input.OrderID)
if err := worker.RecordActivityHeartbeat(ctx, worker.ActivityProgress{Message: "authorizing"}); err != nil {
return "", err
}
return "charge-" + input.OrderID, nil
}
- Heartbeats.
worker.RecordActivityHeartbeatreports progress and renews the task lease when the Server advertises lease renewal. The attempt's execution deadline stays fixed. It returnsworker.ErrActivityHeartbeatUnavailablewhen the context has no heartbeat sender, for example outside an activity callback, andworker.ErrActivityHeartbeatTooLargewhen the progress exceeds the advertised payload limit. - Cancellation and deadlines. The activity context ends when the attempt
stops.
context.Cause(ctx)tells you why:worker.ErrActivityCancelledwhen the Server cancels the attempt,worker.ErrActivityWorkerLostwhen the Server refuses the worker's claim,worker.ErrWorkerShutdownwhen the worker stops, or a*worker.ActivityTimeoutErrorwith the timeoutKind. - Retries and timeouts. Use
workflow.CallActivityWithOptions(ctx, ref, input, options)to set the queue, deadlines and retry policy. Timeouts and retry backoff use whole seconds.
Register and run a worker
Bind each reference to its handler in a worker.Registry, then run a
worker.Worker on a task queue. Before the worker polls, registration
refuses invalid wire names, inputs that are not structs, nil handlers,
duplicate names and alias collisions. A collision error names both
registration sites.
package main
import (
"context"
"errors"
"log"
"os"
"os/signal"
"syscall"
"time"
"go.durable-workflow.com/sdk/worker"
"go.durable-workflow.com/sdk/workflow"
)
func main() {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
var registry worker.Registry
if err := worker.RegisterWorkflow(®istry, ProcessOrder, processOrder); err != nil {
log.Fatal(err)
}
if err := worker.RegisterSignal(®istry, ProcessOrder, Approve, func(workflow.Context, Approval) error { return nil }); err != nil {
log.Fatal(err)
}
if err := worker.RegisterActivity(®istry, ChargeCard, chargeCard); err != nil {
log.Fatal(err)
}
w := worker.New(®istry, worker.RegistrationConfig{
Endpoint: os.Getenv("DW_ENDPOINT"),
Token: os.Getenv("DW_AUTH_TOKEN"),
TaskQueue: "orders",
WorkerID: "orders-worker-1",
ShutdownTimeout: 20 * time.Second,
})
if err := w.Run(ctx); err != nil && !errors.Is(err, context.Canceled) {
log.Fatal(err)
}
}
Run registers the worker, polls workflow, activity and query tasks with one
slot for each kind, and returns after the worker has drained and
deregistered. When ctx ends or Stop(ctx) is called, the worker stops
polling, gives running activities ShutdownTimeout (20 seconds by default)
before cancelling them with worker.ErrWorkerShutdown, waits for their
reports, and deregisters. A worker runs once.
RegistrationConfig also takes Namespace (default default), an
HTTPClient, a Logger (*slog.Logger), a Metrics recorder, and
WorkflowWarningAfter, which logs a warning when workflow code runs longer
than five seconds without reaching a durable operation.
Reusing a WorkerID supersedes the previous incarnation's fence in the same
namespace. For scripts and tests, worker.Register returns a Registration
whose RunOneWorkflow, RunOneActivity and RunOneQuery methods handle
one task each, and Deregister releases it.
Use worker.RegisterWorkflowWithRevision to give a workflow an authored
replay revision. Keep the revision when an equivalent build moves or
recompiles the workflow, and change it after an intentional change to its
replay behavior.
Start a workflow with the client
sdk, err := client.New(client.Config{
Endpoint: os.Getenv("DW_ENDPOINT"),
Token: os.Getenv("DW_AUTH_TOKEN"),
})
if err != nil {
return err
}
handle, err := client.Start(ctx, sdk, ProcessOrder, client.StartOptions{
WorkflowID: "order-1042",
TaskQueue: "orders",
}, OrderInput{OrderID: "1042"})
if err != nil {
return err
}
result, err := handle.Result(ctx)
client.Start returns a *client.Handle for the selected run, with its
WorkflowID and RunID. Result waits for the run to close and decodes the
typed result. client.Config also takes Namespace, HTTPClient, Logger
and Metrics. When HTTPClient is omitted, the client refuses redirects.
To start a workflow by name, for example one registered by another SDK, use
sdk.StartNamed(ctx, name, options, arguments...), which returns a
*client.Handle[any].
Signals
Declare a signal on its workflow with worker.RegisterSignal so the Server
admits it, then send it from the client:
err := client.Signal(ctx, handle, Approve, Approval{Approved: true})
In workflow code, workflow.AwaitSignal returns the next input directly. A
signal handler registered for an AwaitCondition wait runs synchronously
with the workflow's values and cannot issue durable operations.
Queries
Go queries require Native Server 3.30.0 or later. The worker needs the replay
clock sent with query tasks. The development server bundled with CLI 2.15.0
returns HTTP 409 (query_rejected) for Go queries.
Register a query handler with worker.RegisterQuery and call it with
client.Query:
status, err := client.Query(ctx, handle, Status, dw.Unit{})
The worker replays the run's history before calling the handler, and the
handler's workflow.ReadOnlyContext returns that history's time from
Now(). In the preview, the query context does not carry workflow-scoped
values, so a query cannot yet read state that the workflow keeps in memory.
Updates
An update handler runs at a recorded durable wait, inherits the workflow's
clock and values, and returns a typed result. It cannot issue durable
operations. If it returns an error, nothing is recorded and the next replay
discards its in-memory changes. In this example, the workflow has stored a
*string under noteKey{} with workflow.WithValue.
type noteKey struct{}
err := worker.RegisterUpdate(®istry, ProcessOrder, SetNote,
func(ctx workflow.Context, input Note) (string, error) {
*ctx.Value(noteKey{}).(*string) = input.Text
return "saved", nil
})
update, err := client.StartUpdate(ctx, handle, SetNote, Note{Text: "gift wrap"}, client.UpdateOptions{})
if err != nil {
return err
}
result, err := update.Result(ctx)
StartUpdate waits for admission and returns an *client.UpdateHandle with
the UpdateID and the RequestID that identifies the submission across
retries. Set UpdateOptions.RequestID to choose it yourself. Result reads
the outcome without resubmitting, also after the run continues as new.
If a request fails, *client.UpdateRequestError keeps the RequestID so
that you can retry the same submission. A failed update returns
*client.UpdateFailedError with FailureID and FailureMessage. When the
worker cannot decode a new update's input, it fails that update with
update_argument_decode_failed before calling the handler, and the run
continues.
Cancellation
Request cooperative cancellation of a selected run from the client:
receipt, err := handle.RequestCancellation(ctx, client.CancellationOptions{
Reason: "customer cancelled",
CleanupTimeout: 30 * time.Second,
})
The receipt has the RequestID, RequestedAt, CleanupDeadline and a
Duplicate flag for a repeated request. Cancellation reaches activities
through worker.ErrActivityCancelled on a worker that runs only activities,
because only such a worker opts in to cooperative cancellation. Workflow code
cannot yet observe a cancellation request: a workflow task that carries one
fails. Termination is not available in the Go client yet. Use the
dw CLI or another SDK to terminate a run.
Errors
- Activity failures. Return a
*dw.ApplicationErrorto control how a failure crosses process boundaries. ItsType,Message,NonRetryableflag andDetailsare reported to the Server, andCausestays available toerrors.Isanderrors.Asin the process.NonRetryableis honored anywhere in a wrap chain. Other errors are reported with the typeGoActivityFailure. - Activity outcomes. In workflow code, use
errors.Asto read a recorded terminal failure or timeout as*dw.ActivityError. For an application failure,Causecontains the portable type, message, retry flag and decoded details. A timeout has aTimeoutKindand a nilCause. Useerrors.Aswith an*dw.ApplicationErrortarget for an application failure. - Workflow errors. In the preview, an error returned from workflow code, a panic, or a replay mismatch fails the workflow task, not the run. The run stays open and a fixed worker can resume it.
- Replay drift.
*worker.ShapeMismatchreports the authored and recorded command, the history sequence, the source line, and a stableReason, such asrecorded_command_mismatch,recorded_command_detail_mismatch,timer_delay_mismatchoractivity_identity_mismatch. Payloads that cannot be decoded during replay producepayload_type_mismatchwith the recorded history sequence. - Client errors. Failed requests return
*client.Errorwith theOperation,Endpoint,Code,StatusCodeand anyRetryAfterSeconds.Resultreturns a*client.ErrorwhoseCodeisfailed,cancelledorterminatedwhen the run did not complete. - Registration errors.
*worker.RegistrationErrornames the conflicting registration sites.
Replay
Replay exported history against the current code before you deploy a
workflow change. Export a run with dw workflow:history-export or
workflowtest, then replay a directory of exports:
var registry worker.Registry
if err := worker.RegisterWorkflow(®istry, ProcessOrder, processOrder); err != nil {
return err
}
root, err := os.OpenRoot("testdata/histories")
if err != nil {
return err
}
defer root.Close()
if err := worker.ReplayDirectory(ctx, ®istry, root.FS()); err != nil {
return err
}
worker.ReplayExport replays one Native history export. The offline
replayer uses the same command matcher and registry as the live worker, and
ReplayOptions.MaxBundleBytes limits the export size.
Metrics and logging
Set client.Config.Metrics and worker.RegistrationConfig.Metrics to a
metrics.Recorder. It receives the shared client and worker counters and
seconds histograms:
durable_workflow_client_requestsanddurable_workflow_client_request_duration_seconds, labeled withmethod,route,plane,status_codeandoutcomedurable_workflow_worker_polls,durable_workflow_worker_poll_duration_seconds,durable_workflow_worker_tasksanddurable_workflow_worker_task_duration_seconds, labeled withtask_kind,task_queueandoutcomedurable_workflow_worker_task_schedule_to_start_seconds, labeled withtask_kindandtask_queue
Routes are bounded templates, such as
/workflows/{workflow_id}/runs/{run_id}. Keep task queue names bounded to
control label cardinality. Leave Metrics nil to disable recording. The
otel module provides NewRecorder for an OpenTelemetry meter.
The client and worker accept a *slog.Logger. Worker task-failure logs carry
the task identity and a typed failure code, not the error text, which could
contain payload values.
Test with a development server
The workflowtest module starts an isolated, pinned dw development server
for each test, with a free loopback port, its own SQLite data and a fresh
token:
server := workflowtest.StartDevServer(t)
cfg := client.Config{Endpoint: server.Endpoint(), Token: server.Token()}
server.ExportHistory(ctx, workflowID, runID) captures a run as a history
export for worker.ReplayExport.
Not yet supported
The preview does not yet provide:
- Go queries on the development server bundled with CLI 2.15.0 (see Queries)
- child workflows, parallel groups and first-completion selection
- local activities
- version markers and saga compensation
- workflow-side handling of cancellation
- termination, describe and list operations in the client
- workflow streams, schedules, payload protection, worker sessions and sticky execution
- query access to workflow state
Each feature reaches this guide when it is available on the SDK's main branch.
Laravel Go integration
The Laravel Go integration preview connects a Laravel application to Durable Workflow service mode. It requires Go 1.27 and uses Go SDK v0.1.1. In a new Laravel application:
laravel new --go my-app
cd my-app
go get go.durable-workflow.com/sdk/integrations/[email protected]
Import the integration as dwlaravel and add dwlaravel.New(durable.Register) to laravel.Options.Packages. Use your durable.Register function to bind workflow and activity handlers. In a Laravel request or command, dwlaravel.Client(ctx) returns the application's control-plane client.
Start the local development Server in one terminal.
dw server:start-dev
From the application directory in a second terminal, start the worker.
laravel durable-workflow:work
The default task queue is default. With APP_ENV=local, a loopback endpoint and empty credential settings, the package uses the development credential. See the package setup and environment options and the integration tracking issue for the file-watch restart work.