← Files TemporalARCHIVED FILE
skills/temporal-developer/references/typescript/versioning.md
10.9 KB · Nov 28, 2026 · 18:13 UTC
# TypeScript SDK Versioning
For conceptual overview and guidance on choosing an approach, see [Temporal versioning guide](../core/versioning.md).
## Patching API
The Patching API lets you change Workflow Definitions without causing non-deterministic behavior in running Workflows.
### The patched() Function
The `patched()` function takes a `patchId` string and returns a boolean:
```typescript
import { patched } from '@temporalio/workflow';
export async function myWorkflow(): Promise<void> {
if (patched('my-change-id')) {
// New code path
await newImplementation();
} else {
// Old code path (for replay of existing executions)
await oldImplementation();
}
}
```
**How it works:**
- On the first live call for a new patch ID, `patched()` defaults to `true` and records a marker in Event History
- During replay, if the history contains a marker with the same `patchId`, `patched()` returns `true`
- During replay, if no matching marker exists, `patched()` returns `false`
The SDK memoizes the live activation decision for a patch ID. A replay call without a marker can still reach a live activation later.
### Gate a new patch during rollout
The experimental `WorkerOptions.patchActivationCallback` runs on the Worker for the first live encounter with a non-deprecated patch ID. Returning `false` makes `patched()` return `false` without recording a marker. Returning `true` activates the new branch and records the marker. Replay follows history, and a recorded patch bypasses this callback.
```typescript
const worker = await Worker.create({
taskQueue: 'orders',
workflowsPath: require.resolve('./workflows'),
patchActivationCallback: ({ patchId }) =>
patchId !== 'my-change-id' || enableNewOrderPath,
});
```
Read `enableNewOrderPath` from Worker configuration. Keep the `patched('my-change-id')` guard and both branches during rollout. The callback must return a boolean synchronously. Keep it fast because it blocks the Worker main thread.
### Three-Step Patching Process
Patching is a three-step process for safely deploying changes.
**Warning:** Failing to follow this process correctly will result in non-determinism errors for in-flight workflows.
#### Step 1: Patch in New Code
Add the patch alongside the old code:
```typescript
import { patched } from '@temporalio/workflow';
// Original code sent fax notifications
export async function shippingConfirmation(): Promise<void> {
if (patched('changedNotificationType')) {
await sendEmail(); // New code
} else {
await sendFax(); // Old code for replay
}
await sleep('1 day');
}
```
#### Step 2: Deprecate the Patch
Once all Workflows using the old code have completed, deprecate the patch:
```typescript
import { deprecatePatch } from '@temporalio/workflow';
export async function shippingConfirmation(): Promise<void> {
deprecatePatch('changedNotificationType');
await sendEmail();
await sleep('1 day');
}
```
The `deprecatePatch()` function records a marker that does not fail replay when Workflow code does not emit it, allowing a transition period.
#### Step 3: Remove the Patch
After all Workflows using `deprecatePatch` have completed, remove it entirely:
```typescript
export async function shippingConfirmation(): Promise<void> {
await sendEmail();
await sleep('1 day');
}
```
### Query Filters for Versioned Workflows
Use List Filters to find Workflows by version:
```
# Find running Workflows with a specific patch
WorkflowType = "shippingConfirmation" AND ExecutionStatus = "Running" AND TemporalChangeVersion = "changedNotificationType"
# Find running Workflows without the patch (started before patching)
WorkflowType = "shippingConfirmation" AND ExecutionStatus = "Running" AND TemporalChangeVersion IS NULL
```
## Workflow Type Versioning
An alternative to patching is creating new Workflow functions for incompatible changes:
```typescript
// Original Workflow
export async function pizzaWorkflow(order: PizzaOrder): Promise<OrderConfirmation> {
// Original implementation
}
// New version with incompatible changes
export async function pizzaWorkflowV2(order: PizzaOrder): Promise<OrderConfirmation> {
// Updated implementation
}
```
Register both Workflows with the Worker:
```typescript
const worker = await Worker.create({
workflowsPath: require.resolve('./workflows'), // Use workflowBundle for production
taskQueue: 'pizza-queue',
});
```
Update client code to start new Workflows with the new type:
```typescript
// Start new executions with V2
await client.workflow.start(pizzaWorkflowV2, {
workflowId: 'order-123',
taskQueue: 'pizza-queue',
args: [order],
});
```
Use List Filters to check for remaining V1 executions:
```
WorkflowType = "pizzaWorkflow" AND ExecutionStatus = "Running"
```
After all V1 executions complete, remove the old Workflow function.
## Worker Versioning
Worker Versioning is GA and allows multiple Worker versions to run simultaneously. Pinned Workflows stay on their original Worker Deployment Version; Auto-Upgrade Workflows can move at Workflow Task boundaries and require replay-compatible code.
### Key Concepts
- **Worker Deployment**: A logical name for your application (e.g., "order-service")
- **Worker Deployment Version**: A specific build identified by deployment name + Build ID
- **Workflow Pinning**: Workflows complete on the Worker Deployment Version they started on
### Configuring Workers for Versioning
```typescript
import { Worker, NativeConnection } from '@temporalio/worker';
const worker = await Worker.create({
workflowsPath: require.resolve('./workflows'), // Use workflowBundle for production
taskQueue: 'my-queue',
connection: await NativeConnection.connect({ address: 'temporal:7233' }),
workerDeploymentOptions: {
useWorkerVersioning: true,
version: {
deploymentName: 'order-service',
buildId: '1.0.0', // Git hash, semver, build number, etc.
},
defaultVersioningBehavior: 'PINNED', // or 'AUTO_UPGRADE'
},
});
```
**Configuration options:**
- `useWorkerVersioning`: Enables Worker Versioning
- `version.deploymentName`: Logical name for your service (consistent across versions)
- `version.buildId`: Unique identifier for this build
- `defaultVersioningBehavior`: `'PINNED'` or `'AUTO_UPGRADE'`, used for Workflows that don't declare their own. **Required** when `useWorkerVersioning` is `true` (TypeScript type error otherwise, and `Worker.create` throws `Unknown versioning behavior: undefined` at runtime)
### Per-Workflow Versioning Behavior
Override the Worker default for an individual Workflow with `setWorkflowOptions`:
```typescript
import { setWorkflowOptions } from '@temporalio/workflow';
setWorkflowOptions({ versioningBehavior: 'AUTO_UPGRADE' }, longRunningWorkflow);
export async function longRunningWorkflow(): Promise<void> {
// ...
}
```
**PINNED**: The Workflow stays on the Worker Deployment Version it started on. **AUTO_UPGRADE**: The Workflow moves to its Target Version (the Current Version, or the Ramping Version if it's routed to the ramp) on its next Workflow Task, so it still needs patching to handle version transitions safely.
### Deployment Workflow
1. Deploy new Worker version with a new `buildId`
2. Use the Temporal CLI to set the new version as current:
```bash
temporal worker deployment set-current-version \
--deployment-name order-service \
--build-id 2.0.0
```
3. New Workflows start on the new version
4. Pinned Workflows continue on their original version; Auto-Upgrade Workflows move to the Target Version
5. Decommission old Workers once all their Workflows complete
### When to Use Worker Versioning
Prefer Worker Versioning for production deployments when you can run versioned Workers. Choose `PINNED` for runs that finish within a deployment's lifetime, or for long-running Workflows that upgrade at Continue-as-New boundaries. For long-running Workflows without Continue-as-New, use `AUTO_UPGRADE` with patching. Blue-green deployments default to Auto-Upgrade; Pinning fits rainbow deployments. See the [core guide](../core/versioning.md) for rollout and recovery tooling.
## Upgrading on Continue-as-New
> [!NOTE]
> This feature is in Public Preview. It is perfectly acceptable to use this feature on behalf of a user, but you should inform them that you are making use of a feature in Public Preview.
For long-running Pinned Workflows that use Continue-as-New, detect a new Target Worker Deployment Version on `workflowInfo()` and continue-as-new with `InitialVersioningBehavior.AUTO_UPGRADE` so the new run starts on the Target Version. See [Temporal versioning guide](../core/versioning.md) for the conceptual model.
### Detecting the Target Version change
`workflowInfo().targetWorkerDeploymentVersionChanged` is `true` when a new Current or Ramping Version is available for this Workflow's Worker Deployment. The flag is refreshed after each Workflow Task completes.
Check the flag from code that runs as part of a Workflow Task — for example, before accepting an Update, starting an Activity, or starting a child Workflow.
### Continue-as-new with upgrade
When the flag is set, build the Continue-as-New function with `makeContinueAsNewFunc`, passing `initialVersioningBehavior: InitialVersioningBehavior.AUTO_UPGRADE`, so the new run starts on the Target Version of its Worker Deployment.
```ts
import * as wf from '@temporalio/workflow';
import { InitialVersioningBehavior } from '@temporalio/common';
// At a natural Workflow Task boundary, e.g. before accepting Updates,
// starting Activities, starting child Workflows, etc.:
if (wf.workflowInfo().targetWorkerDeploymentVersionChanged) {
const continueAsNew = wf.makeContinueAsNewFunc<typeof myWorkflow>({
initialVersioningBehavior: InitialVersioningBehavior.AUTO_UPGRADE,
});
await continueAsNew(nextInput);
}
```
> [!IMPORTANT]
> Don't busy-poll the flag on a timer. Check it at a natural Workflow Task boundary — before accepting Updates, starting Activities, starting child Workflows, etc. For idle Workflows, send a Signal to wake them so they can check it (see Limitations).
### Limitations
- **Lazy moving only — idle Workflows do not upgrade.** Send a Signal to wake an idle Workflow so it can check `targetWorkerDeploymentVersionChanged`.
- **Workflow input must remain compatible across versions.** The new version's Workflow definition must accept the previous version's input; otherwise the new run may fail on its first Workflow Task.
- **Pinned Workflow Types only.** Auto-Upgrade Workflows move at Workflow Task boundaries already; the upgrade-on-CaN pattern adds nothing for them.
## Best Practices
1. Use descriptive `patchId` names that explain the change
2. Follow the three-step patching process completely before removing patches
3. Use List Filters to verify no running Workflows before removing version support
4. Keep Worker Deployment names consistent across all versions
5. Use unique, traceable Build IDs (git hashes, semver, timestamps)
6. Test version transitions with replay tests before deploying
SHA-256: 518faa186b3839d25ec2d38891b9238df43af9f3491e83e1072d9d07c54679cf