跳到主要内容
非官方简体中文翻译,内容版权归 Mastra 所有,遵循 Apache-2.0 许可。

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 Mastra
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.

Setup
Setup的直接链接

Install the required packages:

npm install @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 workflow
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 initialization
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.

src/mastra/temporal/index.ts
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 retries
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 steps
Creating steps的直接链接

Define the individual steps that will compose your workflow. Each step becomes a Temporal activity.

src/mastra/workflows/index.ts
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 workflow
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.

src/mastra/workflows/index.ts
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 instance
Configuring the Mastra instance的直接链接

Register the workflow with Mastra. The execution is driven by the Temporal worker.

src/mastra/index.ts
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 worker
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.

src/mastra/worker.ts
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 workflows
Running workflows的直接链接

Running locally
Running locally的直接链接

  1. Install the Temporal CLI, then start the local server:

    temporal server start-dev --db-filename temporal.db
  2. Open the Temporal UI at http://localhost:8233 to inspect namespaces, workflows, and activities.

  3. In a new terminal, start the worker by running:

    npx tsx src/mastra/worker.ts
  4. Trigger a workflow run from a script or any process that imports your Mastra instance:

    scripts/run.ts
    import { mastra } from '../src/mastra'

    const run = await mastra.getWorkflow('incrementWorkflow').createRun()
    const result = await run.start({ inputData: { value: 5 } })

    console.log(result)
  5. Monitor execution in the Temporal UI under Workflows to see step-by-step activity progress and retry history.

Running in production
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:

.env
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 options
Configuration options的直接链接

taskQueue
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).

startToCloseTimeout
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.

src/mastra/temporal/index.ts
export const { createWorkflow, createStep } = init({
client,
taskQueue: 'mastra',
startToCloseTimeout: '5 minutes',
})

Constraints and notes
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 in Worker.create({ activities }).