Temporal go
Build durable applications on Temporal (temporal.io) with the Go SDK — Workflows, Activities, Workers, Signals, Queries, Updates, child Workflows, retries, and versioning. Use when writing or reviewing Temporal Go code, debugging non-determinism or replay failures, choosing timeouts and retry policies, or setting up Workflow tests.
By- name:
- temporal-go
- description:
- Build durable applications on Temporal (temporal.io) with the Go SDK — Workflows, Activities, Workers, Signals, Queries, Updates, child Workflows, retries, and versioning. Use when writing or reviewing Temporal Go code, debugging non-determinism or replay failures, choosing timeouts and retry policies, or setting up Workflow tests.
Building Temporal applications in Go
When to use this skill
Use this when the task involves go.temporal.io/sdk: writing a Workflow or
Activity, setting up a Worker, wiring a client, choosing timeouts or retry
policies, adding Signals/Queries/Updates, testing Workflow code, or diagnosing
a NonDeterministicError / replay failure.
Not a fit for: Temporal Cloud account administration, self-hosted cluster operations, or SDKs other than Go.
The mental model
A Workflow is a durable function. Temporal records every step it takes into an Event History. If the process running it crashes, Temporal replays that history against your code on another Worker to rebuild the in-memory state, then continues from where it left off. Your function appears to run for days or months, uninterrupted, across deploys and machine failures.
Replay is the whole reason determinism matters. Replayed code must make the same decisions it made the first time. If it doesn't — because it read the clock, generated a UUID, or called an API — the rebuilt state diverges from the recorded history and Temporal fails the Workflow Task.
So the code is split in two. Workflow code orchestrates: it decides what runs, in what order, and what to do on failure. It must be deterministic. Activity code does the actual work: HTTP calls, database writes, file I/O, anything that can fail on its own or return a different answer twice. Activities are ordinary Go with no restrictions, and Temporal retries them for you.
A Worker is your process, polling a Task Queue for work and executing the Workflow and Activity code you registered on it. Temporal stores state and hands out tasks; it never runs your code. A client starts Workflows and sends them Signals, Queries, and Updates from outside.
Determinism: read this before writing Workflow code
The single most common way to get Temporal wrong is putting non-deterministic
work directly in a Workflow function. In Go there is no sandbox — nothing
stops you from calling time.Now() in Workflow code. It compiles, it runs, and
it corrupts the Execution on the first replay, often days later in production.
Inside a Workflow function, never call:
| Never | Use instead |
|---|---|
time.Now() |
workflow.Now(ctx) |
time.Sleep() |
workflow.Sleep(ctx, d) |
time.After() in select |
workflow.NewTimer(ctx, d) + workflow.Selector |
rand.Intn() |
workflow.SideEffect(ctx, ...) |
uuid.New() |
workflow.SideEffect(ctx, ...) |
os.Getenv, file/network/DB I/O |
an Activity |
go func() |
workflow.Go(ctx, ...) |
sync.Mutex, chan, select |
workflow.Mutex, workflow.Channel, workflow.Selector |
| map iteration where order matters | sort the keys first |
| mutable package-level state | Workflow-local variables |
Two rules behind the table:
- Anything that can return a different answer on a second run must be
recorded, not recomputed. Activities and
SideEffectrecord their results in history; replay reads the recorded value instead of running the code again. - Never block a Workflow goroutine on anything but a Workflow API. Blocking on a real channel, mutex, or syscall stalls the Workflow Task until the deadlock detector kills it (1 second of wall-clock progress by default).
Decision checklist
For every step you are about to add, ask:
- Does it call an external system (HTTP, DB, queue, filesystem, another service)?
- Can it fail independently of the rest of the Workflow, in a way worth retrying?
- Is it non-deterministic (clock, randomness, UUID, env, changing data)?
- Does it take more than a few milliseconds of CPU, or block?
Any "yes" → it belongs in an Activity, not in Workflow code.
If it is pure computation over data the Workflow already holds — branching, arithmetic, building a struct — leave it inline.
SideEffect is the narrow exception for cheap non-deterministic values (a UUID,
a random number) that aren't worth an Activity's round trip. It records the value
in history but gets no retries and no timeouts — never put I/O in it.
Full rules and wrong-vs-right code: references/determinism.md.
Getting started
templates/go-starter/ is a complete, runnable project — Workflow, Activities,
Worker, client, and tests — verified against temporal server start-dev. Copy it
as a starting point rather than assembling one from scratch:
temporal server start-dev # UI on http://localhost:8233
cd templates/go-starter
go run ./worker # terminal 1
go run ./starter # terminal 2
go test ./...
It demonstrates explicit retry policies, non-retryable errors, heartbeating, a Signal raced against a timer, a Query handler, deterministic ID generation, and both unit and replay tests.
Reference files
Load these as needed — don't read them all up front.
| File | Read it when |
|---|---|
references/determinism.md |
Writing/reviewing Workflow code, or debugging a replay failure |
references/go-sdk.md |
You need the Go API surface: options, Selectors, Signals/Queries/Updates, child Workflows, ContinueAsNew, compensation/Saga |
references/concepts.md |
A Temporal term is unfamiliar |
references/testing.md |
Writing Workflow tests, mocking Activities, or adding replay tests |
references/pitfalls.md |
Choosing timeouts/retries, deploying a change to running Workflows, or hitting size limits |
Non-negotiables
- Every Activity needs
StartToCloseTimeout(orScheduleToCloseTimeout). The SDK refuses to run an Activity with neither set. - Set an explicit
RetryPolicywithMaximumAttemptson Activities that call external systems. The default is unlimited retries, which turns a permanently-broken dependency into a Workflow that hangs forever. - Mark permanent failures non-retryable with
temporal.NewNonRetryableApplicationError(...)so bad input fails fast. - Make Activities idempotent. Delivery is at-least-once; any Activity can run twice with the same input.
- Never change the sequence of Workflow API calls in code that has running
Executions without
workflow.GetVersion. Seereferences/pitfalls.md. - In any multi-step transaction, plan the failure path. Temporal retries
steps but never undoes completed ones — if step 3 fails permanently, steps 1
and 2 stay committed. Order processing, payments, and bookings all need
explicit compensation; see the Saga section in
references/go-sdk.md.
Open this reference as its own page
Core concepts glossary
Execution model
Temporal Service (Server/Cluster) — Stores Event Histories, schedules Tasks, enforces timeouts. It never runs your code; it only records what happened and hands out work.
Worker — Your process, using the SDK to poll a Task Queue and execute the Workflow and Activity code registered on it. Scaling throughput means running more Workers. Nothing runs if no Worker polls the queue — the most common cause of a Workflow that sits in "Running" with no progress.
Task Queue — A named channel connecting Workflow/Activity Tasks to the
Workers that can run them. The name in client.StartWorkflowOptions.TaskQueue
and in worker.New(...) must match exactly.
Namespace — Isolation boundary for Workflows, with its own retention period
and configuration. The dev server gives you default.
Workflows
Workflow Definition — The function you write (func(workflow.Context, In) (Out, error)).
Must be deterministic; see determinism.md.
Workflow Type — The registered name, defaulting to the Go function name. Renaming the function changes the Type and orphans running Executions unless you register an explicit name.
Workflow Execution — One running instance, identified by Workflow ID
(yours; use a business key) plus Run ID (Temporal's, new for each run,
including after ContinueAsNew or a retry).
Event History — The append-only, durable log of everything the Execution did: Activities scheduled and completed, timers, Signals received, and their results. This is the Workflow's state; it's what replay reads. Capped at 51,200 events / 50 MB.
Workflow Task — A unit of work handed to a Worker telling it to advance the Workflow: replay the history, run until the code blocks, and report back the new commands. Workflow code runs inside these, which is why a Workflow Task must finish quickly (the deadlock detector fires after 1s of no progress).
Replay — Re-running Workflow code from the start against recorded history to rebuild in-memory state after a crash, deploy, or long sleep. The reason determinism is mandatory.
Command — What Workflow code asks Temporal to do (schedule an Activity, start a timer, complete the Workflow). The recorded sequence of commands is what must stay stable across replays.
ContinueAsNew — Atomically ends the current Execution and starts a fresh one with a new (empty) history, carrying state forward as input. How long-running or looping Workflows stay under the history cap.
Activities
Activity Definition — A normal Go function (func(context.Context, In) (Out, error))
that does real work: I/O, API calls, computation. No determinism constraints.
Activity Execution — One invocation, retried per its Retry Policy. Delivery is at-least-once, so Activities should be idempotent.
Heartbeat — activity.RecordHeartbeat(ctx, details) tells the server the
Activity is alive and checkpoints progress. Required for long Activities so a
dead Worker is detected quickly (via HeartbeatTimeout) rather than waiting out
StartToCloseTimeout. Details are returned to the next attempt.
Local Activity — Runs in the same Worker process without a Task Queue round trip. Lower latency, weaker guarantees. Only for very short operations.
Retry Policy — InitialInterval, BackoffCoefficient, MaximumInterval,
MaximumAttempts, NonRetryableErrorTypes. Activities retry by default with
unlimited attempts; Workflows do not retry by default. See pitfalls.md.
Timeouts — StartToClose (one attempt), ScheduleToClose (all attempts
including backoff), ScheduleToStart (queue wait), Heartbeat. One of
StartToClose / ScheduleToClose is required.
Messages
Signal — Asynchronous one-way message into a running Workflow. Mutates state,
returns nothing, is recorded in history. SignalWithStartWorkflow delivers a
Signal and starts the Workflow if it isn't running.
Query — Synchronous, read-only request for Workflow state. Must not mutate state, execute Activities, or block. Not recorded in history — so it can be served by replay against any Worker.
Update — Synchronous call that can mutate state and return a value, recorded in history, with an optional validator that can reject the request before it's recorded. Roughly "a Signal and a Query in one, with rejection".
Choosing between them: read-only → Query; fire-and-forget → Signal; need a result or must reject bad input → Update.
Composition
Child Workflow — A Workflow started by another Workflow, with its own Execution, history budget, and lifecycle. Parent Close Policy decides what happens to it when the parent closes. Use when you need separate history or different Task Queue routing; otherwise prefer an Activity.
SideEffect — Records the result of a cheap non-deterministic computation (UUID, random number) in history so replay reuses the value. Not an Activity: no retries, no timeouts. Never do I/O in it. MutableSideEffect is a variant that re-evaluates and only records when the value changes.
Timer — workflow.Sleep / workflow.NewTimer. Durable: survives Worker
restarts, consumes no resources while pending, and can safely span months.
Selector — workflow.NewSelector(ctx), the deterministic analogue of Go's
select. Races futures, timers, and Signal channels.
Await — workflow.Await(ctx, predicate) blocks until a condition over
Workflow state becomes true. Re-evaluated after each event, so keep it pure.
Operations
Versioning / Patching — workflow.GetVersion branches between old and new
code paths so a deploy doesn't break in-flight Executions. Worker Versioning
is the alternative: pin Workers to a Build ID and let old Executions finish on
old code. See pitfalls.md.
Data Converter — Controls serialization of inputs, outputs, and Signals (JSON by default). The extension point for encryption or compression.
Search Attributes / Memo — Indexed (queryable) and non-indexed metadata attached to an Execution, for finding Workflows in the UI or via List filters.
Open this reference as its own page
Determinism in Temporal Go Workflows
Why replay demands determinism
Temporal does not snapshot your Workflow's memory. It stores an Event History — the ordered list of commands your Workflow issued (timers started, Activities scheduled, Signals received) and their results.
When a Worker picks up a Workflow whose state it doesn't have in memory — after a crash, a deploy, a rebalance, or just a long sleep — it replays the history: it runs your Workflow function again from line one, intercepting each Workflow API call and feeding back the recorded result instead of doing the work again. Once the recorded history is exhausted, execution continues live.
For this to reconstruct the same state, the replayed run must issue the same commands in the same order. If it doesn't, Temporal detects the divergence and fails the Workflow Task with a non-determinism error.
Two consequences worth internalizing:
- Your Workflow function may execute many times over its life. Anything with a visible side effect will happen on every replay unless Temporal records it.
- Replay uses today's code against yesterday's history. Deploying a
change that alters command order breaks Workflows that are already running.
See
pitfalls.mdfor versioning.
Go has no workflow sandbox. Unlike the TypeScript SDK, which patches Date
and Math.random inside an isolated context, the Go SDK cannot stop you from
calling time.Now(). It compiles and runs fine, and the damage surfaces only on
the first replay — often days later, in production. The discipline is entirely
on you and on code review.
What must stay stable
The SDK tracks the sequence of these operations. Reordering, adding, or removing any of them mid-flight breaks replay:
- Scheduling or cancelling Activities and child Workflows
- Starting or cancelling Timers
- Signalling external Workflows
SideEffectandMutableSideEffectGetVersioncalls- Upserting Search Attributes or Memos
- Completing, failing, cancelling, or continuing-as-new
Things you can change freely: timer durations, Activity options (timeouts, retry policies), Activity input values, and logging.
Wrong vs. right
Clock
// WRONG — a different value on every replay.
deadline := time.Now().Add(24 * time.Hour)
if time.Now().After(cutoff) { ... }
// RIGHT — workflow.Now returns the recorded Workflow Task time, stable on replay.
deadline := workflow.Now(ctx).Add(24 * time.Hour)
if workflow.Now(ctx).After(cutoff) { ... }
Sleeping and timers
// WRONG — blocks the Worker thread; invisible to Temporal; dies with the process.
time.Sleep(30 * time.Minute)
// WRONG — real timer inside a real select.
select {
case <-time.After(time.Hour):
case msg := <-someGoChannel:
}
// RIGHT — durable timer; survives Worker restarts, costs nothing while pending.
if err := workflow.Sleep(ctx, 30*time.Minute); err != nil {
return err // context cancelled
}
// RIGHT — race a Signal against a durable timer.
sel := workflow.NewSelector(ctx)
sel.AddFuture(workflow.NewTimer(ctx, time.Hour), func(workflow.Future) {
timedOut = true
})
sel.AddReceive(workflow.GetSignalChannel(ctx, "approve"), func(c workflow.ReceiveChannel, _ bool) {
c.Receive(ctx, &approval)
})
sel.Select(ctx)
A workflow.Sleep of a month consumes no resources — the Worker holds nothing
in memory while it waits.
Randomness and UUIDs
// WRONG — new value each replay; downstream writes land under different keys.
id := uuid.New().String()
if rand.Float64() < 0.1 { ... }
// RIGHT — SideEffect records the value in history and replays the recorded one.
var id string
if err := workflow.SideEffect(ctx, func(workflow.Context) any {
return uuid.New().String()
}).Get(&id); err != nil {
return err
}
SideEffect never re-executes on replay. It is not an Activity: no retries, no
timeouts, no visibility into failure. Keep it to cheap, in-process, always-succeeds
computation. Anything that can fail belongs in an Activity.
Note that the Workflow ID and Run ID are already stable and available via
workflow.GetInfo(ctx) — prefer deriving deterministic keys from them over
generating fresh UUIDs:
info := workflow.GetInfo(ctx)
idempotencyKey := fmt.Sprintf("%s-payment", info.WorkflowExecution.ID)
I/O
// WRONG — network call in Workflow code. Repeats on replay, can't be retried,
// blocks the Workflow Task, and will trip the deadlock detector if slow.
resp, err := http.Get("https://api.example.com/rate")
row := db.QueryRow("SELECT ...")
key := os.Getenv("API_KEY")
// RIGHT — an Activity. Retried, timed out, and recorded.
ao := workflow.ActivityOptions{
StartToCloseTimeout: 30 * time.Second,
RetryPolicy: &temporal.RetryPolicy{MaximumAttempts: 5},
}
var rate float64
err := workflow.ExecuteActivity(workflow.WithActivityOptions(ctx, ao), FetchRate).Get(ctx, &rate)
Configuration (like API_KEY) should be read by the Worker at startup and
closed over by the Activity, or passed as Workflow input — never read from the
environment inside Workflow code.
Concurrency
// WRONG — real goroutines and channels are invisible to the SDK; the scheduler
// can't replay their interleaving, and blocking on them deadlocks the task.
go doSomething()
ch := make(chan int)
var mu sync.Mutex
// RIGHT — SDK primitives run on a single deterministic scheduler.
workflow.Go(ctx, func(ctx workflow.Context) {
_ = workflow.ExecuteActivity(ctx, Notify).Get(ctx, nil)
})
ch := workflow.NewChannel(ctx)
mu := workflow.NewMutex(ctx)
To run Activities in parallel, start them without blocking and collect the futures:
futures := make([]workflow.Future, 0, len(items))
for _, item := range items {
futures = append(futures, workflow.ExecuteActivity(ctx, Process, item))
}
for _, f := range futures {
if err := f.Get(ctx, nil); err != nil {
return err
}
}
Iteration order
// WRONG — Go randomizes map iteration order; a different order each replay
// means Activities are scheduled in a different sequence.
for id, item := range itemsByID {
workflow.ExecuteActivity(ctx, Process, id, item)
}
// RIGHT — impose a stable order.
ids := make([]string, 0, len(itemsByID))
for id := range itemsByID {
ids = append(ids, id)
}
sort.Strings(ids)
for _, id := range ids {
workflow.ExecuteActivity(ctx, Process, id, itemsByID[id])
}
Global state
// WRONG — shared across every Workflow Execution on the Worker, and not
// reconstructed on replay.
var counter int
func MyWorkflow(ctx workflow.Context) error {
counter++
}
Keep all state in local variables inside the Workflow function. They are reconstructed by replay; package-level variables are not.
Logging
workflow.GetLogger(ctx) suppresses output during replay, so recovery doesn't
produce duplicate log lines. Plain log.Println or fmt.Println will print
again on every replay.
logger := workflow.GetLogger(ctx)
logger.Info("order received", "orderID", order.ID)
Recognizing a determinism failure
Symptoms: the Workflow stalls with a Workflow Task failing repeatedly, and the
UI or Worker logs show:
NonDeterministicError: unable to find command ... history event ...
Typical causes, in rough order of frequency:
- Code was deployed that added/removed/reordered Activity or timer calls in a
Workflow with running Executions → needs
workflow.GetVersion(pitfalls.md). - Non-deterministic call in Workflow code (the table in
SKILL.md). - Map iteration or other unordered traversal driving command order.
- The Workflow's behaviour depending on Worker-local state — an env var, a package variable, a config file read at replay time.
Reproduce it locally with a replay test against the failing Execution's history
rather than guessing — see testing.md.
Open this reference as its own page
Go SDK idioms
Import paths (module go.temporal.io/sdk, verified against v1.47.0):
import (
"go.temporal.io/sdk/activity" // Activity context helpers
"go.temporal.io/sdk/client" // starting/signalling from outside
"go.temporal.io/sdk/temporal" // RetryPolicy, error constructors
"go.temporal.io/sdk/testsuite" // test environments
"go.temporal.io/sdk/worker" // Worker, replayer
"go.temporal.io/sdk/workflow" // Workflow-side API
)
Shapes
A Workflow takes workflow.Context first and returns error, optionally
with one result value before it:
func MyWorkflow(ctx workflow.Context, input MyInput) (*MyResult, error)
An Activity takes a standard context.Context first, same return shape:
func MyActivity(ctx context.Context, input MyInput) (*MyResult, error)
Inputs and outputs are serialized (JSON by default). Use exported struct fields, and prefer a single struct parameter over positional arguments — adding a field to a struct is backward-compatible, adding a parameter is not.
Worker
c, err := client.Dial(client.Options{}) // defaults to localhost:7233
defer c.Close()
w := worker.New(c, "my-task-queue", worker.Options{})
w.RegisterWorkflow(MyWorkflow)
w.RegisterActivity(MyActivity)
err = w.Run(worker.InterruptCh()) // blocks until interrupted
Registering by function value means the Workflow Type name is the function name
(MyWorkflow). To decouple the wire name from the Go identifier — so renaming
the function doesn't orphan running Executions — register explicitly:
w.RegisterWorkflowWithOptions(MyWorkflow, workflow.RegisterOptions{Name: "MyWorkflow"})
w.RegisterActivityWithOptions(MyActivity, activity.RegisterOptions{Name: "MyActivity"})
Activities can also be registered as a struct, which is the cleanest way to inject dependencies (DB handles, HTTP clients, config):
type Activities struct{ DB *sql.DB }
func (a *Activities) Charge(ctx context.Context, in ChargeInput) error { ... }
w.RegisterActivity(&Activities{DB: db}) // registers each method by name
Workflow code has no access to that instance, so reference the method through a nil-receiver method value — the SDK only reads it to derive the Activity name, and dispatches to the registered instance at runtime:
func MyWorkflow(ctx workflow.Context, in ChargeInput) error {
var a *Activities // nil on purpose; never dereferenced
return workflow.ExecuteActivity(ctx, a.Charge, in).Get(ctx, nil)
}
This keeps compile-time checking of the name and signature. A string name
(workflow.ExecuteActivity(ctx, "Charge", in)) also works but loses both.
Calling Activities
ActivityOptions are mandatory — at minimum StartToCloseTimeout or
ScheduleToCloseTimeout. The SDK errors out if neither is set.
ao := workflow.ActivityOptions{
StartToCloseTimeout: 30 * time.Second,
RetryPolicy: &temporal.RetryPolicy{
InitialInterval: time.Second,
BackoffCoefficient: 2.0,
MaximumInterval: time.Minute,
MaximumAttempts: 5,
NonRetryableErrorTypes: []string{"InvalidInput"},
},
}
ctx = workflow.WithActivityOptions(ctx, ao)
var result MyResult
err := workflow.ExecuteActivity(ctx, MyActivity, input).Get(ctx, &result)
ExecuteActivity returns a Future immediately; .Get(ctx, &out) blocks. To
fan out, start everything first, then Get each future (see determinism.md).
Pass the function reference (MyActivity) rather than a string name where
possible — the compiler then catches typos and signature drift.
Local Activities
For very short, low-latency operations on the same process (a quick in-memory
lookup, a fast local computation) workflow.ExecuteLocalActivity skips the task
queue round trip. It has weaker guarantees — no independent Worker routing, and
limited retry across Worker restarts — so use it only for sub-second work.
lao := workflow.LocalActivityOptions{StartToCloseTimeout: time.Second}
err := workflow.ExecuteLocalActivity(workflow.WithLocalActivityOptions(ctx, lao), fn, arg).Get(ctx, &out)
Errors
// Permanent failure: stop retrying immediately.
return temporal.NewNonRetryableApplicationError("card declined", "CardDeclined", nil)
// Retryable failure with a type name (matchable in NonRetryableErrorTypes).
return temporal.NewApplicationError("gateway timeout", "GatewayTimeout")
Inspecting an Activity failure in Workflow code:
var appErr *temporal.ApplicationError
if errors.As(err, &appErr) && appErr.Type() == "CardDeclined" {
// compensate rather than retry
reason := appErr.Message() // just the message; Error() adds type/retryable
}
var timeoutErr *temporal.TimeoutError
if errors.As(err, &timeoutErr) { ... }
Activity errors arrive wrapped in *temporal.ActivityError; always use
errors.As rather than type assertions.
What you get when retries run out
When an Activity exhausts MaximumAttempts (or its ScheduleToCloseTimeout
budget), the Workflow sees the last attempt's error, wrapped:
*WorkflowExecutionError → *ActivityError → *ApplicationError
errors.As unwraps all of it, so the same check matches whether the failure was
permanent on the first try or retryable and exhausted after five. That means
errors.As alone cannot tell you which happened. If the distinction matters —
say, "declined" should refund but "gateway kept timing out" should alert — check
explicitly:
var appErr *temporal.ApplicationError
if errors.As(err, &appErr) {
switch {
case appErr.NonRetryable():
// Permanent: failed fast, no point trying again.
default:
// Retryable, but the budget ran out.
}
}
If the Activity was still running when a timeout struck, you get a
*temporal.TimeoutError instead — with TimeoutType() distinguishing
StartToClose from Heartbeat. Check TimeoutError before falling through to a
generic error branch.
Compensation (the Saga pattern)
Temporal gives you retries for free, but it does not undo completed steps. In a multi-step business transaction — reserve inventory, charge card, ship — a permanent failure at step 3 leaves steps 1 and 2 committed. You have to unwind them yourself.
The idiomatic Go approach is a compensation stack, run in reverse on failure:
func ProcessOrder(ctx workflow.Context, order Order) (err error) {
var compensations []func(workflow.Context)
// Runs on any error return, in reverse order.
defer func() {
if err == nil {
return
}
// Use a disconnected context so compensation still runs even if the
// Workflow is being cancelled.
cctx, cancel := workflow.NewDisconnectedContext(ctx)
defer cancel()
for i := len(compensations) - 1; i >= 0; i-- {
compensations[i](cctx)
}
}()
var reservation Reservation
if err = workflow.ExecuteActivity(ctx, ReserveInventory, order).Get(ctx, &reservation); err != nil {
return err
}
compensations = append(compensations, func(ctx workflow.Context) {
// Log, don't return: a failing compensation must not mask the original
// error, but it does need to be visible.
if e := workflow.ExecuteActivity(ctx, ReleaseInventory, reservation).Get(ctx, nil); e != nil {
workflow.GetLogger(ctx).Error("compensation failed", "step", "ReleaseInventory", "error", e)
}
})
var charge Charge
if err = workflow.ExecuteActivity(ctx, ChargePayment, order).Get(ctx, &charge); err != nil {
return err
}
compensations = append(compensations, func(ctx workflow.Context) {
if e := workflow.ExecuteActivity(ctx, RefundPayment, charge).Get(ctx, nil); e != nil {
workflow.GetLogger(ctx).Error("compensation failed", "step", "RefundPayment", "error", e)
}
})
return workflow.ExecuteActivity(ctx, ShipOrder, order).Get(ctx, nil)
}
Business rejection vs. operational failure
A declined card is a normal business outcome, not a system fault. Failing the Workflow for it means retries, alerts, and an "errored" Execution for something that worked exactly as designed.
Compensate either way, but decide deliberately how the Workflow ends: return a result describing the rejection, or return an error. A useful split:
- Expected business outcome (declined, out of stock, rejected by a rule) → compensate, then complete successfully with a result carrying the outcome.
- Operational failure (gateway unreachable after the retry budget, database down) → compensate, then return the error so it surfaces and pages someone.
var appErr *temporal.ApplicationError
if errors.As(chargeErr, &appErr) && appErr.NonRetryable() {
// Declined: compensate, then report a clean, well-formed outcome.
return &OrderResult{Status: "payment_declined", Reason: appErr.Message()}, nil
}
return nil, chargeErr // infrastructure gave up; let it fail loudly
Model the result type so it can express both — a Status field with explicit
terminal values beats overloading error.
Points that matter:
- Compensating Activities need their own retry policies, and usually more
generous ones than the forward step: a failed refund leaves money in the wrong
place, while a failed charge leaves nothing behind. A reasonable starting
point is
MaximumAttempts: 10with aScheduleToCloseTimeoutof an hour or more, versus ~5 attempts over minutes for the forward path. Tune to how bad the un-compensated state is. - Make them idempotent too, keyed off the original operation's ID.
- Use
workflow.NewDisconnectedContextfor compensation. If the Workflow is failing because it was cancelled,ctxis already cancelled and every compensating Activity would fail immediately. - Not everything can be undone. Some steps need a forward fix (a notification, a manual-review task) rather than a reversal. Decide per step.
- Appending the compensation after the step succeeds is deliberate — never compensate work that never happened.
Heartbeating
Long-running Activities should heartbeat so failures are detected quickly and
retries can resume from progress. Requires HeartbeatTimeout in the options.
for i, item := range items {
activity.RecordHeartbeat(ctx, i) // details are checkpointed
select {
case <-ctx.Done():
return ctx.Err() // honour cancellation
default:
}
process(item)
}
Resuming on a retry:
start := 0
if activity.HasHeartbeatDetails(ctx) {
var completed int
if err := activity.GetHeartbeatDetails(ctx, &completed); err == nil {
start = completed + 1
}
}
Signals, Queries, Updates
Signal — asynchronous, one-way, mutates state, no return value.
// Workflow side
ch := workflow.GetSignalChannel(ctx, "approve")
var in ApproveInput
ch.Receive(ctx, &in) // blocks
// Client side
err := c.SignalWorkflow(ctx, workflowID, runID, "approve", ApproveInput{...})
Prefer SignalWithStartWorkflow when the Workflow may not exist yet — it starts
it and delivers the Signal atomically.
Query — synchronous read-only. Must not mutate state, execute Activities, or block. Not recorded in history.
err := workflow.SetQueryHandler(ctx, "status", func() (string, error) {
return status, nil
})
resp, err := c.QueryWorkflow(ctx, workflowID, runID, "status")
var status string
err = resp.Get(&status)
Update — synchronous, can mutate state and return a value, with an optional validator that rejects bad requests before anything is recorded.
err := workflow.SetUpdateHandlerWithOptions(ctx, "setLimit",
func(ctx workflow.Context, newLimit int) (int, error) {
old := limit
limit = newLimit
return old, nil
},
workflow.UpdateHandlerOptions{
Validator: func(ctx workflow.Context, newLimit int) error {
if newLimit < 0 {
return fmt.Errorf("limit must be non-negative")
}
return nil
},
})
The validator must be side-effect free — it runs on every replay path.
handle, err := c.UpdateWorkflow(ctx, client.UpdateWorkflowOptions{
WorkflowID: workflowID,
UpdateName: "setLimit",
WaitForStage: client.WorkflowUpdateStageCompleted,
Args: []any{500},
})
var previous int
err = handle.Get(ctx, &previous)
Drain handlers before returning. If a Workflow completes while a Signal or Update handler is still in flight, the work is silently lost. Guard the exit:
if err := workflow.Await(ctx, func() bool { return !processing }); err != nil {
return err
}
Waiting on conditions
workflow.Await blocks until a predicate over Workflow state becomes true. The
predicate is re-evaluated after each event, so it must be pure and cheap.
err := workflow.Await(ctx, func() bool { return approvals >= 2 })
ok, err := workflow.AwaitWithTimeout(ctx, time.Hour, func() bool { return done })
Child Workflows
ParentClosePolicy lives in the API module, not the SDK — a common stumble:
import enumspb "go.temporal.io/api/enums/v1"
cwo := workflow.ChildWorkflowOptions{
WorkflowID: "shipment-" + orderID,
TaskQueue: "shipping",
// What happens to the child if the parent completes first.
ParentClosePolicy: enumspb.PARENT_CLOSE_POLICY_TERMINATE,
}
ctx = workflow.WithChildOptions(ctx, cwo)
var out ShipResult
err := workflow.ExecuteChildWorkflow(ctx, ShipWorkflow, in).Get(ctx, &out)
To wait only until the child has started, use .GetChildWorkflowExecution().
Reach for a child Workflow when you need a separate Execution — its own history budget, its own retry/versioning lifecycle, or routing to a different Task Queue. Otherwise prefer an Activity; child Workflows add moving parts.
ContinueAsNew
Event History is capped (51,200 events / 50 MB). Long-lived or looping Workflows must periodically restart with a fresh history, carrying state forward as input:
if workflow.GetInfo(ctx).GetContinueAsNewSuggested() {
return workflow.NewContinueAsNewError(ctx, MyWorkflow, carryForwardState)
}
GetContinueAsNewSuggested() is the SDK's own signal that history is getting
large — prefer it to a hand-rolled iteration counter.
Client
we, err := c.ExecuteWorkflow(ctx, client.StartWorkflowOptions{
ID: "order-" + orderID, // business ID; dedupes retries
TaskQueue: "orders",
// Optional. Workflows do NOT retry by default; usually leave it that way.
WorkflowExecutionTimeout: 24 * time.Hour,
}, MyWorkflow, input)
var result MyResult
err = we.Get(ctx, &result) // blocks until completion
ExecuteWorkflow returns as soon as the Workflow is started. Use a meaningful
business ID: Temporal rejects a duplicate ID while an Execution with that ID is
running, which makes double-submission a no-op instead of a duplicate order.
Version pinning
- Go SDK:
go.temporal.io/sdk v1.47.0 - CLI (dev server):
temporalv1.8.1, bundling Server 1.31.2
Updates and GetContinueAsNewSuggested need reasonably recent SDK and Server
versions; on an older self-hosted Server, check support before relying on them.
Open this reference as its own page
Recurring failure modes
1. Retry policy vs. timeout confusion
These are different knobs and they are constantly mixed up. There are four Activity timeouts:
| Timeout | Bounds | Notes |
|---|---|---|
StartToCloseTimeout |
one attempt | The one you almost always want. Required (or ScheduleToClose). |
ScheduleToCloseTimeout |
all attempts including retries and backoff | The wall-clock budget for the whole operation. |
ScheduleToStartTimeout |
time waiting in the queue before a Worker picks it up | Rarely useful; usually indicates a capacity problem you should fix instead. |
HeartbeatTimeout |
max gap between heartbeats | Only meaningful if the Activity calls RecordHeartbeat. |
The default Retry Policy is:
InitialInterval: 1sBackoffCoefficient: 2.0MaximumInterval: 100 ×InitialInterval(100s)MaximumAttempts: unlimitedNonRetryableErrorTypes: none
Activities retry by default. Workflows do not.
The classic mistakes
Setting only StartToCloseTimeout and expecting the operation to give up.
It bounds a single attempt. With the default unlimited MaximumAttempts, a
permanently-down dependency produces an Activity that retries forever — the
Workflow just hangs, looking "running" but making no progress.
// WRONG — retries forever.
ao := workflow.ActivityOptions{StartToCloseTimeout: 30 * time.Second}
// RIGHT — bound the attempt AND the overall effort.
ao := workflow.ActivityOptions{
StartToCloseTimeout: 30 * time.Second, // one attempt
ScheduleToCloseTimeout: 10 * time.Minute, // total budget
RetryPolicy: &temporal.RetryPolicy{
MaximumAttempts: 5,
},
}
Setting MaximumAttempts: 1 to mean "no retry" — correct, but easy to confuse
with 0, which means unlimited, not "none".
Assuming MaximumAttempts and ScheduleToCloseTimeout are alternatives.
They are independent limits and whichever is reached first stops the retries.
With ScheduleToCloseTimeout: 3s, InitialInterval: 1s, and
MaximumAttempts: 100, you get about 4 attempts, not 100 — the budget expires
long before the attempt count does. Verified against SDK v1.47.0.
Two consequences:
- If you want a guaranteed number of attempts, make sure the budget is large enough to contain them, including exponential backoff.
- When the budget expires between attempts, the Workflow sees the last
attempt's error, not a
TimeoutError. ATimeoutErrorsurfaces only when a timeout interrupts an attempt that was actually running. Don't rely on seeingTimeoutErrorto detect an exhausted retry budget.
Setting StartToCloseTimeout shorter than the work actually takes. Each
attempt is killed mid-flight and retried, so the Activity never completes and
side effects pile up. If duration is unpredictable, heartbeat and set a generous
StartToCloseTimeout with a short HeartbeatTimeout — that detects a dead
Worker fast without capping legitimate long work.
Retrying non-retryable failures. A validation error or a declined card will fail identically on every attempt. Mark them:
return temporal.NewNonRetryableApplicationError("card declined", "CardDeclined", nil)
...or list the type in RetryPolicy.NonRetryableErrorTypes.
Putting a retry policy on the Workflow to compensate for a flaky Activity. Workflow-level retry restarts the entire Workflow from scratch, re-running completed steps. Retry at the Activity level.
2. Versioning a running Workflow after a deploy
This is the failure that bites in production. Workflows started under the old code are still running; when a Worker on the new code replays their history, any change to the sequence of Workflow API calls diverges from what was recorded and the Workflow Task fails.
Safe to change freely: timer durations, Activity options (timeouts, retry policies), Activity input values, logging, and anything inside Activity code.
Requires versioning: adding, removing, or reordering Activity calls, timers,
child Workflows, SideEffects, or Signal sends.
Patching with workflow.GetVersion
Say v1 called ActivityA and you want new Executions to call ActivityB:
// v1 — original
err := workflow.ExecuteActivity(ctx, ActivityA, data).Get(ctx, nil)
// v2 — patched. Old Executions replay the DefaultVersion branch; new ones take v1.
v := workflow.GetVersion(ctx, "UseActivityB", workflow.DefaultVersion, 1)
if v == workflow.DefaultVersion {
err = workflow.ExecuteActivity(ctx, ActivityA, data).Get(ctx, nil)
} else {
err = workflow.ExecuteActivity(ctx, ActivityB, data).Get(ctx, nil)
}
GetVersion records the version in history the first time it runs, and returns
that recorded value on every replay — which is what keeps both branches
deterministic.
Once every pre-patch Execution has finished (past your Namespace retention),
raise minSupported to drop the dead branch:
// v3 — old branch retired.
v := workflow.GetVersion(ctx, "UseActivityB", 1, 1)
err = workflow.ExecuteActivity(ctx, ActivityB, data).Get(ctx, nil)
Keep the GetVersion call itself until no history contains that marker; removing
it early is itself a breaking change.
Rules of thumb:
- The
changeIDmust be unique and stable — never reuse one for a different change. - Don't put
GetVersioninside a loop or conditional whose execution differs between branches. - The safest deploy for a large restructure is often not patching at all: give the new code a new Workflow Type name, route new traffic to it, and let old Executions drain on the old code.
Alternative: Worker Versioning. Instead of branching in code, pin Workers to a Build ID so existing Executions keep running on the code they started with. Better for frequent large changes; more deployment machinery. Temporal now recommends this over patching for many cases — worth checking current docs when choosing.
Always add a replay test (see testing.md) when changing Workflow code.
3. Oversized payloads
Limits:
| Limit | Value |
|---|---|
| Single payload (blob) | 2 MB |
| gRPC message / history transaction | 4 MB |
| Event History | 51,200 events or 50 MB (warnings at 10,240 / 10 MB) |
Every Activity input and output is stored in Event History permanently. Passing a 50 MB file through an Activity return value will blow the limit and fail the Workflow, possibly hours in.
Use the claim-check pattern: put the blob in object storage and pass the key.
// WRONG — the whole document travels through history.
var content []byte
workflow.ExecuteActivity(ctx, DownloadFile, url).Get(ctx, &content)
workflow.ExecuteActivity(ctx, ProcessFile, content).Get(ctx, nil)
// RIGHT — only the reference is recorded.
var s3Key string
workflow.ExecuteActivity(ctx, DownloadToS3, url).Get(ctx, &s3Key)
workflow.ExecuteActivity(ctx, ProcessFromS3, s3Key).Get(ctx, nil)
Watch history growth in general: a loop that runs thousands of Activities will
approach the event cap. Use ContinueAsNew (see go-sdk.md), driven by
GetContinueAsNewSuggested().
4. Blocking calls inside Workflow code
The Workflow scheduler is single-threaded and cooperative. Blocking a Workflow
goroutine on anything other than a Workflow API stalls the whole Workflow Task.
The deadlock detector fires after 1 second of no progress
(worker.Options.DeadlockDetectionTimeout) and fails the task.
// WRONG — all of these block the scheduler.
time.Sleep(time.Second)
resp, _ := http.Get(url)
<-someGoChannel
mu.Lock()
wg.Wait()
Use workflow.Sleep, Activities, workflow.Channel, workflow.Mutex, and
workflow.Await respectively. See determinism.md.
Heavy CPU work also counts: a tight loop over a million items inside a Workflow will trip the detector. Move it to an Activity.
5. Other frequent traps
Non-idempotent Activities. Delivery is at-least-once. An Activity that succeeds but whose completion is lost to a network partition will run again. Pass an idempotency key derived from stable Workflow state:
info := workflow.GetInfo(ctx)
key := fmt.Sprintf("%s-charge", info.WorkflowExecution.ID)
Don't generate the key inside the Activity — it would differ per attempt.
Losing in-flight Signals or Updates at completion. If the Workflow returns
while a handler is still running, that work vanishes. Drain before returning with
workflow.Await.
Mutating state in a Query handler. Queries aren't recorded in history, so mutations there don't survive replay and silently corrupt state. Queries must be read-only.
Reusing a Workflow ID carelessly. Temporal rejects a start while another
Execution with the same ID is running — usually what you want for dedupe. If you
genuinely need reruns, understand WorkflowIDReusePolicy before changing it.
Worker not registered for the Task Queue. A Workflow that stays in "Running" with no events, or an Activity stuck in "Scheduled", almost always means no Worker is polling that queue, or the Workflow/Activity name isn't registered. Check the Task Queue string matches on both sides.
Renaming a Workflow or Activity function. The Type name defaults to the Go
function name, so a rename orphans running Executions. Register explicitly with
RegisterOptions{Name: ...} to decouple the two.
Open this reference as its own page
Testing Temporal Go code
Three layers, each catching a different class of bug:
- Workflow unit tests — logic and orchestration, Activities mocked, time skipped.
- Activity unit tests — the Activity function in isolation.
- Replay tests — current code against a real recorded history, to catch determinism regressions before deploy.
All of it lives in go.temporal.io/sdk/testsuite and needs no running server.
Workflow unit tests
TestWorkflowEnvironment runs the Workflow in-process with a time-skipping
clock: a workflow.Sleep(ctx, 30*24*time.Hour) returns instantly. Tests of
month-long Workflows run in milliseconds.
func TestIngest_ApprovedPath(t *testing.T) {
env := (&testsuite.WorkflowTestSuite{}).NewTestWorkflowEnvironment()
env.OnActivity(ValidateDocument, mock.Anything, mock.Anything).Return(nil)
env.OnActivity(ExtractText, mock.Anything, mock.Anything).
Return(&ExtractResult{Text: "hello world", WordCount: 2}, nil)
env.OnActivity(IndexDocument, mock.Anything, mock.Anything).Return(nil)
env.ExecuteWorkflow(IngestDocumentWorkflow, IngestInput{DocumentID: "doc-1"})
require.True(t, env.IsWorkflowCompleted())
require.NoError(t, env.GetWorkflowError())
var result IngestResult
require.NoError(t, env.GetWorkflowResult(&result))
require.True(t, result.Approved)
env.AssertExpectations(t)
}
ExecuteWorkflow blocks until the Workflow finishes (or the test environment's
own timeout trips). Always assert IsWorkflowCompleted before reading results.
Mocking Activities
The mock's argument list is (context, args...), so the first matcher is always
for the context:
env.OnActivity(ChargeCard, mock.Anything, mock.Anything).Return(nil)
// Match a specific input.
env.OnActivity(ChargeCard, mock.Anything, ChargeInput{Amount: 100}).Return(nil)
// Return an error.
env.OnActivity(ChargeCard, mock.Anything, mock.Anything).
Return(temporal.NewNonRetryableApplicationError("declined", "CardDeclined", nil))
// Dynamic behaviour — the func signature must match the Activity's.
var attempts int
env.OnActivity(ChargeCard, mock.Anything, mock.Anything).
Return(func(ctx context.Context, in ChargeInput) error {
attempts++
if attempts < 3 {
return errors.New("transient")
}
return nil
})
// Constrain call counts.
env.OnActivity(ChargeCard, mock.Anything, mock.Anything).Return(nil).Times(1)
Return(func(...)) is the way to assert retry behaviour: count invocations
and check the Workflow's retry policy actually produced the attempts you expect.
If you register an Activity without mocking it, the real implementation runs:
env.RegisterActivity(ValidateDocument) // real
env.OnActivity(ChargeCard, ...).Return(nil) // mocked
Driving Signals, Queries, and time
Callbacks are scheduled on the skipped clock, so time.Minute here costs no
real time. Use them to deliver a Signal once the Workflow is parked:
env.RegisterDelayedCallback(func() {
env.SignalWorkflow(ApproveSignal, ApproveInput{Approved: true})
}, time.Minute)
Querying mid-run:
env.RegisterDelayedCallback(func() {
res, err := env.QueryWorkflow(StatusQuery)
require.NoError(t, err)
var status string
require.NoError(t, res.Get(&status))
require.Equal(t, "awaiting_approval", status)
}, time.Minute)
Sending an Update:
env.RegisterDelayedCallback(func() {
env.UpdateWorkflow("setLimit", "update-1", &testsuite.TestUpdateCallback{
OnAccept: func() {},
OnReject: func(err error) { t.Fatal(err) },
OnComplete: func(v converter.EncodedValue, err error) { require.NoError(t, err) },
}, 500)
}, time.Minute)
Testing a timeout path is just not sending the Signal — the Workflow's timer wins the race and the test still finishes instantly.
Other useful controls:
env.SetStartTime(time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)) // pin workflow.Now
env.SetTestTimeout(10 * time.Second) // wall-clock guard
env.CancelWorkflow() // exercise cancellation
Activity unit tests
TestActivityEnvironment runs one Activity directly, with a working
activity.GetLogger / RecordHeartbeat context:
func TestExtractText(t *testing.T) {
env := (&testsuite.WorkflowTestSuite{}).NewTestActivityEnvironment()
env.RegisterActivity(ExtractText)
val, err := env.ExecuteActivity(ExtractText, IngestInput{DocumentID: "doc-4"})
require.NoError(t, err)
var res ExtractResult
require.NoError(t, val.Get(&res))
require.Equal(t, 40, res.WordCount)
}
To exercise resume-from-heartbeat logic, seed the details:
env.SetHeartbeatDetails(11) // Activity sees HasHeartbeatDetails == true
Note there is no API to set the attempt number — activity.GetInfo(ctx).Attempt
is always 1 here. If your Activity branches on Attempt, put that behind a
variable or parameter so it stays testable (the starter template does this).
Replay tests
The most important test you can add when changing an existing Workflow. It runs today's code against a history recorded from a real Execution and fails if the command sequence diverges.
Export a history:
temporal workflow show --workflow-id ingest-doc-42 --output json > testdata_history.json
func TestReplayWorkflowHistory(t *testing.T) {
replayer := worker.NewWorkflowReplayer()
replayer.RegisterWorkflow(IngestDocumentWorkflow)
err := replayer.ReplayWorkflowHistoryFromJSONFile(nil, "testdata_history.json")
require.NoError(t, err)
}
Activities are never executed during replay — their results come from the history — so no mocks are required.
Practices that make this pay off:
- Commit histories from representative Executions (happy path, timeout path, cancellation) as fixtures and replay them all in CI.
- When a Workflow fails in production with a non-determinism error, download that Execution's history and replay it locally. You get the exact divergence instead of guessing.
- After intentionally changing Workflow code, a failing replay test means you
need
workflow.GetVersion(seepitfalls.md) — not a refreshed fixture. Only regenerate the fixture once the change is properly patched.
ReplayWorkflowHistory (taking a history object) and ReplayWorkflowExecution
(fetching directly from a live server by Workflow ID) are also available.
Integration tests against a real server
testsuite.StartDevServer boots a real dev server in-process — slower, but
exercises the actual client, Worker, and server together:
srv, err := testsuite.StartDevServer(context.Background(), testsuite.DevServerOptions{
ClientOptions: &client.Options{HostPort: ""}, // "" picks a free port
})
require.NoError(t, err)
defer func() { _ = srv.Stop() }()
c := srv.Client()
w := worker.New(c, "test-queue", worker.Options{})
w.RegisterWorkflow(IngestDocumentWorkflow)
w.RegisterActivity(ExtractText)
require.NoError(t, w.Start())
defer w.Stop()
we, err := c.ExecuteWorkflow(context.Background(),
client.StartWorkflowOptions{ID: "it-1", TaskQueue: "test-queue"},
IngestDocumentWorkflow, IngestInput{DocumentID: "doc-1"})
require.NoError(t, err)
Reserve this for wiring checks — registration names, serialization, Task Queue
mismatches. There is no time skipping here, so keep timers short. Use the
in-process TestWorkflowEnvironment for logic.
More in this playbook
Safe to turn on
Use this skill when an agent or person is about to create, change or enable an automation inside someone else's account or a shared environment: "create this workflow", "build it in the customer's account", "turn it on", "go live", "deploy this automation". Produces a proposal the human approves, an automation created in the off state, and a short list of what only the human can finish.
Workflow buildingMITn8n agents
Design n8n AI agents the right way. Use when building or editing any @n8n/n8n-nodes-langchain.* AI node — an AI Agent, LLM chain, Text Classifier, or Information Extractor — and whenever the user mentions AI agents, LLM with tools, tool calling, $fromAI, system prompts, agent memory, sessionId, structured/JSON output, output parser, RAG, vector store, a chat assistant/bot, or human-in-the-loop review. Covers Agent-vs-chain-vs-classifier choice, the model/memory/tools/outputParser slots, tool names/descriptions as prompt, structured output with autoFix, memory, RAG, human review, and chat topologies.
Workflow buildingMITn8n agents
Design n8n AI agents the right way. Use when building or editing any @n8n/n8n-nodes-langchain.* AI node — an AI Agent, LLM chain, Text Classifier, or Information Extractor — and whenever the user mentions AI agents, LLM with tools, tool calling, $fromAI, system prompts, agent memory, sessionId, structured/JSON output, output parser, RAG, vector store, a chat assistant/bot, or human-in-the-loop review. Covers Agent-vs-chain-vs-classifier choice, the model/memory/tools/outputParser slots, tool names/descriptions as prompt, structured output with autoFix, memory, RAG, human review, and chat topologies.


