Temporal Workflow Versioning and Deterministic Replay at Scale
Quick Summary (TL;DR) Temporal workflows are stateful programs whose history is replayed on every worker task — so any code change that alters the command sequence breaks in-flight executions with a
NonDeterministicError. To evolve safely: (1) treat the determinism contract as a hard rule, (2) choose a versioning strategy — patching (GetVersion), build-ID worker versioning, or new workflow types — based on your change and cluster, (3) replay-test real histories in CI before every deploy, and (4) keep patches alive until every open execution that could have taken the old branch has closed. This guide walks through each step with concrete code, a comparison table, and operational guardrails for self-hosted clusters.
Self-hosted Temporal gives you enormous durability: a workflow can run for months, survive worker crashes, and resume exactly where it left off. That same durability is what makes code changes dangerous. Unlike a stateless service where a rolling deploy simply replaces old pods, a Temporal worker must be able to re-execute old workflow code paths to reconstruct state. If your new code produces a different sequence of commands than the history recorded, Temporal refuses to continue.
This guide is a production-oriented playbook for evolving long-running workflows on a self-hosted cluster without breaking in-flight executions.
Why Workflow Code Is Different From Ordinary Code
In a normal service, deploying new code affects only future requests. In Temporal, deploying new code affects existing workflows too, because the worker replays their event history to rebuild in-memory state after every task, cache eviction, or worker restart.
A workflow execution is essentially an append-only event log: WorkflowExecutionStarted, ActivityTaskScheduled, ActivityTaskCompleted, TimerStarted, and so on. When a worker picks up a workflow task, it does not restore a snapshot — it re-runs your workflow function from the beginning, feeding it the recorded results of activities, timers, and signals instead of actually executing them. The commands your code emits must match the history exactly.
flowchart TD
A[Worker receives Workflow Task] --> B[Load full event history]
B --> C[Re-execute workflow code from start]
C --> D{Commands emitted match history?}
D -- Yes --> E[Apply new commands, advance workflow]
D -- No --> F[NonDeterministicError: workflow task fails]
F --> G[Workflow stuck until code is fixed or reverted]
The Determinism Contract: What Replay Actually Re-executes
Replay re-executes workflow code only. Activities, child workflow executions, and side effects are not re-run — their recorded results are replayed from history. That distinction is the key to understanding what you can and cannot change.
The Non-Deterministic Error in Practice
Suppose your workflow originally scheduled chargeCard then sendReceipt. A developer “cleans up” the code and swaps the order. On the next task, replay emits sendReceipt first, but the history expects chargeCard. Temporal raises:
NonDeterministicError: Workflow activation completion failed:
Nondeterminism error: Activity type mismatch, expected chargeCard, got sendReceipt
The workflow task fails and retries indefinitely until you either revert the code or patch it. This is a hard stop, not a warning — which is good (no silent corruption) but painful if it hits at 3 a.m.
Determinism Rules Checklist
Keep this list in your PR template:
- ✅ Use
workflow.Now(), nottime.Now(); useworkflow.SideEffect/workflow.NewRandomfor randomness. - ✅ Iterate over sorted map keys — Go map iteration order is randomized per run.
- ✅ Never call external APIs, read env vars, or touch the filesystem directly in workflow code.
- ✅ Keep the order and count of activities, timers, signals, and child workflows stable.
- ✅ Pin your SDK version and review release notes for command-emission changes.
- ✅ Route all non-deterministic work through activities or side effects.
Versioning Strategies Compared
There are three practical ways to evolve workflow code. Most mature teams use a blend.
Strategy 1: Patching (GetVersion)
Patching lets old and new code paths coexist inside one workflow function. GetVersion records the chosen version into history the first time it runs, so every replay of that execution takes the same branch forever.
v := workflow.GetVersion(ctx, "add-fraud-check", workflow.DefaultVersion, 1)
if v == workflow.DefaultVersion {
// old path: no fraud check
err = workflow.ExecuteActivity(ctx, ChargeCard, in).Get(ctx, nil)
} else {
// new path: fraud check first
err = workflow.ExecuteActivity(ctx, FraudCheck, in).Get(ctx, nil)
if err == nil {
err = workflow.ExecuteActivity(ctx, ChargeCard, in).Get(ctx, nil)
}
}
Old executions replay with DefaultVersion; new executions record version 1. This is the most surgical, portable option.
Strategy 2: Worker Versioning (Build-ID Based)
Worker versioning moves the decision from code to infrastructure. Each worker build gets a build ID; the server routes workflow tasks to a compatible build so old executions stay on old code and new executions start on new code. You configure it per task queue and promote builds through stages (e.g., a “ramping” build that receives a percentage of new executions). It requires a self-hosted server and SDK version that support the feature — verify before adopting.
Strategy 3: Workflow Type Versioning (New Names)
The blunt instrument: register OrderWorkflowV2 as a new type and start new executions on it, leaving OrderWorkflow untouched until its executions drain. Simple and safe, but you must update all callers and child-workflow references, and you carry two types until the old one is fully drained.
Comparison Table
| Criterion | Patching (GetVersion) | Worker Versioning | New Workflow Type |
|---|---|---|---|
| Granularity | Per-change, in code | Per-build, infrastructure | Per-workflow |
| Portability | Any server/SDK | Requires supported server + SDK | Any server/SDK |
| Cleanup effort | Manual DeprecatePatch + removal | Retire old build IDs | Delete old type after drain |
| Handles long-lived executions | Yes, explicitly | Yes, via routing | Yes, via drain |
| Best for | Surgical changes, mixed paths | Deployment safety, fast iteration | Major redesigns |
| Risk if misused | Forgotten patches accumulate | Misconfigured routing strands tasks | Type sprawl, caller churn |
Step-by-Step: Evolving a Live Workflow With Patching
Let’s walk through adding a fraud check to a live OrderWorkflow.
Step 1: Identify the Change Point
Pinpoint the exact line where the command sequence diverges. Anything before it replays identically; anything after is where the patch boundary belongs.
Step 2: Introduce the Patch
v := workflow.GetVersion(ctx, "fraud-check-v1", workflow.DefaultVersion, 1)
if v >= 1 {
if err := workflow.ExecuteActivity(ctx, FraudCheck, in).Get(ctx, nil); err != nil {
return err
}
}
Commit this with a clear changelog note naming the patch ID.
Step 3: Deploy Workers With the Patch
Roll out workers normally (see deployment section). After deploy, new executions record version 1; existing executions replay with DefaultVersion and continue on the old path.
Step 4: Deprecate the Old Branch
Once no open execution can still be on DefaultVersion, call workflow.DeprecatePatch(ctx, "fraud-check-v1"). This marks the version as deprecated in history so you know it’s safe to remove.
Step 5: Remove the Patch
Delete the if block and the GetVersion call entirely. Because history now records the deprecated marker, replay remains deterministic.
sequenceDiagram
participant Dev
participant CI
participant Server
participant Worker
Dev->>CI: push patched code
CI->>CI: replay fixtures pass
CI->>Server: deploy workers (build v2)
Server->>Worker: old executions replay on DefaultVersion
Server->>Worker: new executions record version 1
Dev->>Server: watch open executions drain
Dev->>CI: DeprecatePatch, then remove branch
Replay Testing Before Every Deploy
The single highest-value guardrail is replaying real captured histories against every build in CI.
Replay From a Local History File
Export a representative history from your cluster with the Temporal CLI:
temporal workflow show \
--namespace production \
--workflow-id order-12345 \
--output json > fixtures/order-12345.json
Then replay it in a test:
func TestReplayFixtures(t *testing.T) {
replayer := worker.NewWorkflowReplayer()
replayer.RegisterWorkflow(OrderWorkflow)
if err := replayer.ReplayWorkflowHistoryFromJSONFile(
nil, "fixtures/order-12345.json"); err != nil {
t.Fatalf("non-determinism detected: %v", err)
}
}
Automated Replay in CI
Store fixtures for every branch of every active patch, and fail the pipeline on any replay error:
# .github/workflows/replay.yml (excerpt)
- name: Replay determinism tests
run: go test ./workflows/... -run TestReplayFixtures -count=1
Rotate fixtures periodically so they reflect current production shapes, and always include at least one history per active patch branch.
Worker Deployment Strategies for Self-Hosted Clusters
Rolling Deploys With Build-ID Routing
Tag each build with a unique build ID and let the server route tasks. New executions start on the promoted build; old executions stay pinned to their compatible build until they close. Promote gradually — route a small percentage of new executions to the new build, watch error rates and replay failures, then ramp to 100%.
Task Queue Isolation
For risky changes, run a separate task queue (e.g., orders-v2) and migrate new executions to it via a routing workflow or feature flag. This isolates blast radius: a bad build only affects the new queue. Combine with build-ID routing for version-aware routing inside each queue.
Operational Guardrails at Scale
- Track open executions per workflow type — dashboards on
temporal_workflow_countby type tell you when a patch is safe to remove. - Patch registry — keep a table of patch IDs, owners, introduction dates, and removal criteria.
- Alert on
NonDeterministicError— a spike means a bad deploy is live; page immediately. - Version-pin SDKs and review release notes for command changes.
- Canary namespaces — replay production histories in a staging namespace before promoting.
Frequently Asked Questions
What causes a non-deterministic error in Temporal?
A non-deterministic error occurs when a worker replays a workflow history and the code produces a different sequence of commands than the history recorded. Common causes include changing the order of activities, adding or removing timers, using random numbers or wall-clock time directly in workflow code, iterating over unordered maps, or upgrading SDK versions that alter command emission. Temporal detects the mismatch and fails the workflow task with a NonDeterministicError.
Should I use patching or worker versioning? Use worker versioning when your self-hosted cluster and SDK support it and you want infrastructure-level control over which build executes which workflows. Use patching when you need fine-grained, in-code branching for a specific change, when you cannot yet adopt versioning, or when multiple concurrent code paths must coexist. Many teams combine both: versioning for deployment safety and patches for surgical changes.
How long must I keep a patch in the code?
Keep a patch until every workflow execution that could have taken the old branch has closed. For long-running workflows this can be months. Track open executions per workflow type, and only call DeprecatePatch and later remove the branch once no open history contains the pre-patch path. Removing a patch too early reintroduces non-determinism for in-flight executions.
Can I change activity implementations without versioning the workflow? Yes. Activity implementations are not replayed, so you can change their internals freely as long as the activity type name, input and output shapes, and retry semantics remain compatible. If you change the activity signature or split one activity into two, that changes the workflow command sequence and requires a patch or a new workflow version.
How do I test replay for workflows that have been running for months? Download representative histories from your self-hosted cluster using the Temporal CLI or the visibility API, store them as fixtures in your repository, and run the replay test utility in CI against every build. Include histories that exercise each branch of your patches. This catches non-determinism before deployment rather than after a worker restart.
Does worker versioning require Temporal Cloud? No. Worker versioning is available on self-hosted Temporal Server versions that support it, but you must verify your server and SDK versions. Enable it per task queue and configure build-ID-based routing in your worker deployment. If your server version predates the feature, patching remains the portable approach.