Temporal
Temporal is a durable execution platform for orchestrating long-running, fault-tolerant workflows. The @mastra/temporal package lets you author workflows with the standard Mastra API and run them on a Temporal cluster.
How Temporal works with MastraDirect link to How Temporal works with Mastra
Mastra workflows authored with createWorkflow() and createStep() map onto Temporal's workflow and activity model. The MastraPlugin for the Temporal worker compiles your Mastra entry file at bundle time:
- Each
createStep()handler is extracted into a Temporal activity. - Each
createWorkflow()is rewritten into a Temporal workflow that invokes those activities. - The plugin registers the generated activities and workflows with the worker automatically.
When a run starts through mastra.getWorkflow(...).createRun().start(...), the Mastra client hands control to Temporal. Temporal then drives durable execution, retries, and state persistence on the worker.
SetupDirect link to Setup
Install the required packages:
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/temporal@latest @temporalio/client @temporalio/worker @temporalio/envconfig
pnpm add @mastra/temporal@latest @temporalio/client @temporalio/worker @temporalio/envconfig
yarn add @mastra/temporal@latest @temporalio/client @temporalio/worker @temporalio/envconfig
bun add @mastra/temporal@latest @temporalio/client @temporalio/worker @temporalio/envconfig
You also need access to a Temporal cluster. For local development, use the Temporal CLI development server.
Building a Temporal-backed workflowDirect link to Building a Temporal-backed workflow
This guide walks through creating a workflow with Temporal and Mastra, demonstrating a counter application that increments a value.
Temporal initializationDirect link to Temporal initialization
Initialize the Temporal integration to obtain Mastra-compatible workflow helpers. The createWorkflow() and createStep() functions are bound to a Temporal client and a task queue.
import { init } from '@mastra/temporal'
import { Client, Connection } from '@temporalio/client'
import { loadClientConnectConfig } from '@temporalio/envconfig'
const config = loadClientConnectConfig()
const connection = await Connection.connect(config.connectionOptions)
const client = new Client({ connection })
export const { createWorkflow, createStep } = init({
client,
taskQueue: 'mastra',
})
loadClientConnectConfig() reads standard Temporal environment variables such as TEMPORAL_ADDRESS, TEMPORAL_NAMESPACE, and mTLS settings. See the Temporal envconfig docs for the full list.
Configure activity retriesDirect link to Configure activity retries
Pass retry to init() to set a Temporal activity retry policy for workflows created by these helpers. For example, add the following options to the initialization above to limit a failing activity to five total attempts:
export const { createWorkflow, createStep } = init({
client,
taskQueue: 'mastra',
startToCloseTimeout: '5 minutes',
retry: {
initialInterval: '5 seconds',
backoffCoefficient: 2,
maximumInterval: '5 minutes',
maximumAttempts: 5,
nonRetryableErrorTypes: ['ValidationError'],
},
})
The policy applies to all generated activities, including steps, mappings, and conditions. Set maximumAttempts: 1 to disable retries. Omitting retry preserves Temporal's default policy, which allows unlimited attempts. Mastra's workflow retryConfig doesn't configure Temporal activity retries.
Keep retry options in the statically analyzable init() configuration so the worker build can include them. Inline object literal spreads are supported. Spreads of variables or function results are skipped during activity option extraction, so retry and startToCloseTimeout inside those spreads aren't forwarded to the generated workflow. Provide these options directly in init() or in an inline object literal spread instead. Rebuild and restart the worker after changing the policy.
Creating stepsDirect link to Creating steps
Define the individual steps that will compose your workflow. Each step becomes a Temporal activity.
import { z } from 'zod'
import { createWorkflow, createStep } from '../temporal'
const incrementStep = createStep({
id: 'increment',
inputSchema: z.object({
value: z.number(),
}),
outputSchema: z.object({
value: z.number(),
}),
execute: async ({ inputData }) => {
return { value: inputData.value + 1 }
},
})
Creating the workflowDirect link to Creating the workflow
Compose the steps into a workflow. The workflow id must be a static string literal so the build-time transformer can derive its Temporal export name.
const workflow = createWorkflow({
id: 'increment-workflow',
steps: [incrementStep],
inputSchema: z.object({
value: z.number(),
}),
outputSchema: z.object({
value: z.number(),
}),
}).then(incrementStep)
workflow.commit()
export { workflow as incrementWorkflow }
Configuring the Mastra instanceDirect link to Configuring the Mastra instance
Register the workflow with Mastra. The execution is driven by the Temporal worker.
import { Mastra } from '@mastra/core'
import { PinoLogger } from '@mastra/loggers'
import { incrementWorkflow } from './workflows'
export const mastra = new Mastra({
workflows: { incrementWorkflow },
logger: new PinoLogger({ name: 'Mastra', level: 'info' }),
})
Running the workerDirect link to Running the worker
The worker is a long-lived Node.js process that polls a Temporal task queue. Install MastraPlugin and pass it the path to the Mastra entry file that registers your workflows.
import { MastraPlugin } from '@mastra/temporal/worker'
import { NativeConnection, Worker } from '@temporalio/worker'
const connection = await NativeConnection.connect({
address: 'localhost:7233',
})
const mastraPlugin = new MastraPlugin(import.meta.resolve('./index.ts'))
const worker = await Worker.create({
connection,
namespace: 'default',
taskQueue: 'mastra',
plugins: [mastraPlugin],
})
await worker.run()
MastraPlugin rewrites the entry file into a workflow-only bundle and wires step handlers in as Temporal activities. You don't need to pass activities or workflowsPath to Worker.create() manually.
Running workflowsDirect link to Running workflows
Running locallyDirect link to Running locally
-
Install the Temporal CLI, then start the local server:
temporal server start-dev --db-filename temporal.db -
Open the Temporal UI at http://localhost:8233 to inspect namespaces, workflows, and activities.
-
In a new terminal, start the worker by running:
npx tsx src/mastra/worker.ts -
Trigger a workflow run from a script or any process that imports your Mastra instance:
scripts/run.tsimport { mastra } from '../src/mastra'const run = await mastra.getWorkflow('incrementWorkflow').createRun()const result = await run.start({ inputData: { value: 5 } })console.log(result) -
Monitor execution in the Temporal UI under Workflows to see step-by-step activity progress and retry history.
Running in productionDirect link to Running in production
For production, use Temporal Cloud or a self-hosted Temporal cluster. Configure the client and worker connections through environment variables read by @temporalio/envconfig:
TEMPORAL_ADDRESS=your-namespace.tmprl.cloud:7233
TEMPORAL_NAMESPACE=your-namespace
TEMPORAL_API_KEY=your-api-key
See the Temporal Cloud connection docs for mTLS and API key options.
The Temporal worker must run as a long-lived process. Don't deploy it to serverless platforms with short execution limits, such as AWS Lambda or Vercel functions. Use a container, VM, or worker-friendly platform such as Fly.io, Railway, or Kubernetes.
Configuration optionsDirect link to Configuration options
taskQueueDirect link to taskqueue
Required. Identifies the Temporal task queue your worker polls. The same value must be passed to init() (used by the client to start runs) and to Worker.create() (used by the worker to receive them).
startToCloseTimeoutDirect link to starttoclosetimeout
Optional. Sets the maximum time a single activity (step) is allowed to run before Temporal cancels it and applies the retry policy. Defaults to 1 minute.
export const { createWorkflow, createStep } = init({
client,
taskQueue: 'mastra',
startToCloseTimeout: '5 minutes',
})
CompatibilityDirect link to Compatibility
@mastra/temporal is experimental. It supports a subset of the Mastra workflow API, and anything it can't compile fails when the worker builds, not at run time.
Run APIsDirect link to Run APIs
| Method | Temporal support |
|---|---|
start(), startAsync() | Starts a Temporal workflow execution |
resume(), resumeAsync() | Signals the Temporal execution to resume a suspended step. Pass step, or omit it when only one step is suspended. Resuming by label isn't supported |
cancel() | Cancels the Temporal execution |
stream(), streamLegacy(), resumeStream() | Throws. Use start() or startAsync() instead |
restart(), timeTravel(), timeTravelStream() | Throws. Time travel is tracked in #24025 |
observeStream(), watch() | Not connected to Temporal. Runs emit no Mastra events |
Run state, step results, and events stay in Temporal and aren't written to Mastra storage, so Temporal runs don't appear in Studio's run history. Studio's workflow runner calls stream(), which throws for Temporal workflows. Use the Temporal UI to inspect runs. Projecting Temporal runs into Mastra APIs and Studio is tracked in #24016.
Workflow methodsDirect link to Workflow methods
The worker build reads each workflow chain statically, so arguments must be resolvable at build time. A step can be an identifier or an inline createStep() call whose id is a string literal. Conditions for .branch(), .dowhile(), and .dountil() must be identifiers.
| Method | Supported arguments |
|---|---|
.then() | A step or workflow |
.parallel() | An array literal of steps or workflows |
.branch() | An array literal of [condition, step] pairs |
.dowhile(), .dountil() | A step and a condition |
.foreach() | A step and an optional options object |
.sleep() | A numeric literal or a function identifier |
.sleepUntil() | A new Date(...) expression, a string or number literal, or a function identifier |
.map() | An inline function or a top-level function identifier. Declarative object mappings aren't supported |
.commit() | No arguments |
| Any other method | Not supported |
Condition functions and .sleep() or .sleepUntil() function identifiers are called as activities named after the identifier, but the plugin only generates activities for steps and .map() callbacks. Register these functions yourself in Worker.create({ activities }), or the run fails when it reaches them. These functions receive inputData, runId, workflowId, resourceId, and requestContext as a plain object. They don't receive getInitData().
Nested workflows passed to .then() or .parallel() run as Temporal child workflows. Each one is registered as its own workflow type and shows up as a separate execution in the Temporal UI. A suspended step inside a child workflow can't be resumed through the parent run.
An unsupported construct stops the worker build with an error that names the workflow and file:
// Build error: .map() does not yet support declarative object mappings; use a callback mapping
workflow.map({ city: { step: fetchWeather, path: 'city' } })
Step execution contextDirect link to Step execution context
Each step runs as a Temporal activity. Its execute function receives:
inputDataand, when resuming,resumeDatarunId,workflowId, andresourceIdrequestContextgetInitData()suspend(), except in.foreach()stepsmastra, when the step's module can import the Mastra instance
Other execute parameters, such as state, setState(), getStepResult(), bail(), abort(), writer, and tracingContext, aren't available. Steps in a nested workflow receive the parent's runId, resourceId, and request context, and the nested workflow's own workflowId.
Bundling and worker operationDirect link to Bundling and worker operation
On startup, MastraPlugin bundles your Mastra entry file and writes the generated code to node_modules/.mastra/:
workflow.mjs: the workflow bundle, which runs in Temporal's deterministic workflow sandboxactivities.mjs: the step and mapping code, which runs as regular Node.js activitiesactivity-bindings.json: the map from step ids to activity exports
Keep I/O, clients, agents, tools, storage, and MCP connections inside step execute functions. The workflow bundle can't import Node.js builtins such as node:fs. When it does, the build fails with Temporal workflow bundle cannot depend on Node.js builtin, and you need to move that dependency into a step. Check the generated files in node_modules/.mastra/ when a build or activity lookup fails.
A run started while no worker polls the task queue stays queued without an error. Before you send traffic, confirm that a worker is polling:
temporal task-queue describe --task-queue mastra
Constraints and notesDirect link to Constraints and notes
- Workflow ids must be static string literals. The build-time transformer reads the literal value to derive Temporal workflow export names.
- Activities are generated automatically from
createStep()handlers. Don't pass them inWorker.create({ activities }). - Each step checks its input against
inputSchemaand its request context againstrequestContextSchemabefore it runs. A mismatch fails the step without retries. Only the steps inside a nested workflow are checked, not its owninputSchema. - Set
validateInputstofalseincreateWorkflow()to skip these checks. This also skips the workflow input checks inrun.start(). - The build-time transformer reads
validateInputsfrom thecreateWorkflow()call. When it can't, for example withoptions: sharedOptions, it prints a warning. Runs started withrun.start()orrun.startAsync()still use the workflow's setting, and runs started another way, such as from a Temporal Schedule, check step input. - Step input and request context pass through Temporal's data converter, which turns a
Dateinto a string. Usez.coerce.date()instead ofz.date()in a step'sinputSchemaandrequestContextSchema. - Lifecycle callbacks (
onStart,onFinish,onError) run in the process that callsrun.start()orrun.startAsync(), not in the worker. Afterrun.startAsync(), that process must keep running until the workflow finishes foronFinishandonErrorto run. Runs started another way, such as from a Temporal Schedule, don't run them. - After a
.parallel()that contains a nested workflow, the next step receives the nested workflow's output under its Temporal workflow type, for exampleinnerWorkflowfor idinner. The default workflow engine uses the id instead.