
I Tried Running Lambda MicroVMs Jobs with Step Functions
This page has been translated by machine translation. View original
Introduction
On November 25, 2026, an extension was announced that lets AWS Lambda durable functions orchestrate Lambda MicroVMs.
I tried to see whether the mechanisms this extension implements, namely running individual tasks and sessions, can be achieved with Step Functions SDK integrations and JSONata. This article presents the results.
Test environment
- Region: Tokyo (ap-northeast-1)
- AWS CLI: 2.42.4
- State machine: Standard, JSONata
- Base image: al2023-1 (the version selected when creating the Image was 4.2)
- Image minimum memory: 4096 MiB
- Network connector: INTERNET_EGRESS
- additionalOsCapabilities: ALL
- Architectures: ARM_64, X86_64
- vCPUs (nproc inside the MicroVM): 8
- Root file system (inside the MicroVM): 63G
- Free memory (inside the MicroVM, before docker build starts): about 15.2 GiB
Preparation
The state machine starts a MicroVM with runMicrovm. The app inside the MicroVM runs the job and returns the result with SendTaskSuccess and similar calls. The state machine then ends the MicroVM with terminateMicrovm.
What you need: an S3 bucket to hold the Image materials, three IAM roles, a MicroVM Image, an Activity, and state machines. I laid out the files as follows.
artifacts/
├── iam/
│ ├── trust-lambda.json
│ ├── trust-states.json
│ ├── build-role-policy.json
│ ├── microvm-role-policy.json
│ └── sfn-role-policy.json
├── iam-rendered/ # iam/ のポリシーのプレースホルダを値に置換したもの
├── asl/
│ ├── job.asl.json
│ ├── session.asl.json
│ └── matrix.asl.json
├── asl-rendered/
│ └── session.asl.json # ${ACTIVITY_ARN} を置換したもの
├── microvm/
│ ├── Dockerfile
│ ├── hooks.json
│ ├── app.py
│ └── jobs/
│ ├── info.sh
│ ├── build-hello.sh
│ ├── docker-check.sh
│ └── strands-build.sh
├── build/microvm.zip
└── input-*.json
IAM roles
| Role name | Purpose | Required permissions |
|---|---|---|
| sfnmvm-build | Creating the Image | Read the zip from S3, write logs |
| sfnmvm-microvm | App inside the MicroVM | SendTaskSuccess, SendTaskFailure, SendTaskHeartbeat, GetActivityTask, S3 read/write, write logs |
| sfnmvm-sfn | State machine | RunMicrovm, TerminateMicrovm, GetMicrovm, PassNetworkConnector, PassRole |
Because the app inside the MicroVM returns results with a task token, I attached SendTask* to the MicroVM execution role. The state machine starts MicroVMs from an Image with an INTERNET_EGRESS network connector attached. For that, the state machine's role needs lambda:PassNetworkConnector.
Full policies (with placeholders)
trust-lambda.json
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": { "Service": "lambda.amazonaws.com" },
"Action": "sts:AssumeRole"
}]
}
trust-states.json
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": { "Service": "states.amazonaws.com" },
"Action": "sts:AssumeRole"
}]
}
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": "*" }
]
}
microvm-role-policy.json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["states:SendTaskSuccess", "states:SendTaskFailure", "states:SendTaskHeartbeat"],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": "states:GetActivityTask",
"Resource": "arn:aws:states:ap-northeast-1:<アカウントID>:activity:sfnmvm-*"
},
{
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:PutObject"],
"Resource": "arn:aws:s3:::<バケット名>/*"
},
{
"Effect": "Allow",
"Action": ["logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents"],
"Resource": "arn:aws:logs:ap-northeast-1:<アカウントID>:log-group:/aws/lambda-microvms/*"
}
]
}
sfn-role-policy.json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["lambda:RunMicrovm", "lambda:GetMicrovm", "lambda:TerminateMicrovm"],
"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/sfnmvm-microvm"
}
]
}
I created the bucket and roles and attached the policies with the following commands.
aws s3api create-bucket --bucket <バケット名> --create-bucket-configuration LocationConstraint=ap-northeast-1
aws iam create-role --role-name sfnmvm-build --assume-role-policy-document file://artifacts/iam/trust-lambda.json
aws iam create-role --role-name sfnmvm-microvm --assume-role-policy-document file://artifacts/iam/trust-lambda.json
aws iam create-role --role-name sfnmvm-sfn --assume-role-policy-document file://artifacts/iam/trust-states.json
aws iam put-role-policy --role-name sfnmvm-build --policy-name inline --policy-document file://artifacts/iam-rendered/build-role-policy.json
aws iam put-role-policy --role-name sfnmvm-microvm --policy-name inline --policy-document file://artifacts/iam-rendered/microvm-role-policy.json
aws iam put-role-policy --role-name sfnmvm-sfn --policy-name inline --policy-document file://artifacts/iam-rendered/sfn-role-policy.json
MicroVM Image
At the top level of the zip, place the Dockerfile, the app itself app.py, and a jobs/ directory holding the job scripts. hooks.json is not put in the zip; it is passed with --hooks when creating the Image.
Dockerfile
FROM public.ecr.aws/amazonlinux/amazonlinux:2023
RUN dnf install -y python3 python3-boto3 awscli-2 gcc tar gzip git && dnf clean all
ENV AWS_DEFAULT_REGION=ap-northeast-1
WORKDIR /app
COPY app.py /app/app.py
COPY jobs /app/jobs
EXPOSE 8080
# Lambda takes the snapshot after the process starts
CMD ["python3", "-u", "/app/app.py"]
hooks.json
{
"port": 8080,
"microvmHooks": {
"run": "ENABLED",
"runTimeoutInSeconds": 30,
"resume": "ENABLED",
"resumeTimeoutInSeconds": 30,
"suspend": "ENABLED",
"suspendTimeoutInSeconds": 30,
"terminate": "ENABLED",
"terminateTimeoutInSeconds": 30
},
"microvmImageHooks": { "ready": "ENABLED", "readyTimeoutInSeconds": 60 }
}
The app reads the runHookPayload of the /run hook, which is called when the MicroVM starts, as JSON. If the payload contains a task token, it runs the job and returns the result with SendTaskSuccess or SendTaskFailure. Some jobs take several minutes and exceed the /run hook timeout (30 seconds in hooks.json), so the app returns 200 to the hook immediately and runs the job in a separate thread. While the job runs, it calls SendTaskHeartbeat at the interval given by heartbeatSeconds in the payload (30 seconds). If the payload contains an Activity ARN, the app waits for Activity tasks with GetActivityTask (used for sessions).
Full app.py
"""MicroVM 内のアプリ。ポート 8080 でライフサイクルフックを受ける。
- /run フックの runHookPayload を JSON として読む
- activityArn があれば Step Functions の Activity を待ち受ける(セッション用)
- taskToken があればジョブを実行し、SendTaskSuccess で結果を返す(1ジョブ用)
- フックには 200 を即返す。MicroVM は /run が 200 を返すまでトラフィックを受けない。
"""
import datetime
import json
import os
import platform
import subprocess
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import boto3
from botocore.config import Config
HOOK_PREFIX = "/aws/lambda-microvms/runtime/v1/"
SESSION_DIR = "/tmp/session"
JOB_DIR = "/app/jobs"
REGION = os.environ.get("AWS_DEFAULT_REGION", "ap-northeast-1")
# セッション検証で「メモリ」に置く値
MEMORY = {"value": None}
STATE = {"microvmId": None}
def log(**kw):
kw = {"ts": datetime.datetime.now(datetime.timezone.utc).isoformat(), **kw}
print(json.dumps(kw, ensure_ascii=False), flush=True)
def sfn():
# 認証情報は実行時に解決する
return boto3.client(
"stepfunctions", region_name=REGION, config=Config(read_timeout=70)
)
def run_script(name, env, tail_chars=3000):
"""ジョブのスクリプトを実行し、終了コードと出力の末尾を返す。"""
started = time.time()
path = os.path.join(JOB_DIR, name)
proc = subprocess.Popen(
["bash", path],
env={**os.environ, **env},
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
)
lines = []
for line in proc.stdout:
print(line, end="", flush=True) # CloudWatch Logs へ出す
lines.append(line)
code = proc.wait()
return {
"microvmId": STATE["microvmId"],
"script": name,
"uname": platform.machine(),
"exitCode": code,
"seconds": round(time.time() - started, 1),
"tail": "".join(lines)[-tail_chars:],
}
def heartbeat_loop(token, every, stop):
while not stop.wait(every):
try:
sfn().send_task_heartbeat(taskToken=token)
log(event="heartbeat sent")
except Exception as e: # noqa: BLE001
log(event="heartbeat failed", error=str(e))
def run_job(payload):
"""1ジョブ: 実行して SendTaskSuccess / SendTaskFailure で返す。"""
token = payload["taskToken"]
job = payload["job"]
stop = threading.Event()
hb = payload.get("heartbeatSeconds")
if hb:
threading.Thread(target=heartbeat_loop, args=(token, hb, stop), daemon=True).start()
try:
log(event="job start", job=job)
result = run_script(job["script"], job.get("env", {}))
stop.set()
if result["exitCode"] != 0:
sfn().send_task_failure(
taskToken=token, error="JobFailed", cause=json.dumps(result)[:32000]
)
else:
sfn().send_task_success(taskToken=token, output=json.dumps(result))
log(event="job done", exitCode=result["exitCode"], seconds=result["seconds"])
except Exception as e: # noqa: BLE001
stop.set()
log(event="job error", error=repr(e))
try:
sfn().send_task_failure(taskToken=token, error="WorkerError", cause=repr(e)[:32000])
except Exception as e2: # noqa: BLE001
log(event="send_task_failure failed", error=repr(e2))
def handle_session_op(job):
"""セッション: 1つ目が書いたファイルとメモリを、2つ目が読む。"""
op = job["op"]
if op == "write":
os.makedirs(SESSION_DIR, exist_ok=True)
with open(f"{SESSION_DIR}/note.txt", "w") as f:
f.write(job["value"])
MEMORY["value"] = job["value"]
return {"op": op, "microvmId": STATE["microvmId"], "pid": os.getpid()}
if op == "read":
with open(f"{SESSION_DIR}/note.txt") as f:
file_value = f.read()
return {
"op": op,
"microvmId": STATE["microvmId"],
"pid": os.getpid(),
"file": file_value,
"memory": MEMORY["value"],
}
raise ValueError(f"unknown op {op}")
def activity_loop(activity_arn):
"""Activity を待ち受ける。タスクが来たら処理し、SendTaskSuccess で返す。"""
log(event="activity loop start", activityArn=activity_arn)
while True:
try:
task = sfn().get_activity_task(
activityArn=activity_arn, workerName=STATE["microvmId"] or "microvm"
)
except Exception as e: # noqa: BLE001
log(event="get_activity_task failed", error=repr(e))
time.sleep(5)
continue
token = task.get("taskToken")
if not token:
continue # 60 秒のロングポーリングが空で戻った
job = json.loads(task["input"])
log(event="activity task", job=job)
try:
out = handle_session_op(job)
sfn().send_task_success(taskToken=token, output=json.dumps(out))
except Exception as e: # noqa: BLE001
sfn().send_task_failure(taskToken=token, error="WorkerError", cause=repr(e)[:32000])
def on_run(body):
STATE["microvmId"] = body.get("microvmId")
payload = json.loads(body.get("runHookPayload") or "{}")
log(event="run hook", microvmId=STATE["microvmId"], payloadKeys=sorted(payload))
if "activityArn" in payload:
threading.Thread(target=activity_loop, args=(payload["activityArn"],), daemon=True).start()
elif "taskToken" in payload:
threading.Thread(target=run_job, args=(payload,), daemon=True).start()
class Handler(BaseHTTPRequestHandler):
def do_POST(self):
length = int(self.headers.get("Content-Length") or 0)
raw = self.rfile.read(length) if length else b""
hook = self.path[len(HOOK_PREFIX):] if self.path.startswith(HOOK_PREFIX) else None
try:
if hook == "run":
on_run(json.loads(raw or b"{}"))
elif hook:
log(event=f"{hook} hook")
except Exception as e: # noqa: BLE001
log(event="hook error", hook=hook, error=repr(e))
self.send_response(200)
self.send_header("Content-Length", "0")
self.end_headers()
def do_GET(self):
self.send_response(200)
self.send_header("Content-Length", "0")
self.end_headers()
def log_message(self, fmt, *args):
pass
if __name__ == "__main__":
log(event="boot", machine=platform.machine())
ThreadingHTTPServer(("0.0.0.0", 8080), Handler).serve_forever()
Job scripts
jobs/info.sh
#!/bin/bash
# 最小のジョブ: MicroVM の環境を返す
set -euo pipefail
echo "uname -m: $(uname -m)"
echo "kernel: $(uname -r)"
echo "os: $(. /etc/os-release && echo "$PRETTY_NAME")"
echo "python: $(python3 --version)"
echo "caller: $(aws sts get-caller-identity --query Arn --output text | sed -E 's/[0-9]{12}/<ACCOUNT>/')"
echo "vcpus: $(nproc) mem: $(free -m | awk '/Mem:/{print $2}') MiB"
echo "disk: $(df -h / | awk 'NR==2{print $2" total, "$4" avail"}')"
jobs/build-hello.sh
#!/bin/bash
# 小さな C プログラムをビルドし、アーキテクチャを確認して S3 に置く
# 環境変数: BUCKET, ARCH_LABEL
set -euo pipefail
WORK=$(mktemp -d)
cd "$WORK"
cat > hello.c <<'EOF'
#include <stdio.h>
int main(void) { puts("hello from a MicroVM build"); return 0; }
EOF
gcc -O2 -o hello hello.c
echo "uname -m: $(uname -m)"
echo "binary: $(readelf -h hello | awk -F: '/Machine/{gsub(/^ +/,"",$2); print $2}')"
echo "run: $(./hello)"
echo "sha256: $(sha256sum hello | cut -d' ' -f1)"
KEY="out/${ARCH_LABEL}/hello"
aws s3 cp hello "s3://${BUCKET}/${KEY}" --no-progress
echo "uploaded: s3://<BUCKET>/${KEY}"
jobs/docker-check.sh
#!/bin/bash
# Check that the Docker daemon runs inside the MicroVM and docker build succeeds.
# Do not use set -e. Leave in the output where it stopped.
step() { echo; echo "=== $* ($(date +%T))"; }
step "dnf install docker"
dnf install -y docker 2>&1 | tail -n 5
echo "exit=$?"
step "start dockerd"
mkdir -p /var/log
nohup dockerd > /var/log/dockerd.log 2>&1 &
for i in $(seq 1 30); do
docker info > /dev/null 2>&1 && break
sleep 1
done
docker info 2>&1 | head -n 8
echo "docker info exit=${PIPESTATUS[0]}"
echo "--- dockerd.log (tail)"
tail -n 15 /var/log/dockerd.log
step "docker build"
D=$(mktemp -d)
cat > "$D/Dockerfile" <<'EOF'
FROM public.ecr.aws/amazonlinux/amazonlinux:2023
RUN echo "built inside a MicroVM" > /msg.txt
CMD ["cat", "/msg.txt"]
EOF
docker build -t mvm-check "$D" 2>&1 | tail -n 15
echo "docker build exit=${PIPESTATUS[0]}"
step "docker run"
docker run --rm mvm-check 2>&1 | tail -n 5
echo "docker run exit=${PIPESTATUS[0]}"
jobs/strands-build.sh
#!/bin/bash
# Docker-build the strands-decider Lambda image inside the MicroVM.
# 環境変数: VARIANT (lambda | lambda-gpu), PLATFORM (linux/arm64 | linux/amd64), MODEL, COMMIT
# No push. Returns build time and image size.
set -uo pipefail
step() { echo "STEP $* at $(date -u +%FT%TZ)"; }
step "start dockerd"
dnf install -y docker > /dev/null 2>&1
nohup dockerd > /var/log/dockerd.log 2>&1 &
for i in $(seq 1 30); do docker info > /dev/null 2>&1 && break; sleep 1; done
docker info > /dev/null 2>&1 || { echo "dockerd did not start"; tail -n 20 /var/log/dockerd.log; exit 1; }
# Progress indicator: print disk usage and free memory every 60 seconds
( while true; do echo "DF $(date -u +%T) $(df -h / | awk 'NR==2{print $3" used, "$4" avail"}') mem_avail=$(awk '/MemAvailable/{printf "%d MiB", $2/1024}' /proc/meminfo)"; sleep 60; done ) &
DF_PID=$!
step "git clone"
git init -q /src && cd /src \
&& git fetch -q --depth 1 https://github.com/strands-labs/strands-decider "$COMMIT" \
&& git checkout -q FETCH_HEAD || { echo "git fetch failed"; exit 1; }
echo "commit: $(git rev-parse HEAD)"
step "docker build start ($VARIANT, $PLATFORM)"
START=$(date +%s)
docker build --progress=plain --platform "$PLATFORM" \
-f "deploy/$VARIANT/Dockerfile" --build-arg MODEL="$MODEL" -t "strands-$VARIANT" .
CODE=$?
END=$(date +%s)
kill $DF_PID 2>/dev/null
step "docker build end exit=$CODE"
echo "BUILD_SECONDS=$((END - START))"
echo "IMAGE_SIZE=$(docker image inspect "strands-$VARIANT" --format '{{.Size}}' 2>/dev/null || echo none)"
echo "uname -m: $(uname -m) vcpus: $(nproc)"
df -h / | awk 'NR==2{print "disk: "$3" used, "$4" avail"}'
exit $CODE
I built the zip, put it in S3, and created ARM and x86 Images. The architecture is specified with --cpu-configurations: architecture=ARM_64 for the ARM Image and architecture=X86_64 for the x86 Image.
(cd artifacts/microvm && zip -r ../build/microvm.zip Dockerfile app.py jobs)
aws s3 cp artifacts/build/microvm.zip s3://<バケット名>/microvm.zip
aws lambda-microvms create-microvm-image \
--name sfnmvm-arm \
--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/sfnmvm-build \
--egress-network-connectors arn:aws:lambda:ap-northeast-1:aws:network-connector:aws-network-connector:INTERNET_EGRESS \
--hooks file://artifacts/microvm/hooks.json \
--resources minimumMemoryInMiB=4096 \
--additional-os-capabilities ALL \
--cpu-configurations architecture=ARM_64
aws lambda-microvms create-microvm-image \
--name sfnmvm-x86 \
--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/sfnmvm-build \
--egress-network-connectors arn:aws:lambda:ap-northeast-1:aws:network-connector:aws-network-connector:INTERNET_EGRESS \
--hooks file://artifacts/microvm/hooks.json \
--resources minimumMemoryInMiB=4096 \
--additional-os-capabilities ALL \
--cpu-configurations architecture=X86_64
I started creating both Images at the same time, and when I checked with get-microvm-image 2 minutes 45 seconds later, both were CREATED. Start state machine executions only after the Image becomes CREATED.
Verification
Running one job
Running one job can be written with two states: RunJob (runMicrovm.waitForTaskToken) and TerminateMicrovm. RunHookPayload contains the task token issued by Step Functions ($states.context.Task.Token). The heartbeat interval and job specification are combined with the task token into a single JSON string. When the app inside the MicroVM calls SendTaskSuccess with this token, the RunJob state completes and the result is passed to the next state.
asl/job.asl.json
{
"Comment": "MicroVM を起動し、1ジョブを実行して結果を受け取り、終了する (JSONata / SDK 統合のみ)",
"QueryLanguage": "JSONata",
"StartAt": "RunJob",
"States": {
"RunJob": {
"Type": "Task",
"Resource": "arn:aws:states:::aws-sdk:lambdamicrovms:runMicrovm.waitForTaskToken",
"TimeoutSeconds": 900,
"HeartbeatSeconds": 120,
"Arguments": {
"ImageIdentifier": "{% $states.input.imageArn %}",
"ExecutionRoleArn": "{% $states.input.executionRoleArn %}",
"MaximumDurationInSeconds": 3600,
"Logging": {
"CloudWatch": {
"LogGroup": "/aws/lambda-microvms/sfnmvm",
"LogStream": "{% 'sfn-' & $states.context.Execution.Name %}"
}
},
"RunHookPayload": "{% $string({'taskToken': $states.context.Task.Token, 'heartbeatSeconds': 30, 'job': $states.input.job}) %}"
},
"Next": "TerminateMicrovm"
},
"TerminateMicrovm": {
"Type": "Task",
"Resource": "arn:aws:states:::aws-sdk:lambdamicrovms:terminateMicrovm",
"Arguments": {
"MicrovmIdentifier": "{% $states.input.microvmId %}"
},
"Output": "{% $states.input %}",
"End": true
}
}
}
Because the app includes microvmId in the SendTaskSuccess output, terminateMicrovm can specify the target with $states.input.microvmId. The input is the following file.
artifacts/input-g1.json
{"imageArn":"arn:aws:lambda:ap-northeast-1:<アカウントID>:microvm-image:sfnmvm-arm","executionRoleArn":"arn:aws:iam::<アカウントID>:role/sfnmvm-microvm","job":{"script":"info.sh"}}
aws stepfunctions create-state-machine --name sfnmvm-job --type STANDARD \
--role-arn arn:aws:iam::<アカウントID>:role/sfnmvm-sfn \
--definition file://artifacts/asl/job.asl.json
aws stepfunctions start-execution \
--state-machine-arn arn:aws:states:ap-northeast-1:<アカウントID>:stateMachine:sfnmvm-job \
--name g1-run2 --input file://artifacts/input-g1.json
The RunHookPayload recorded in TaskScheduled in the execution history was as follows.
"RunHookPayload": "{\"taskToken\":\"<タスクトークン>\",\"heartbeatSeconds\":30,\"job\":{\"script\":\"info.sh\"}}"
The task token was 648 characters and the whole payload was 713 characters. In the strands-decider build described later, the job specification included environment variables, so the payload became 889 to 893 characters. The RunHookPayload limit of runMicrovm is documented differently: up to 4096 characters in the API reference and up to 16 KB in the user guide. The payload here fits under either limit.
The execution reached SUCCEEDED, and the output was as follows.
{
"microvmId": "<microvmId>",
"script": "info.sh",
"uname": "aarch64",
"exitCode": 0,
"seconds": 7.4,
"tail": "uname -m: aarch64\nkernel: 6.1.189-236.400.amzn2023.aarch64.microvm\nos: Amazon Linux 2023.12.20261120\npython: Python 3.9.25\ncaller: arn:aws:sts::<アカウントID>:assumed-role/sfnmvm-microvm/Lambda-microvmsExecutor-<microvmId の先頭部分>\n/app/jobs/info.sh: line 9: free: command not found\nvcpus: 8 mem: MiB\ndisk: 63G total, 59G avail\n"
}
The caller line shows that the AWS CLI inside the MicroVM ran with the permissions of the MicroVM execution role (sfnmvm-microvm). The mem field is blank because the Image has no free command.
In the execution history, the runMicrovm response (TaskSubmitted) was recorded 0.26 seconds after ExecutionStarted. The MicroVM state at that point was PENDING. TaskSucceeded, upon receiving SendTaskSuccess, came about 9.5 seconds after TaskSubmitted. The whole execution, including terminateMicrovm, took 10.0 seconds from start to end, of which the job script took 7.4 seconds.
Sessions
I built a session, which sends multiple jobs to the same MicroVM, with an Activity. The app receives the Activity ARN in the /run hook and waits with GetActivityTask. The state machine proceeds in this order: runMicrovm, two Task states that use the Activity, then terminateMicrovm. What I verified is a configuration where one execution sends jobs to a single MicroVM that is waiting on the Activity.
The Resource of a Task state that uses an Activity needs a fixed ARN. So I replaced ${ACTIVITY_ARN} in the template asl/session.asl.json with the Activity's ARN. If you don't specify which variables to substitute, envsubst also replaces JSONata's $states. So I limited the substitution to ${ACTIVITY_ARN} as shown below and wrote the result to asl-rendered/session.asl.json.
export ACTIVITY_ARN=$(aws stepfunctions create-activity --name sfnmvm-session --query activityArn --output text)
envsubst '${ACTIVITY_ARN}' < artifacts/asl/session.asl.json > artifacts/asl-rendered/session.asl.json
asl/session.asl.json (template)
{
"Comment": "同じ MicroVM に2つのジョブを送り、2つ目が1つ目のファイルとメモリを読む (Activity)",
"QueryLanguage": "JSONata",
"StartAt": "RunMicrovm",
"States": {
"RunMicrovm": {
"Type": "Task",
"Resource": "arn:aws:states:::aws-sdk:lambdamicrovms:runMicrovm",
"Arguments": {
"ImageIdentifier": "{% $states.input.imageArn %}",
"ExecutionRoleArn": "{% $states.input.executionRoleArn %}",
"MaximumDurationInSeconds": 3600,
"Logging": {
"CloudWatch": {
"LogGroup": "/aws/lambda-microvms/sfnmvm",
"LogStream": "{% 'sfn-' & $states.context.Execution.Name %}"
}
},
"RunHookPayload": "{% $string({'activityArn': '${ACTIVITY_ARN}'}) %}"
},
"Assign": {
"microvmId": "{% $states.result.MicrovmId %}"
},
"Next": "Job1Write"
},
"Job1Write": {
"Type": "Task",
"Resource": "${ACTIVITY_ARN}",
"TimeoutSeconds": 300,
"Arguments": { "op": "write", "value": "written-by-job1" },
"Assign": { "job1": "{% $states.result %}" },
"Next": "Job2Read"
},
"Job2Read": {
"Type": "Task",
"Resource": "${ACTIVITY_ARN}",
"TimeoutSeconds": 300,
"Arguments": { "op": "read" },
"Assign": { "job2": "{% $states.result %}" },
"Next": "TerminateMicrovm"
},
"TerminateMicrovm": {
"Type": "Task",
"Resource": "arn:aws:states:::aws-sdk:lambdamicrovms:terminateMicrovm",
"Arguments": { "MicrovmIdentifier": "{% $microvmId %}" },
"Output": {
"runMicrovmId": "{% $microvmId %}",
"job1": "{% $job1 %}",
"job2": "{% $job2 %}"
},
"End": true
}
}
}
runMicrovm is a normal SDK integration that doesn't use a task token, and it saves the MicrovmId from the response into the variable microvmId with Assign. The first job (write) writes a value to a file and to an in-memory variable, and the second job (read) reads both and returns them.
aws stepfunctions create-state-machine --name sfnmvm-session --type STANDARD \
--role-arn arn:aws:iam::<アカウントID>:role/sfnmvm-sfn \
--definition file://artifacts/asl-rendered/session.asl.json
aws stepfunctions start-execution \
--state-machine-arn arn:aws:states:ap-northeast-1:<アカウントID>:stateMachine:sfnmvm-session \
--name g2-run1 --input file://artifacts/input-g2.json
The input (input-g2.json) has two items: imageArn and executionRoleArn. The output was as follows.
{
"runMicrovmId": "<microvmId>",
"job1": { "op": "write", "microvmId": "<microvmId>", "pid": 1 },
"job2": {
"op": "read",
"microvmId": "<microvmId>",
"pid": 1,
"file": "written-by-job1",
"memory": "written-by-job1"
}
}
The microvmId and pid were the same for both jobs. The second job could read both the file contents and the in-memory value written by the first job.
In the execution history, the time from ActivityScheduled to ActivityStarted was about 2.6 seconds for the first job and about 0.06 seconds for the second. The first includes the time for the MicroVM to start and the app to begin waiting. The whole execution took 3.4 seconds.
ARM and x86 builds
I ran the ARM and x86 MicroVMs in parallel by passing two elements, arm and x86, in the input's targets and setting the Map's MaxConcurrency to 2. Inside the Map state are the same RunJob and TerminateMicrovm as in "Running one job". The Image ARN and the job specification vary per element of targets.
artifacts/input-matrix-hello.json
{"executionRoleArn":"arn:aws:iam::<アカウントID>:role/sfnmvm-microvm","targets":[
{"arch":"arm","imageArn":"arn:aws:lambda:ap-northeast-1:<アカウントID>:microvm-image:sfnmvm-arm","job":{"script":"build-hello.sh","env":{"BUCKET":"<バケット名>","ARCH_LABEL":"arm"}}},
{"arch":"x86","imageArn":"arn:aws:lambda:ap-northeast-1:<アカウントID>:microvm-image:sfnmvm-x86","job":{"script":"build-hello.sh","env":{"BUCKET":"<バケット名>","ARCH_LABEL":"x86"}}}]}
State machine (asl/matrix.asl.json)
{
"Comment": "ARM と x86 の MicroVM を並列に起動し、それぞれでジョブを実行する (2要素の Map)",
"QueryLanguage": "JSONata",
"StartAt": "BuildAll",
"States": {
"BuildAll": {
"Type": "Map",
"MaxConcurrency": 2,
"Items": "{% $states.input.targets %}",
"ItemSelector": {
"executionRoleArn": "{% $states.input.executionRoleArn %}",
"arch": "{% $states.context.Map.Item.Value.arch %}",
"imageArn": "{% $states.context.Map.Item.Value.imageArn %}",
"job": "{% $states.context.Map.Item.Value.job %}"
},
"ItemProcessor": {
"ProcessorConfig": { "Mode": "INLINE" },
"StartAt": "RunJob",
"States": {
"RunJob": {
"Type": "Task",
"Resource": "arn:aws:states:::aws-sdk:lambdamicrovms:runMicrovm.waitForTaskToken",
"TimeoutSeconds": 3000,
"HeartbeatSeconds": 120,
"Arguments": {
"ImageIdentifier": "{% $states.input.imageArn %}",
"ExecutionRoleArn": "{% $states.input.executionRoleArn %}",
"MaximumDurationInSeconds": 3600,
"Logging": {
"CloudWatch": {
"LogGroup": "/aws/lambda-microvms/sfnmvm",
"LogStream": "{% 'sfn-' & $states.context.Execution.Name & '-' & $states.input.arch %}"
}
},
"RunHookPayload": "{% $string({'taskToken': $states.context.Task.Token, 'heartbeatSeconds': 30, 'job': $states.input.job}) %}"
},
"Next": "TerminateMicrovm"
},
"TerminateMicrovm": {
"Type": "Task",
"Resource": "arn:aws:states:::aws-sdk:lambdamicrovms:terminateMicrovm",
"Arguments": { "MicrovmIdentifier": "{% $states.input.microvmId %}" },
"Output": "{% $states.input %}",
"End": true
}
}
},
"End": true
}
}
}
aws stepfunctions create-state-machine --name sfnmvm-matrix --type STANDARD \
--role-arn arn:aws:iam::<アカウントID>:role/sfnmvm-sfn \
--definition file://artifacts/asl/matrix.asl.json
aws stepfunctions start-execution \
--state-machine-arn arn:aws:states:ap-northeast-1:<アカウントID>:stateMachine:sfnmvm-matrix \
--name hello-run1 --input file://artifacts/input-matrix-hello.json
The job run in each MicroVM (jobs/build-hello.sh) builds a small C program with gcc. It checks the architecture with uname -m and readelf, then puts the binary in S3.
| ARM | x86 | |
|---|---|---|
| uname -m | aarch64 | x86_64 |
| readelf Machine | AArch64 | Advanced Micro Devices X86-64 |
| Job duration | 11.2 s | 10.3 s |
Times in the execution history are JST. The two MapIterationStarted events had the same time (22:00:53.418). The runMicrovm TaskSubmitted events were at 22:00:53.644 and 22:00:53.691. The two MicroVM IDs differ. The whole execution took 13.6 seconds (ExecutionStarted 22:00:53.391 to ExecutionSucceeded 22:01:06.942).
docker build inside a MicroVM
With an Image whose additionalOsCapabilities is ALL, everything from installing Docker to docker build and docker run succeeded. The check job docker-check.sh used the one-job state machine sfnmvm-job and ran on an ARM MicroVM. The input is the info.sh input with the job changed to {"script":"docker-check.sh"}. The job installs Docker with dnf install -y docker and starts dockerd in the background. It then builds a Dockerfile based on Amazon Linux 2023 with a single RUN instruction and runs the resulting image with docker run. The docker run output was as follows.
built inside a MicroVM
In the dockerd log, it took about 1.3 seconds from containerd starting to Daemon has completed initialization.
time="2026-11-26T13:01:46.527984063Z" level=info msg="containerd successfully booted in 0.007954s"
time="2026-11-26T13:01:47.824285745Z" level=info msg="Daemon has completed initialization"
The Docker versions were 25.0.14 for the client and 25.0.18 for the daemon, with the overlay2 storage driver. The exit codes of docker build and docker run were 0, and the whole job took 57.2 seconds.
Next, as a build that takes around five minutes, I built the strands-labs/strands-decider Lambda container image inside the MicroVMs. It is an image that bundles the model. The ARM MicroVM handles the CPU version (deploy/lambda, linux/arm64). The x86 MicroVM handles the GPU version (deploy/lambda-gpu, linux/amd64). I did not push the images. The input is as follows.
artifacts/input-matrix-strands.json
{"executionRoleArn":"arn:aws:iam::<アカウントID>:role/sfnmvm-microvm","targets":[
{"arch":"arm","imageArn":"arn:aws:lambda:ap-northeast-1:<アカウントID>:microvm-image:sfnmvm-arm","job":{"script":"strands-build.sh","env":{"VARIANT":"lambda","PLATFORM":"linux/arm64","MODEL":"StrandsAgents/strands-decider-2B-qwen3.5-v1-2610","COMMIT":"6d85079caf1f1906ebb0f1370b56ef28ba7aa93e"}}},
{"arch":"x86","imageArn":"arn:aws:lambda:ap-northeast-1:<アカウントID>:microvm-image:sfnmvm-x86","job":{"script":"strands-build.sh","env":{"VARIANT":"lambda-gpu","PLATFORM":"linux/amd64","MODEL":"StrandsAgents/strands-decider-2B-qwen3.5-v1-2610","COMMIT":"6d85079caf1f1906ebb0f1370b56ef28ba7aa93e"}}}]}
The job script (jobs/strands-build.sh) is in the collapsed "Job scripts" section in the "Preparation" chapter. I used the sfnmvm-matrix state machine from the previous section as is and only swapped the input.
| ARM (deploy/lambda, CPU version) | x86 (deploy/lambda-gpu, GPU version) | |
|---|---|---|
| docker build duration | 316 s | 270 s |
| Image size | 2,748,143,503 bytes (about 2.7 GB) | 11,875,327,236 bytes (about 11.9 GB) |
| Peak disk usage (recorded every 60 s) | 9.2G | 17G |
| Minimum free memory (recorded every 60 s) | 11,405 MiB | 11,053 MiB |
| Result | exitCode 0 | exitCode 0 |
The whole execution ran from 22:11:16.233 to 22:18:11.920, 6 minutes 55.7 seconds.
Checking progress and execution time limits
State transitions and inputs/outputs can be checked in the execution history from get-execution-history. Heartbeats sent by the app are not recorded as events in the execution history.
Progress during the build can be checked in the CloudWatch Logs log stream specified in runMicrovm's Logging. I named the stream from the execution name and architecture, like sfn-<execution name>-arm. The STEP lines and DF lines (disk usage and free memory) output by the job script and the heartbeat-sending logs output by the app appear in chronological order. Log times are UTC. Here is an excerpt from the ARM log.
{"ts": "2026-11-26T13:11:17.763018+00:00", "event": "run hook", "microvmId": "<microvmId>", "payloadKeys": ["heartbeatSeconds", "job", "taskToken"]}
STEP start dockerd at 2026-11-26T13:11:19Z
{"ts": "2026-11-26T13:11:48.687549+00:00", "event": "heartbeat sent"}
STEP git clone at 2026-11-26T13:12:10Z
DF 13:12:10 1.8G used, 58G avail mem_avail=15568 MiB
STEP docker build start (lambda, linux/arm64) at 2026-11-26T13:12:15Z
{"ts": "2026-11-26T13:12:18.741682+00:00", "event": "heartbeat sent"}
{"ts": "2026-11-26T13:12:48.826280+00:00", "event": "heartbeat sent"}
DF 13:13:11 4.2G used, 56G avail mem_avail=14712 MiB
DF 13:16:11 9.2G used, 51G avail mem_avail=11405 MiB
STEP docker build end exit=0 at 2026-11-26T13:17:31Z
{"ts": "2026-11-26T13:18:11.638723+00:00", "event": "job done", "exitCode": 0, "seconds": 413.8}
A MicroVM's idle determination is based on inbound traffic through the MicroVM's endpoint. I did not specify idlePolicy. Even during the build, with no inbound traffic, the state stayed RUNNING after PENDING and never became SUSPENDED.
The specified maximums are one year for a Standard execution and 28,800 seconds (8 hours) for a MicroVM's MaximumDurationInSeconds. For long jobs, the MicroVM reaches its limit first.
Summary
The flow from starting a Lambda MicroVM through running one job to ending it could be written in a Standard state machine using Step Functions SDK integrations.
The advantage of the durable functions extension is that you can write orchestration flexibly in TypeScript or Python code. If managing Lambda code and runtimes becomes a concern, consider Step Functions too, which lets you build orchestration from a state machine definition instead of code.




