
I Tried Running Lambda MicroVMs Jobs Using an Extension of Lambda Durable Functions
This page has been translated by machine translation. View original
Introduction
On November 25, 2026, an extension to Lambda durable functions was released as a developer preview. With this extension, you can orchestrate Lambda MicroVMs.
Using this extension, I tried starting a MicroVM, running a job, and terminating it from a TypeScript durable function. Here are the results.
Test environment
- Region: Tokyo (ap-northeast-1)
- Lambda function
- Runtime: nodejs22.x
- Memory: 512 MB
- Timeout: 71 seconds
- Bundled packages
- @aws/durable-execution-sdk-js: 3.1.0
- @aws/durable-execution-sdk-js-extensions: 0.1.0-alpha.0
- @aws-sdk/client-lambda-microvms: 3.1178.0
- MicroVM
- Base image: al2023-1
- Architecture: ARM_64
- Minimum memory: 2048 MiB
- egress: INTERNET_EGRESS
- Packages included in the image
- @aws/durable-execution-sdk-js-compute-worker: 0.1.0-alpha.0
Preparation
The extension goes into the function, and the worker that receives jobs on the MicroVM side goes into the MicroVM image.
Create in advance an S3 bucket in which to place the zip for the MicroVM image. In the following, <バケット名> is the name of that bucket. Creating an image requires a build role, so create them in this order: IAM roles, the MicroVM image, and the durable function. Place the files in the following structure, and run the subsequent commands in this directory.
.
├── build.sh
├── package.json
├── tsconfig.json
├── iam/
│ ├── trust.json
│ ├── build-role-policy.json
│ ├── microvm-role-policy.json
│ └── function-role-policy.json
├── microvm/
│ ├── app.ts
│ ├── Dockerfile
│ └── hooks.json
└── function/
└── index.ts
IAM roles
There are three roles. The build role is used to read the zip in S3 when creating the image. The MicroVM role is used when the worker returns results to the function. The function role is used to start and terminate MicroVMs, deliver jobs over HTTP, and pass the MicroVM role.
aws iam create-role --role-name dex-mvm-art-build --assume-role-policy-document file://iam/trust.json
aws iam put-role-policy --role-name dex-mvm-art-build --policy-name inline --policy-document file://iam/build-role-policy.json
aws iam create-role --role-name dex-mvm-art-microvm --assume-role-policy-document file://iam/trust.json
aws iam put-role-policy --role-name dex-mvm-art-microvm --policy-name inline --policy-document file://iam/microvm-role-policy.json
aws iam create-role --role-name dex-mvm-art-function --assume-role-policy-document file://iam/trust.json
aws iam put-role-policy --role-name dex-mvm-art-function --policy-name inline --policy-document file://iam/function-role-policy.json
aws iam attach-role-policy --role-name dex-mvm-art-function --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicDurableExecutionRolePolicy
IAM role files
Replace <バケット名> and <アカウントID> in the policies with your own values. The callback permissions of the MicroVM role are restricted by Resource to functions whose names match dex-mvm-art-*. If you change the function name prefix, change the Resource as well.
iam/trust.json (common to all three roles)
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": { "Service": "lambda.amazonaws.com" },
"Action": ["sts:AssumeRole", "sts:TagSession"]
}]
}
iam/build-role-policy.json
{
"Version": "2012-10-17",
"Statement": [
{ "Effect": "Allow", "Action": ["s3:GetObject"], "Resource": "arn:aws:s3:::<バケット名>/*" },
{ "Effect": "Allow", "Action": ["logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents"], "Resource": "*" }
]
}
iam/microvm-role-policy.json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"lambda:SendDurableExecutionCallbackSuccess",
"lambda:SendDurableExecutionCallbackFailure",
"lambda:SendDurableExecutionCallbackHeartbeat"
],
"Resource": "arn:aws:lambda:ap-northeast-1:<アカウントID>:function:dex-mvm-art-*:*"
},
{ "Effect": "Allow", "Action": ["logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents"], "Resource": "*" }
]
}
Include the TerminateMicrovm permission in the function role. If you don't, the MicroVM won't terminate even after the job finishes, and it will keep running and incurring charges until the maximum run time.
iam/function-role-policy.json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"lambda:RunMicrovm",
"lambda:TerminateMicrovm",
"lambda:GetMicrovm",
"lambda:CreateMicrovmAuthToken"
],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": "lambda:PassNetworkConnector",
"Resource": "arn:aws:lambda:ap-northeast-1:aws:network-connector:aws-network-connector:*"
},
{
"Effect": "Allow",
"Action": "iam:PassRole",
"Resource": "arn:aws:iam::<アカウントID>:role/dex-mvm-art-microvm"
}
]
}
MicroVM image
The worker is started with startMicrovmWorker. A job without a path goes to the handler, and a job with a path goes to the matching route among routes. This worker receives the jobs of microvm() (one job, parallel, failure) in the handler, and the two session jobs in the routes /write and /read.
microvm/app.ts
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { startMicrovmWorker } from "@aws/durable-execution-sdk-js-compute-worker/microvm";
interface Job {
label: string;
sleepSeconds?: number;
fail?: boolean;
}
// ファイルは /tmp/session、メモリはこの変数に置く。セッションの検証で、
// 別のジョブから読めるかを確認する。
const DIR = "/tmp/session";
let remembered: string | undefined;
// microvm() のジョブはここに届く(routes に当たらないジョブ)
const runJob = async (
job: Job,
context: { microvmId: string },
): Promise<unknown> => {
const startedAt = new Date().toISOString();
await new Promise((r) => setTimeout(r, (job.sleepSeconds ?? 0) * 1000));
if (job.fail) {
throw new Error(`job ${job.label} failed on purpose`);
}
return {
label: job.label,
microvmId: context.microvmId,
node: process.version,
startedAt,
finishedAt: new Date().toISOString(),
};
};
await startMicrovmWorker<Job, unknown>({
handler: runJob,
routes: {
// セッション用: 1つ目のジョブがファイルとメモリに書く
"/write": async (input: unknown, context) => {
const { value } = input as { value: string };
await mkdir(DIR, { recursive: true });
await writeFile(`${DIR}/note.txt`, value);
remembered = value;
return { microvmId: context.microvmId, pid: process.pid };
},
// 2つ目のジョブが読む
"/read": async (_input: unknown, context) => ({
microvmId: context.microvmId,
pid: process.pid,
file: await readFile(`${DIR}/note.txt`, "utf8"),
memory: remembered,
}),
},
});
To create the image, I used the following Dockerfile, which copies the built worker app.mjs and starts it.
FROM public.ecr.aws/docker/library/node:22-alpine
WORKDIR /app
COPY app.mjs .
EXPOSE 8080
# Lambda takes a snapshot after the process starts
CMD ["node", "app.mjs"]
Hooks are configured in microvm/hooks.json. run is required, and ready is also required if you enable lifecycle hooks.
{
"port": 8080,
"microvmHooks": {
"run": "ENABLED",
"runTimeoutInSeconds": 10,
"resume": "ENABLED",
"resumeTimeoutInSeconds": 10,
"suspend": "ENABLED",
"suspendTimeoutInSeconds": 10,
"terminate": "ENABLED",
"terminateTimeoutInSeconds": 10
},
"microvmImageHooks": { "ready": "ENABLED", "readyTimeoutInSeconds": 60 }
}
build.sh creates two zips, one for the function and one for the worker. function/index.ts is a single file that joins the following two parts: the code in the "durable function" section (imports and common settings), and the four exports (job, session, parallel, failure) in the "Execution and execution history" sections. Place all the files, then run build.sh.
build.sh, package.json, tsconfig.json
build.sh
#!/bin/bash
# Install dependencies in Docker, type-check, and create two zips
set -euo pipefail
cd "$(dirname "$0")"
docker run --rm --user "$(id -u):$(id -g)" -e HOME=/tmp -v "$PWD:/app" -w /app node:22 bash -c '
npm install --no-audit --no-fund --loglevel=error
npx tsc -p tsconfig.json
rm -rf build && mkdir -p build/function build/microvm
# Function: bundle the durable SDK and the MicroVMs client
npx esbuild function/index.ts --bundle --platform=node --target=node22 \
--format=cjs --outfile=build/function/index.js --log-level=warning
# Worker: uses top-level await, so make it an ES module
npx esbuild microvm/app.ts --bundle --platform=node --target=node22 \
--format=esm --outfile=build/microvm/app.mjs --log-level=warning \
--banner:js="import { createRequire } from \"node:module\"; const require = createRequire(import.meta.url);"
cp microvm/Dockerfile build/microvm/Dockerfile
'
(cd build/function && zip -qj ../function.zip index.js)
(cd build/microvm && zip -qj ../microvm.zip app.mjs Dockerfile)
ls -l build/*.zip
package.json
{
"name": "dex-mvm-article",
"private": true,
"type": "module",
"dependencies": {
"@aws-sdk/client-lambda-microvms": "3.1178.0",
"@aws/durable-execution-sdk-js": "3.1.0",
"@aws/durable-execution-sdk-js-compute-worker": "0.1.0-alpha.0",
"@aws/durable-execution-sdk-js-extensions": "0.1.0-alpha.0"
},
"devDependencies": {
"esbuild": "0.28.2",
"typescript": "5.9.3",
"@types/node": "22.19.0"
}
}
tsconfig.json
{
"compilerOptions": {
"target": "ES2022",
"module": "ES2022",
"moduleResolution": "bundler",
"strict": true,
"noEmit": true,
"skipLibCheck": true,
"types": ["node"]
},
"include": ["function/*.ts", "microvm/*.ts"]
}
bash build.sh
aws s3 cp build/microvm.zip s3://<バケット名>/microvm.zip
I created the image with the following command.
aws lambda-microvms create-microvm-image \
--name dex-mvm-art-image \
--code-artifact uri=s3://<バケット名>/microvm.zip \
--base-image-arn arn:aws:lambda:ap-northeast-1:aws:microvm-image:al2023-1 \
--build-role-arn arn:aws:iam::<アカウントID>:role/dex-mvm-art-build \
--egress-network-connectors arn:aws:lambda:ap-northeast-1:aws:network-connector:aws-network-connector:INTERNET_EGRESS \
--hooks file://microvm/hooks.json
Immediately after creation, the state was CREATING. After that, I confirmed with the following command that it became CREATED.
aws lambda-microvms get-microvm-image \
--image-identifier arn:aws:lambda:ap-northeast-1:<アカウントID>:microvm-image:dex-mvm-art-image
durable function
At the top of the function code, put the extension imports and the settings common to the jobs. The ARN of the image and the ARN of the MicroVM role are passed through environment variables.
import {
DurableContext,
withDurableExecution,
} from "@aws/durable-execution-sdk-js";
import {
MicrovmJobFailedError,
microvm,
microvmSession,
} from "@aws/durable-execution-sdk-js-extensions/compute/microvm";
const config = {
imageIdentifier: process.env.MICROVM_IMAGE_ARN!,
executionRoleArn: process.env.MICROVM_ROLE_ARN!,
timeout: { minutes: 5 },
heartbeatTimeout: { seconds: 60 },
};
interface JobResult {
label: string;
microvmId: string;
node: string;
startedAt: string;
finishedAt: string;
}
According to the README, at least 11 seconds of remaining invocation time are required when the request step starts. I set the function timeout to 71 seconds so that the request step can use the full 60-second window it uses for retries. A durable function is invoked by specifying a published version or an alias.
The four functions (one job, session, parallel, failure) are created from the same zip. The following command creates the function for the one-job case and publishes a version.
aws lambda create-function \
--function-name dex-mvm-art-job \
--runtime nodejs22.x \
--handler index.job \
--role arn:aws:iam::<アカウントID>:role/dex-mvm-art-function \
--timeout 71 \
--memory-size 512 \
--environment '{"Variables":{"MICROVM_IMAGE_ARN":"arn:aws:lambda:ap-northeast-1:<アカウントID>:microvm-image:dex-mvm-art-image","MICROVM_ROLE_ARN":"arn:aws:iam::<アカウントID>:role/dex-mvm-art-microvm"}}' \
--durable-config '{"ExecutionTimeout":3600,"RetentionPeriodInDays":1}' \
--zip-file fileb://build/function.zip
aws lambda publish-version --function-name dex-mvm-art-job
The four functions differ only in --function-name and --handler. For all of them, I published version 1.
| Execution | Function name | handler |
|---|---|---|
| One job | dex-mvm-art-job | index.job |
| Session | dex-mvm-art-session | index.session |
| Parallel | dex-mvm-art-parallel | index.parallel |
| Failure | dex-mvm-art-failure | index.failure |
Execution and execution history
I invoked all four functions asynchronously. Specify the DurableExecutionArn returned by the invocation as <DurableExecutionArn> in the subsequent commands. I retrieved the result with get-durable-execution and the execution history with get-durable-execution-history, and formatted the history into TSV with the following jq.
aws lambda get-durable-execution-history \
--durable-execution-arn <DurableExecutionArn> \
--include-execution-data \
| jq -r '.Events[] | [.EventId, .EventTimestamp[11:23], .EventType, (.SubType//""), (.Name//""), (if .EventType=="InvocationCompleted" then (.InvocationCompletedDetails.StartTimestamp[11:23] + " - " + .InvocationCompletedDetails.EndTimestamp[11:23]) else "" end)] | @tsv'
I checked the state of the MicroVMs by running the following command every few seconds while the function was running.
aws lambda-microvms list-microvms --query 'items[].state' --output text
One job
This is a function that calls microvm once. The second argument, hello, is the name of the operation, and it is also used as the prefix of the child operation names in the history (such as hello.launch).
export const job = withDurableExecution(
async (_event: unknown, context: DurableContext) =>
microvm<JobResult>(context, "hello", { label: "hello" }, config),
);
aws lambda invoke \
--function-name dex-mvm-art-job \
--qualifier 1 \
--invocation-type Event \
--durable-execution-name job-1 \
--payload '{}' \
--cli-binary-format raw-in-base64-out \
invoke-job.json
aws lambda get-durable-execution --durable-execution-arn <DurableExecutionArn>
Here are the fields needed to check the result, excerpted from the output of get-durable-execution.
{
"Result": "{\"label\":\"hello\",\"microvmId\":\"microvm-9600f2ff-…\",\"node\":\"v22.23.5\",\"startedAt\":\"2026-11-26T02:26:46.153Z\",\"finishedAt\":\"2026-11-26T02:26:46.222Z\"}",
"StartTimestamp": "2026-11-26T11:26:43.820000+09:00",
"Status": "SUCCEEDED",
"EndTimestamp": "2026-11-26T11:26:47.270000+09:00"
}
The execution history was as follows.
| ID | Time | EventType | SubType | Name | Function execution interval |
|---|---|---|---|---|---|
| 1 | 11:26:43.820 | ExecutionStarted | job-1 | ||
| 2 | 11:26:44.710 | ContextStarted | Microvm | hello | |
| 3 | 11:26:44.710 | CallbackStarted | MicrovmCallback | hello.callback | |
| 4 | 11:26:44.799 | StepStarted | MicrovmLaunch | hello.launch | |
| 5 | 11:26:44.937 | StepSucceeded | MicrovmLaunch | hello.launch | |
| 6 | 11:26:44.972 | InvocationCompleted | 11:26:43.884 - 11:26:44.967 | ||
| 7 | 11:26:47.031 | CallbackSucceeded | MicrovmCallback | hello.callback | |
| 8 | 11:26:47.128 | StepStarted | MicrovmTerminate | hello.terminate | |
| 9 | 11:26:47.229 | StepSucceeded | MicrovmTerminate | hello.terminate | |
| 10 | 11:26:47.251 | ContextSucceeded | Microvm | hello | |
| 11 | 11:26:47.270 | InvocationCompleted | 11:26:47.064 - 11:26:47.266 | ||
| 12 | 11:26:47.270 | ExecutionSucceeded | job-1 |
Under hello, three operations were recorded: launch (starting the MicroVM), callback (receiving the job result), and terminate (termination).
The function execution was split into two parts. The first ended right after launch completed (44.937), and the second started right after the callback succeeded (47.031). During the roughly 2.1 seconds in between, the function was not running.
There is no request step in this history. The result of launch was "delivery":"run-hook".
Session
This is a function that, inside microvmSession, runs a write job, a 10-second wait, and a read job in that order. For write and read, specify a path that matches the worker's routes.
export const session = withDurableExecution(
async (_event: unknown, context: DurableContext) =>
microvmSession(
context,
"pipeline",
{
imageIdentifier: config.imageIdentifier,
executionRoleArn: config.executionRoleArn,
timeout: { minutes: 10 },
},
async (vm, ctx) => {
const written = await vm.invoke<{ microvmId: string; pid: number }>(
ctx,
"write",
{ value: "written-by-job-1" },
{
path: "/write",
timeout: { minutes: 5 },
heartbeatTimeout: { seconds: 30 },
},
);
await ctx.wait("pause", { seconds: 10 });
const read = await vm.invoke<{
microvmId: string;
pid: number;
file: string;
memory: string;
}>(
ctx,
"read",
{},
{
path: "/read",
timeout: { minutes: 5 },
heartbeatTimeout: { seconds: 30 },
},
);
return { written, read };
},
),
);
The invocation is the same as for the one-job case, with the function name changed to dex-mvm-art-session and the execution name to session-1. The Result was as follows.
{
"Result": "{\"written\":{\"microvmId\":\"microvm-f06a41bc-…\",\"pid\":1},\"read\":{\"microvmId\":\"microvm-f06a41bc-…\",\"pid\":1,\"file\":\"written-by-job-1\",\"memory\":\"written-by-job-1\"}}"
}
The two jobs had the same microvmId, and the second job could read the value written by the first from both the file and the memory.
Following ParentId in the execution history, the operation names and SubTypes are shown below as a parent-child tree.
pipeline (MicrovmSession)
├─ pipeline.session (MicrovmSessionId)
├─ pipeline.launch (MicrovmLaunch)
├─ write (MicrovmSessionJob)
│ ├─ write.callback (MicrovmCallback)
│ └─ write.request (MicrovmRequest)
├─ pause (Wait) 11:27:07.171 → 11:27:17.171
├─ read (MicrovmSessionJob)
│ ├─ read.callback (MicrovmCallback)
│ └─ read.request (MicrovmRequest)
└─ pipeline.terminate (MicrovmTerminate)
In the session, the delivery in the launch result was http, and a request step was recorded for each job.
The function execution ended once at 11:27:07.198, right after the wait started, and resumed at 11:27:17.274, after the wait finished. In the checks at 11:27:10 and 11:27:16 during the wait, the session's MicroVM remained RUNNING.
Parallel execution
This is a function that calls microvm inside map. Each of the two jobs waits 20 seconds in the worker and then returns its result.
export const parallel = withDurableExecution(
async (_event: unknown, context: DurableContext) => {
const items = [{ label: "a" }, { label: "b" }];
const results = await context.map("builds", items, async (itemCtx, item) =>
microvm<JobResult>(
itemCtx,
`build-${item.label}`,
{ label: item.label, sleepSeconds: 20 },
config,
),
);
return results.getResults();
},
);
The execution started at 11:27:33.946 and ended at 11:27:57.019 (23.07 seconds). The Result was as follows.
{
"Result": "[{\"label\":\"a\",\"microvmId\":\"microvm-cf598de8-…\",\"node\":\"v22.23.5\",\"startedAt\":\"2026-11-26T02:27:36.582Z\",\"finishedAt\":\"2026-11-26T02:27:56.584Z\"},{\"label\":\"b\",\"microvmId\":\"microvm-8578e2e0-…\",\"node\":\"v22.23.5\",\"startedAt\":\"2026-11-26T02:27:36.698Z\",\"finishedAt\":\"2026-11-26T02:27:56.701Z\"}]"
}
The two jobs ran on separate MicroVMs. From startedAt and finishedAt (UTC) in the Result, you can see that each ran for 20 seconds, almost simultaneously. In the checks every 3 seconds (7 times, from 11:27:37 to 11:27:55), there were two RUNNING MicroVMs every time.
In the history, there were two MapIterations under Map, and a Microvm operation under each of them. Both launch steps started at 11:27:35.419.
builds (Map)
├─ map-item-0 (MapIteration)
│ └─ build-a (Microvm)
│ ├─ build-a.callback (MicrovmCallback)
│ ├─ build-a.launch (MicrovmLaunch)
│ └─ build-a.terminate (MicrovmTerminate)
└─ map-item-1 (MapIteration)
└─ build-b (Microvm)
├─ build-b.callback (MicrovmCallback)
├─ build-b.launch (MicrovmLaunch)
└─ build-b.terminate (MicrovmTerminate)
Job failure
This is a function in which the first job throws an exception in the worker. The function catches MicrovmJobFailedError and then calls a second microvm. For the attempt-1 job, fail: true is passed in the input.
export const failure = withDurableExecution(
async (_event: unknown, context: DurableContext) => {
let failure: { name: string; message: string } | undefined;
try {
await microvm(context, "attempt-1", { label: "x", fail: true }, config);
} catch (error) {
if (!(error instanceof MicrovmJobFailedError)) {
throw error;
}
failure = { name: error.name, message: error.message };
}
const second = await microvm<JobResult>(
context,
"attempt-2",
{ label: "x" },
config,
);
return { failure, second };
},
);
The name and message of the caught error were included in the failure of the Result.
{
"Result": "{\"failure\":{\"name\":\"MicrovmJobFailedError\",\"message\":\"MicroVM \\\"attempt-1\\\": the job failed: job x failed on purpose\"},\"second\":{\"label\":\"x\",\"microvmId\":\"microvm-06e03e52-…\",\"node\":\"v22.23.5\",\"startedAt\":\"2026-11-26T02:28:15.813Z\",\"finishedAt\":\"2026-11-26T02:28:15.814Z\"}}"
}
Here are the rows of the history that show the flow before and after the failure.
| ID | Time | EventType | SubType | Name |
|---|---|---|---|---|
| 4 | 11:28:12.732 | StepStarted | MicrovmLaunch | attempt-1.launch |
| 5 | 11:28:12.874 | StepSucceeded | MicrovmLaunch | attempt-1.launch |
| 7 | 11:28:14.059 | CallbackFailed | MicrovmCallback | attempt-1.callback |
| 8 | 11:28:14.173 | StepStarted | MicrovmTerminate | attempt-1.terminate |
| 9 | 11:28:14.233 | StepSucceeded | MicrovmTerminate | attempt-1.terminate |
| 10 | 11:28:14.266 | ContextFailed | Microvm | attempt-1 |
| 11 | 11:28:14.266 | ContextStarted | Microvm | attempt-2 |
| 12 | 11:28:14.266 | CallbackStarted | MicrovmCallback | attempt-2.callback |
| 13 | 11:28:14.311 | StepStarted | MicrovmLaunch | attempt-2.launch |
| 14 | 11:28:14.515 | StepSucceeded | MicrovmLaunch | attempt-2.launch |
Even after the callback of attempt-1 failed, the terminate step succeeded. attempt-1.launch was recorded only once. The exception thrown by the worker's job returned to the function as MicrovmJobFailedError without the job being re-executed, and attempt-2 started a separate MicroVM and succeeded.
If you want to re-run the job, catch the error in the function code and call microvm again. For the retry specification, see the following documentation.
Summary
With the Lambda durable functions extension, I was able to confirm in the execution history the starting of a MicroVM, the receiving of the job result, and the termination.
Lambda MicroVMs can be used as execution environments isolated at the virtual machine level.
The durable functions extension makes it easier to build workflows that run multiple MicroVMs in sequence or in parallel.
Please try this update as a way to realize sandboxes that run AI-generated code, and CI/CD pipelines that embed sandboxes.
