Serverless Workers on AWS Lambda
The @temporalio/lambda-worker package lets you run a Temporal Serverless Worker on AWS Lambda.
Deploy your Worker code as a Lambda function, and Temporal Cloud invokes it when Tasks arrive.
Each invocation starts a Worker, polls for Tasks, then gracefully shuts down before a configurable invocation deadline.
You register Workflows and Activities the same way you would with a standard Worker.
For a full end-to-end deployment guide covering AWS IAM setup, compute configuration, and verification, see Deploy a Serverless Worker on AWS Lambda.
Create and run a Worker in Lambda
Use the runWorker function to create a Lambda handler that runs a Temporal Worker.
Pass a deployment version and a configure callback that sets up your Workflows and Activities.
typescript-sandbox/src/workers/serverless-workers/aws-lambda/index.ts
import { runWorker } from '@temporalio/lambda-worker';
// ...
import * as activities from './activities';
import { TASK_QUEUE } from './workflows';
export const handler = runWorker({ deploymentName: 'sdk-demo', buildId: 'v1' }, (config) => {
config.workerOptions.taskQueue = TASK_QUEUE;
config.workerOptions.workflowBundle = {
codePath: require.resolve('./workflow-bundle.js'),
};
config.workerOptions.activities = activities;
// ...
});
The deployment version is required.
Worker Deployment Versioning is always enabled for Serverless Workers.
Each Workflow must declare a versioning behavior, either AutoUpgrade or Pinned.
The default versioning behavior is PINNED. To change it, set workerDeploymentOptions.defaultVersioningBehavior in the configure callback.
Pre-bundle Workflow code
Use workflowBundle with pre-bundled code instead of workflowsPath.
Pre-bundling avoids webpack bundling overhead on every Lambda cold start.
Build the bundle as a separate build step:
typescript-sandbox/src/workers/serverless-workers/aws-lambda/scripts/build-workflow-bundle.ts
import { bundleWorkflowCode } from '@temporalio/worker';
import { writeFile } from 'fs/promises';
import path from 'path';
export async function bundle(): Promise<void> {
const { code } = await bundleWorkflowCode({
workflowsPath: require.resolve('../workflows'),
});
await writeFile(path.join(__dirname, '../workflow-bundle.js'), code);
}
Then reference the bundle in your handler with workflowBundle: { codePath: require.resolve('./workflow-bundle.js') }.
Configure the Temporal connection
The @temporalio/lambda-worker package automatically loads Temporal client configuration from a TOML config file and environment variables. Refer to Environment Configuration for more details.
The package uses the path in TEMPORAL_CONFIG_FILE when set. Otherwise, it looks for a readable temporal.toml in
$LAMBDA_TASK_ROOT (typically /var/task), then in the current working directory. If neither has a readable file, the
package uses the default configuration path. The file is optional.
Load credentials from a secret
Use @temporalio/lambda-worker v1.27.0 or later.
For each credential you want the Worker to load from AWS Secrets Manager, set the secret name or full ARN in the
Lambda environment or under profile.<profile>.ext.aws_secrets_manager in TOML.
| Credential | Environment variable | TOML setting |
|---|---|---|
| API key | TEMPORAL_EXT_AWS_SECRETS_MANAGER_API_KEY_ID | api_key_id |
| Client certificate | TEMPORAL_EXT_AWS_SECRETS_MANAGER_TLS_CLIENT_CERT_ID | tls.client_cert_id |
| Client private key | TEMPORAL_EXT_AWS_SECRETS_MANAGER_TLS_CLIENT_KEY_ID | tls.client_key_id |
| Server CA certificate | TEMPORAL_EXT_AWS_SECRETS_MANAGER_TLS_SERVER_CA_CERT_ID | tls.server_ca_cert_id |
An API key secret contains the key as a plain string. Certificate and private key secrets contain PEM. To load mTLS credentials, set the client certificate and client private key IDs together. If one secret contains the certificate and private key, use its ID for both settings. Set the server CA certificate ID if you need a custom CA. Keep TLS enabled when you use TLS secret IDs.
For each secret ID, the Lambda environment variable overrides the corresponding TOML setting.
When you configure an API key secret ID, remove any TEMPORAL_API_KEY setting from the Lambda function's environment
and any api_key setting from the TOML profile. The
direct-key deployment example
sets that environment variable. The Worker fails at startup if you set a secret ID and a direct value or file path for
the same credential, even across environment variables and TOML.
The Worker retrieves secrets through the AWS Parameters and Secrets Lambda Extension when available. Otherwise, it uses the AWS SDK.
Grant the Lambda execution role permission to read the secrets.
To retrieve secrets through the AWS SDK for JavaScript, add @aws-sdk/client-secrets-manager to your function's
dependencies. If you bundle the handler, keep this dependency outside the bundle and include it in the deployment
package's node_modules directory.
Adjust Worker defaults for Lambda
The @temporalio/lambda-worker package applies conservative defaults suited to short-lived Lambda invocations.
These differ from standard Worker defaults to avoid overcommitting resources in a constrained environment.
| Setting | Lambda default |
|---|---|
maxConcurrentActivityTaskExecutions | 2 |
maxConcurrentWorkflowTaskExecutions | 10 |
maxConcurrentLocalActivityExecutions | 2 |
maxConcurrentNexusTaskExecutions | 5 |
workflowTaskPollerBehavior | SimpleMaximum(2) |
activityTaskPollerBehavior | SimpleMaximum(1) |
nexusTaskPollerBehavior | SimpleMaximum(1) |
shutdownGraceTime | 5 seconds |
maxCachedWorkflows | 30 |
shutdownDeadlineBufferMs | 7000 |
Eager Activities are not supported. Lambda invocations don't maintain persistent connections.
shutdownDeadlineBufferMs is specific to the @temporalio/lambda-worker package.
It controls how much time before the Lambda deadline the Worker begins its graceful shutdown.
The default is shutdownGraceTime (5s) + 2s.
If your Worker handles long-running Activities, increase shutdownGraceTime, shutdownDeadlineBufferMs, and the Lambda invocation deadline (--timeout) together.
For guidance on how these values relate, see Tuning for long-running Activities.
Add observability with OpenTelemetry
The @temporalio/lambda-worker/otel module provides OpenTelemetry integration with defaults configured for the AWS Distro for OpenTelemetry (ADOT) Lambda layers.
With this enabled, the Worker emits SDK metrics and distributed traces for Workflow and Activity executions.
The underlying metrics and traces are the same ones the TypeScript SDK emits in any environment. For general observability concepts and the full list of available metrics, see Observability - TypeScript SDK and the SDK metrics reference.
typescript-sandbox/src/workers/serverless-workers/aws-lambda/index.ts
import { runWorker } from '@temporalio/lambda-worker';
import { applyDefaults } from '@temporalio/lambda-worker/otel';
import * as activities from './activities';
import { TASK_QUEUE } from './workflows';
export const handler = runWorker({ deploymentName: 'sdk-demo', buildId: 'v1' }, (config) => {
config.workerOptions.taskQueue = TASK_QUEUE;
config.workerOptions.workflowBundle = {
codePath: require.resolve('./workflow-bundle.js'),
};
config.workerOptions.activities = activities;
applyDefaults(config);
});
applyDefaults registers Temporal SDK interceptors for tracing and configures the Core SDK to export metrics via OpenTelemetry Protocol (OTLP).
By default, telemetry is sent to localhost:4317, which is the ADOT Lambda layer's default collector endpoint.
To collect this telemetry, attach two ADOT Lambda layers:
- The ADOT JavaScript layer for Node.js-side auto-instrumentation and trace export.
- The ADOT Collector layer (
aws-otel-collector-amd64) to run the OTel Collector as a Lambda extension, receiving telemetry via OTLP onlocalhost:4317and forwarding traces to X-Ray and metrics to CloudWatch.
The default Collector configuration does not route OTLP data to the traces pipeline.
You must provide a custom Collector configuration that wires the OTLP receiver to both the traces and metrics pipelines.
Bundle the following otel-collector-config.yaml in your Lambda deployment package:
typescript-sandbox/src/workers/serverless-workers/aws-lambda/otel-collector-config.yaml
receivers:
otlp:
protocols:
grpc:
endpoint: 'localhost:4317'
http:
endpoint: 'localhost:4318'
exporters:
debug:
awsxray:
region: us-west-2
awsemf:
# AWS EMF exporter for metrics
# These are example configurations
namespace: TemporalWorkerMetrics
log_group_name: /aws/lambda/<your-function-name>
region: us-west-2
dimension_rollup_option: NoDimensionRollup
resource_to_telemetry_conversion:
enabled: true
service:
pipelines:
traces:
receivers: [otlp]
exporters: [awsxray, debug]
metrics:
receivers: [otlp]
exporters: [awsemf]
telemetry:
logs:
level: info
metrics:
address: localhost:8888
Set the following environment variable on the Lambda function:
OPENTELEMETRY_COLLECTOR_CONFIG_URI=/var/task/otel-collector-config.yaml
Enable X-Ray active tracing on the Lambda function:
aws lambda update-function-configuration \
--function-name <your-function-name> \
--tracing-config Mode=Active
The Lambda execution role must have permissions to write to X-Ray and CloudWatch.
Add xray:PutTraceSegments, xray:PutTelemetryRecords, and cloudwatch:PutMetricData permissions to the execution role.
Without these permissions, the Collector fails silently and no telemetry appears.
When pre-bundling Workflow code, pass the plugin from makeOtelPlugin() so that Workflow interceptor modules are included in the bundle:
typescript-sandbox/src/workers/serverless-workers/aws-lambda/scripts/build-workflow-bundle-otel.ts
import { bundleWorkflowCode } from '@temporalio/worker';
import { makeOtelPlugin } from '@temporalio/lambda-worker/otel';
import { writeFile } from 'fs/promises';
import path from 'path';
export async function bundle(): Promise<void> {
const { plugin } = makeOtelPlugin();
const { code } = await bundleWorkflowCode({
workflowsPath: require.resolve('../workflows'),
plugins: [plugin],
});
await writeFile(path.join(__dirname, '../workflow-bundle.js'), code);
}