Lambda MicroVM Lifecycle Hooks: A Primer for Lambda Function Developers
Written for readers who know Lambda functions and are new to MicroVMs.
Lambda MicroVMs run your own long-lived server inside a Firecracker VM that launches from a snapshot and can suspend and resume. Lifecycle hooks (
/run , /suspend , /resume , /terminate , plus build-time /ready and /validate ) are the HTTP endpoints Lambda calls to tell your app what's happening. This article maps the hook model to what you already know from Lambda functions, then shows a working example.If you've built on Lambda functions, you already have a mental model: you write a handler, Lambda calls it with an event, and you return a response. You never think about when the environment starts or stops.
Lambda MicroVMs work differently. You get a long-lived, isolated Firecracker VM, up to 8 hours, that runs your own server. It can be suspended when idle and resumed later with memory and disk preserved. Because of that, you need a way to know when these things happen. Lifecycle hooks are how Lambda tells your application: "you just started," "you're about to be frozen," "you're back," or "you're about to be deleted."
This article covers what hooks are, how they differ from the handler model, and a minimal working example.
The mental shift: from handlers to a server with lifecycle events
Lambda function | Lambda MicroVM |
|---|---|
Lambda invokes your handler per event | You run an HTTP server; callers hit the MicroVM's own endpoint |
Environment lifecycle is invisible | You're notified of lifecycle events through hooks |
Cold start runs your init code | Launch restores a pre-built snapshot, so init code does not re-run |
Don't rely on state between invocations | State in memory and on disk is preserved across suspend/resume |
Lambda scales concurrency for you | You call run-microvm per session or tenant; nothing load-balances across MicroVMs |
~15 minute max | Up to 8 hours total, running plus suspended |
One shared endpoint | One dedicated endpoint per MicroVM |
The row that trips people up is the cold start. Lambda builds your image into a Firecracker snapshot: it runs your Dockerfile, starts your app, waits for it to be ready, then captures disk and memory. Every MicroVM launches from that snapshot, so your startup code already ran at build time. Anything unique generated then (a UUID, a secret, a random seed) is shared by every MicroVM from that image version. Hooks are how you fix that and handle everything else that happens afterward.
If you've used Lambda SnapStart, this will feel familiar: SnapStart also restores from a snapshot and gives you a restore hook to re-randomize unique values. MicroVM hooks are the same idea extended across a full suspend/resume lifecycle rather than just cold start.
What a hook is
A hook is just an HTTP endpoint your app exposes. Lambda sends a
POST to this path on the port you configure:/aws/lambda-microvms/runtime/v1/<hook-name>Lambda uses the HTTP status code to decide whether the hook worked. Return
200 for success.There are two groups of hooks.
Build-time hooks run while Lambda creates the image, before the snapshot is used:
-
/ready: Lambda calls this after your app starts. Return503("not yet") and Lambda retries. Return200and Lambda takes the snapshot. The timeout is configurable from 1 to 3600 seconds.
-
/validate: Lambda calls this on a fresh MicroVM started from the finished image, to confirm the app works after a restore. Same200/503semantics. You can also send mock traffic here so Lambda learns which parts of the snapshot you touch and prefetches them at launch.
Runtime hooks run during a MicroVM's life:
Hook | When it fires | What you'd do there |
|---|---|---|
/run | After launch from snapshot | Generate unique IDs and secrets, load per-tenant config, warm up |
/suspend | Before the MicroVM suspends | Flush writes, close connections |
/resume | After memory and disk are restored | Re-open connections, refresh credentials, validate state |
/terminate | Before final termination | Flush data, notify other systems, clean up |
The lifecycle, step by step
run-microvm | v [PENDING] --/run 200--> [RUNNING] ----terminate / max duration----> [TERMINATING] --/terminate--> [TERMINATED] | ^ ^ idle / suspend | | traffic + /resume 200 | v | | [SUSPENDED] ---------suspended duration-----------/-
run-microvm: The MicroVM goesPENDING. Lambda restores the snapshot and calls/run.
-
RUNNING: After/runreturns 200, the endpoint starts forwarding traffic. Until then, requests are not forwarded to your app.
- Idle: Once the idle policy's
maxIdleDurationSecondspasses with no traffic (or you callsuspend-microvm), the MicroVM goesSUSPENDING. Lambda calls/suspend, checkpoints memory and disk, and the MicroVM reachesSUSPENDED. No compute charges accrue while suspended, but you still pay snapshot storage.
- Traffic returns: With
autoResumeEnabled=true, Lambda holds the incoming request while it restores state and calls/resume. The MicroVM returns toRUNNING, then your app gets the request. Callingresume-microvmhas the same effect. If resume fails, the caller gets a502 Bad Gateway.
- Done:
terminate-microvm, hittingmaximumDurationInSeconds, or exceedingsuspendedDurationSecondsleads toTERMINATING. Lambda calls/terminate, then the MicroVM isTERMINATED. This is final.
Two details matter in practice:
-
/terminatedoes not fire on suspend. Put pre-suspend cleanup in/suspend.
- During
/resume, the MicroVM is stillSUSPENDED. It becomesRUNNINGonly after the hook returns 200.
Where hooks matter most: interactive sessions
Lambda MicroVMs suit interactive sessions: a coding agent holding a multi-turn conversation, a per-user notebook or dev environment, or a chat session that keeps context between messages. In these cases a person (or an agent) comes and goes, and the environment has to feel like it was waiting for them. Each MicroVM has its own endpoint and supports HTTP/2, WebSockets, gRPC, and SSE, so a user can hold a live, streaming connection to one isolated environment. When they step away, the idle policy suspends it and you stop paying for compute (snapshot storage still applies). When they return, the next request triggers an auto-resume, and memory and disk are restored from the suspend checkpoint.
Lifecycle hooks are what make that handoff safe. Restored memory and disk are not the whole story: network connections, auth tokens, and time-based state can all be stale after a pause.
/suspend closes what shouldn't outlive the pause, /resume re-establishes it before the user's request arrives, and /run gives each new session its own identity. Without them, an interactive session would resume with dead connections or, worse, share identity with every other session from the same image. Plan for the latency of the first request after a long pause, since it includes the restore plus your /resume hook, and handle the 502 a failed resume returns.Hook configuration and timeouts
You configure hooks when you create or update the image, in a
--hooks JSON object. Build-time hooks ( ready , validate ) and runtime hooks ( run , suspend , resume , terminate ) live under separate keys, and port (the port your app listens on for hook requests) is required whenever any hook is configured:aws lambda-microvms create-microvm-image \ --name my-first-image \ --base-image-arn arn:aws:lambda:us-east-1:aws:microvm-image:al2023-1 \ --build-role-arn arn:aws:iam::123456789012:role/MicroVMBuildRole \ --code-artifact '{"uri":"s3://my-bucket/microvm-images/my-first-image/code-artifact.zip"}' \ --hooks '{ "port": 9000, "microvmImageHooks": { "ready": "ENABLED", "readyTimeoutInSeconds": 60 }, "microvmHooks": { "run": "ENABLED", "runTimeoutInSeconds": 5, "suspend": "ENABLED", "suspendTimeoutInSeconds": 5, "resume": "ENABLED", "resumeTimeoutInSeconds": 5, "terminate": "ENABLED", "terminateTimeoutInSeconds": 5 } }'Runtime hook timeouts range from 1 to 60 seconds each; build-time hook timeouts (
/ready , /validate ) go up to 3600 seconds. Because hooks are part of the image, changing them means a new image version build, not a runtime change.Failure behavior to know about: if
/run fails or times out, the MicroVM can go straight to TERMINATING without ever reaching RUNNING . Handle errors inside your hooks (return a status code rather than letting the connection drop), and check stateReason in the get-microvm response when something terminates unexpectedly.Passing per-MicroVM data into /run
In Lambda you'd read the event. Here, the closest equivalent is the run hook payload. When you launch a MicroVM you can pass a string of up to 16 KB:
aws lambda-microvms run-microvm \ --image-identifier arn:aws:lambda:us-east-1:123456789012:microvm-image:my-image \ --image-version 1.0 \ --run-hook-payload '{"tenantId":"acme","sessionId":"s-123"}' \ --maximum-duration-in-seconds 14400Lambda delivers it as the JSON body of the
/run call, and adds the MicroVM's ID:{ "microvmId": "mvm-01234567-abcd-ef01-2345-6789abcdef01", "runHookPayload": "{\"tenantId\":\"acme\",\"sessionId\":\"s-123\"}"}Note that
runHookPayload is a string. If you pass JSON, parse it yourself, and handle the case where it isn't valid JSON. Environment variables, by contrast, are fixed at build time and shared by every MicroVM from that image, so use the payload for anything tenant-specific. Pass secret references (such as a Secrets Manager path) rather than raw secrets.A minimal example
A MicroVM runs your app inside a container, so it needs a Dockerfile. Run your application and your hooks on different ports, and expose both. Keeping hooks off the app port lets you scope auth tokens to the app port only, so callers can't reach your lifecycle endpoints through the public endpoint.
# DockerfileFROM public.ecr.aws/lambda/microvms:al2023-minimalRUN dnf install -y python3 && dnf clean allCOPY app.py .EXPOSE 8080 9000CMD ["python3", "app.py"]# app.py — standard library onlyimport jsonimport secretsimport threadingfrom http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
APP_PORT, HOOK_PORT = 8080, 9000HOOK_PREFIX = "/aws/lambda-microvms/runtime/v1/"
# Shared, snapshot-safe state. session_id MUST be set in /run, not here,# or every MicroVM from this image would share one value.state = {"ready": False, "session_id": None, "tenant": None}
def warm_up(): # Build time: load models, prime caches. Runs once, before the snapshot. state["ready"] = True
class Base(BaseHTTPRequestHandler): def _reply(self, code, body=b""): self.send_response(code) self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body)
class AppHandler(Base): def do_GET(self): # Normal application traffic on APP_PORT. self._reply(200, json.dumps({"session": state["session_id"]}).encode())
class HookHandler(Base): def do_POST(self): length = int(self.headers.get("Content-Length", 0)) raw = self.rfile.read(length) if length else b"" hook = self.path.removeprefix(HOOK_PREFIX) try: if hook == "ready": # 503 until warm_up finishes; Lambda retries until it returns 200. return self._reply(200 if state["ready"] else 503) if hook == "run": body = json.loads(raw or b"{}") state["session_id"] = secrets.token_hex(16) # CSPRNG, per MicroVM payload = body.get("runHookPayload") try: state["tenant"] = json.loads(payload) if payload else None except json.JSONDecodeError: state["tenant"] = {"raw": payload} return self._reply(200) if hook in ("validate", "suspend", "resume", "terminate"): # Add your own logic per hook (close/reopen connections, flush, etc.). return self._reply(200) return self._reply(404) except Exception: # Fail with a status code; never drop the connection, or /run may # time out and send the MicroVM straight to TERMINATING. return self._reply(500)
if __name__ == "__main__": threading.Thread(target=warm_up).start() # keeps the 503 path real threading.Thread( target=ThreadingHTTPServer(("0.0.0.0", HOOK_PORT), HookHandler).serve_forever, daemon=True, ).start() ThreadingHTTPServer(("0.0.0.0", APP_PORT), AppHandler).serve_forever()The key point is that
warm_up() runs once at build time, while session_id is generated in /run . If you generated it at module load, every MicroVM would share the same ID.Rules of thumb for Lambda developers
- Move per-instance setup out of init and into
/run. Anything that must be unique (IDs, tokens, keys, seeds, tenant config) goes there, using a CSPRNG for randomness.
- Assume connections go stale across suspend. AWS SDK clients typically recover on their own, but custom sockets and DB pools may not. Close them in
/suspendand re-open or validate them in/resume.
- Bind hooks to
0.0.0.0. Lambda calls them over the network, so alocalhost-only listener is unreachable. Remember toEXPOSEboth the app and hook ports in your Dockerfile.
- Return 503 fast in
/readyand/validate. Don't hold the request open waiting. If the timeout elapses with a request held open, the build ends.
- Keep hooks quick. Runtime hook timeouts are capped at 60 seconds, and a slow
/resumeadds latency to the first request after an auto-resume. (/readyand/validateallow up to 3600 seconds.)
- Persist important data as you go.
/terminateis bounded by a short timeout (up to 60 seconds) and only runs on final termination, not on suspend, so don't treat it as your only chance to save state.
- Set cost guardrails. Use
maxIdleDurationSecondsso idle MicroVMs suspend,suspendedDurationSecondsso they eventually terminate, andmaximumDurationInSecondsas a hard cap.
- Keep the snapshot small. Remove build-time dependencies and temp files before the snapshot is captured, which helps launch and resume times.
Quick mapping if you're coming from Lambda functions
- Init code outside the handler → build-time startup, plus
/ready
- Re-randomizing unique values after restore (SnapStart) →
/runand/resume
- Per-invocation setup from the event →
/runwithrunHookPayload
- Graceful freeze before idle →
/suspend
- Restoring after a freeze →
/resume
- Shutdown extension / SIGTERM handling →
/terminate
Debugging tips
- Readiness is eventually consistent.
get-microvmstate can lag reality. Decide a MicroVM is ready by connecting to its endpoint, not by polling the API.
- Logs need an execution role. Application stdout only reaches CloudWatch when you run the MicroVM with an execution role. Without one, you're debugging blind.
- Check
stateReason. When a MicroVM terminates unexpectedly, theget-microvmresponse carries the reason there.
Where to go next
- Running and using MicroVMs : launch parameters, idle policy, and the hook interface
- MicroVM images : build-time hooks and snapshot compatibility
- Core concepts : states and transitions
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article