AWS Lambda Managed Instances
AWSOfficialPublished by AWS
- Skill
- Tool integration
- Cloud and DevOps
- Apache-2.0
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides technical guidance for using AWS Lambda Managed Instances (LMI), which allows Lambda Event Functions to run on EC2 instances within a user's account. It covers the assessment, configuration, and migration process, including how to manage provisioning, scaling, and cost comparisons. The skill addresses specific requirements for long-running asynchronous and event-source-mapping workloads, including support for function timeouts up to 90 minutes.
What it does
- Assesses workload suitability for LMI versus standard Lambda Event Functions.
- Provides configuration steps for instance sizing, memory-to-vCPU ratios, and scaling controls.
- Details migration patterns for concurrency safety across different runtimes.
- Explains how to enable SOCI lazy loading for container image functions.
- Outlines infrastructure setup including IAM roles and VPC requirements.
- Provides troubleshooting steps for common deployment and scaling issues.
When to use it
- When evaluating if a workload should move from standard Lambda to EC2-backed instances.
- When needing to extend function execution duration up to 90 minutes for asynchronous or ESM tasks.
- When optimizing costs for steady-state workloads using Savings Plans or Reserved Instances.
- When requiring specific instance types or hardware configurations for compute-intensive tasks.
- When addressing cold start concerns through provisioned capacity.
Advantages
- Enables longer execution times up to 90 minutes for specific event sources.
- Allows use of EC2 pricing models like Savings Plans and Reserved Instances.
- Provides full VPC control and access to specific EC2 instance families.
- Eliminates cold starts for provisioned capacity.
- Supports multi-concurrency execution environments for improved resource utilization.
Usage examples
- “Is my workload a good candidate for Lambda Managed Instances?”
- The agent will guide you through an assessment of your traffic patterns, duration requirements, and concurrency needs to determine if LMI is a suitable fit.
- “How do I configure my function to run for 60 minutes?”
- The agent will explain how to set the function timeout to 3600s and ensure your asynchronous or ESM invocation source supports the extended duration.
- “How can I reduce startup time for my large container image?”
- The agent will provide instructions on creating and pushing a SOCI index to enable lazy loading for your container image.
- “What are the concurrency settings for a Python-based LMI function?”
- The agent will provide the recommended PerExecutionEnvironmentMaxConcurrency settings based on whether your workload is I/O-bound or CPU-bound.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/aws/aws-lambda-managed-instances/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip aws-lambda-managed-instances.zip -d .agents/skills
Documentation by AWS
AWS Lambda Managed Instances (LMI)
Runs Lambda Event Functions on EC2 instances in the user's account while AWS manages provisioning, patching, scaling, routing, and load balancing. Combines Lambda's developer experience with EC2's pricing and hardware options.
Works best with the AWS MCP server for sandboxed CLI execution and audit logging. All guidance also works with standard AWS CLI or SAM CLI.
Note: Confirm regional availability, quotas, and instance type offerings against current AWS documentation before production deployment.
Quick Decision: Is LMI Right for This Workload?
| Signal | LMI is a strong fit | Lambda Event Functions are better |
|---|---|---|
| Traffic | Steady, predictable, 50M+ req/mo | Bursty, unpredictable, long periods of no traffic |
| Duration | Long-running asynchronous/ESM jobs that exceed 15 min (up to 90 min on LMI): ETL/data processing, media transcoding, ML inference, financial calc, web scraping | Short invocations; synchronous work needing >15 min (not supported on any Lambda) |
| Cost | Duration-heavy spend at scale | Low or sporadic invocations |
| Cold starts | Unacceptable (LMI eliminates for provisioned capacity) | Tolerable |
| Compute | Latest CPUs, specific families, high network bandwidth, GPU requirements | Lambda Event Functions memory/CPU sufficient |
| Isolation | Dedicated EC2 instances in your account, full VPC control | Shared Firecracker micro-VMs acceptable |
| Scale-to-zero | Does not scale to zero but can create custom schedules with AWS provided solutions | Required (pay nothing when idle) |
| Code readiness | Thread-safe (Node.js/Java/.NET) or any Python code | Non-thread-safe code, expensive to change |
Routing
Read ONLY the single reference file that matches the user's task. Do not preload multiple references.
| User need | Action |
|---|---|
| Cost comparison, pricing analysis, Savings Plans, Reserved Instances | Read cost-comparison.md |
| Instance types, memory sizing, vCPU ratios, scaling tuning, capacity provider config, SOCI lazy loading for large container images | Read configuration-guide.md |
| Thread safety, concurrency model, code review checklist, multi-concurrency readiness | Read thread-safety.md |
| Before/after code examples, runtime-specific migration, connection pooling | Read migration-patterns.md |
| IAM roles, VPC setup, CLI commands, SAM template, CDK example | Read infrastructure-setup.md |
| Errors, throttling, debugging, stuck deployments | Read troubleshooting.md |
Troubleshooting quick facts (always mention when diagnosing issues):
Capacity provider stuck in CREATING → most common cause is private subnets missing a NAT gateway route (instances need outbound internet for image pull and Lambda service communication)
Function not scaling → check that a version is published (PublishToLatestPublished: true)
Memory errors → LMI minimum is 2048 MB
Workflow
Step 1: Assess the Workload
Gather these signals before recommending:
Traffic pattern: Steady vs bursty? Requests per second?
Current costs: Monthly Lambda spend? Existing Savings Plans?
Runtime: Node.js, Java, .NET, or Python?
Memory/CPU: How much memory? CPU-bound or I/O-bound?
Execution duration: Average and P99?
Concurrency readiness: Thread safety? Shared
/tmppaths? Per-invocation DB connections?VPC: Already in a VPC? Private resource access needed?
Long-running asynchronous/ESM jobs that exceed 15 min are a positive fit — LMI supports a function timeout up to 90 min (5400s) for asynchronous and event-source-mapping invocations (ETL/data processing, media transcoding, ML inference, financial calc, web scraping). Duration is the key differentiator here, not just cost.
When recommending LMI, ALWAYS mention: minimum 3 execution environments for AZ resiliency (cannot go below 3 in production).
Step 2: Build the Cost Comparison
REQUIRED: Present a cost comparison before recommending LMI.
Rule of thumb: LMI becomes cost-competitive at 50-100M+ req/month with steady traffic. Use the LMI Pricing Calculator for accurate comparisons.
Step 3: Configure the Deployment
Instance families (400+ types, .large and up): C-series (compute), M-series (general), R-series (memory). ARM (Graviton) for best price-performance.
When using Graviton instances, MUST set
Architectures: [arm64]in the function configuration to match.Memory-to-vCPU ratios: 2:1 (compute), 4:1 (general, default), 8:1 (memory). Min 2 GB, max 32 GB.
Multi-concurrency per-vCPU maximums: Node.js 64, Java 32, .NET 32, Python 16. These are system caps — the actual setting is PerExecutionEnvironmentMaxConcurrency (per execution environment, not per vCPU).
For I/O-bound workloads: use the runtime default or higher PerExecutionEnvironmentMaxConcurrency (e.g., 10 for Node.js) since each request uses minimal CPU while waiting on network.
For CPU-bound workloads: set PerExecutionEnvironmentMaxConcurrency to 1-2 per vCPU since each request saturates CPU.
Scaling: MinExecutionEnvironments (default 3), MaxVCpuCount (optional, default 400 — set explicitly as best practice), TargetResourceUtilization.
Function timeout up to 5400s (90 min) — set via the existing
Timeoutfield (CLIupdate-function-configuration --timeout 5400, SAM/CFNTimeout: 5400, or console). Uses the existingTimeoutfield — no separate API, property, tag, or code change is required. Applies to asynchronous and ESM invocations only; synchronous and On-Demand invocations stay capped at 15 min (even ifTimeoutis higher;GetFunctionConfigurationstill reports the configured value). The Init phase is still capped at 15 min. Durable Functions: each step can run up to 90 min; a multi-step workflow up to 1 year.
Step 4: Migrate the Code
Review code for concurrency safety. LMI runs multiple invocations concurrently per execution environment:
Python: Process-based isolation — globals are NOT shared. No thread-safety changes needed. Focus on
/tmpconflicts and memory sizing.Node.js: Worker threads — globals shared within a worker. Requires async safety.
Java/.NET: OS threads/Tasks — handler shared across threads. Requires full thread safety.
Step 5: Set Up Infrastructure
Create two IAM roles: execution role (for the function) and operator role (for capacity provider EC2 management)
Configure VPC with subnets across 3+ AZs
Create capacity provider with VPC config and scaling limits
Create a new function with the capacity provider attached
Publish a version (triggers instance provisioning)
Step 6: Validate and Cut Over
Deploy to a non-production environment first
Monitor CloudWatch: CPU utilization, memory, concurrency, throttle rate
Gradual traffic shift at the invoking service or routing layer (10% → 50% → 100%)
Compare costs after 1-2 weeks of production data
Decommission the Lambda Event Function once stable
Best Practices
Pricing (always mention when discussing costs)
Three components: EC2 instance hours + 15% management fee + $0.20/1M requests
Savings Plans: Compute Savings Plans apply to the EC2 portion (up to 60-72% discount)
The 15% fee is charged on top of EC2 cost for AWS managing provisioning, patching, scaling, lifecycle
Scaling (always mention when discussing scaling or traffic)
LMI absorbs a 50% traffic spike immediately and doubles capacity within 5 minutes — if traffic more than doubles faster, requests throttle
Lambda Event Functions burst to 3000 instantly — LMI cannot match this
Pre-warm with MinExecutionEnvironments before known spikes
MaxVCpuCount (default 400) — set explicitly as a cost ceiling
Shape: Reduce MinExecutionEnvironments to lower capacity during off-hours (minimum 3 for AZ resiliency)
Large container images (SOCI lazy loading)
For container image functions, the image pull is the largest part of the time between publishing a version or scaling out and the first invocation. Seekable OCI (SOCI) lets Lambda start the execution environment before the whole image is downloaded and fetch files on demand as the function reads them. The benefit is largest for multi-GB images, such as images that package ML frameworks.
Enable it by pushing a SOCI index to Amazon ECR next to the image, pointing the function's image URI at the SOCI-indexed tag, and publishing a version. No other function configuration changes. Steps in configuration-guide.md.
Import libraries and read files in init code, not in the handler. A file first read in the handler is fetched during that invocation and adds to its duration; Lambda does not download the rest of the image in the background.
Recommend testing with and without SOCI to compare startup time and invocation duration for the workload.
Instance Sizing
1 vCPU + 1 GB reserved per instance for OS overhead (not available to your function)
Usable capacity = total - overhead
Configuration
Start with 4:1 ratio and runtime default concurrency
Use ARM (Graviton) unless x86 dependencies exist
Let Lambda choose instance types unless specific hardware needed
Set MaxVCpuCount to control cost ceiling
Never set MinExecutionEnvironments below 3 (breaks AZ resiliency)
Migration
Start with I/O-heavy functions (benefit most from multi-concurrency)
Review code for concurrency safety before attaching to capacity provider
Shift traffic gradually at the invoking service or routing layer
Include request IDs in all log statements
Initialize DB pools and SDK clients outside the handler
Operations
Set CloudWatch alarms on throttle rate > 1% and CPU > 80%
Plan for 14-day instance rotation (automatic)
Never manually terminate LMI EC2 instances (delete the capacity provider instead)
Always publish a version — unpublished functions cannot run on LMI
Long-duration invocations (asynchronous/ESM up to 90 min)
SQS: the queue visibility timeout MUST be ≥ the function timeout (≥ 5400s for a 90-min function). The ESM validates this on create and update — but once the ESM exists, the SQS visibility timeout and the function timeout can each be changed independently (outside the ESM API), which bypasses the check and can reintroduce a mismatch, causing messages to reappear and duplicate invokes.
Kinesis / DynamoDB Streams: enable partial batch failure reporting (
ReportBatchItemFailures) and tune the max batching window and parallelization factor — otherwise one failed record retries the whole batch, re-running up to ~80 min of already-completed work.Asynchronous invocations: failed or timed-out invocations follow the retry policy (up to 2 retries by default), then route to the DLQ / on-failure destination.
Not all ESM sources qualify: Amazon MQ and Amazon DocumentDB ESM remain limited to 15 min; only SQS, Kinesis, and DynamoDB Streams ESM (and asynchronous invocations) get 90 min.
Observability is unchanged: CloudWatch, CloudTrail (one Invoke event on completion/timeout), and X-Ray (single trace) behave identically. Use X-Ray sub-segments to find slow phases near the 90-min limit.
Long-running networking (functions now run for tens of minutes)
NAT Gateway idle timeout — send periodic keep-alive packets on long-lived TCP connections through a NAT Gateway.
Idle connection timeouts (RDS, ElastiCache, external APIs) — add connection health checks / reconnection logic for connections that may go idle mid-computation.
DNS TTL — re-resolve external hostnames periodically; the AWS SDK does this, but custom HTTP clients may cache beyond TTL.
Credentials — rely on the execution role's ephemeral credentials (automatically refreshed by the runtime). For non-IAM secrets (DB passwords, API keys), retrieve them from AWS Secrets Manager or SSM Parameter Store with SDK caching and periodic refresh; never embed long-lived credentials in code or environment variables.
Limits Quick Reference
| Resource | Limit |
|---|---|
| Memory | 2 GB min, 32 GB max |
| Asynchronous/ESM invoke timeout | 90 min (5400s), via the existing Timeout field |
| Sync + On-Demand invoke timeout | 15 min |
| Init phase | 15 min |
| ESM sources capped at 15 min | Amazon MQ, Amazon DocumentDB (SQS/Kinesis/DynamoDB Streams get 90 min) |
| Execution environments | 3 minimum (MinExecutionEnvironments, AZ resiliency) |
| Instance lifespan | 14 days (auto-replaced) |
| Concurrency/vCPU | 64 (Node.js), 32 (Java/.NET), 16 (Python) |
| Runtimes | Node.js 22+, Java 21+, .NET 8+, Python 3.13+, Rust (provided.al2023) |
| Instance families | C, M, R (.large and up) |
| Scaling | Burst headroom equals unused capacity from TargetResourceUtilization; new instances launch within minutes |
| SOCI lazy loading | Container image functions on LMI only (not Lambda Event Functions on-demand); SOCI Index Manifest v2 only; image index with exactly one OCI image manifest plus the SOCI index (no multi-architecture indexes) |
Security Considerations
Operator role scoping: Add
aws:SourceAccountandaws:SourceArnconditions to trust policies to prevent confused deputy attacks.VPC egress: Scope security group egress to VPC endpoint security groups or AWS prefix lists rather than 0.0.0.0/0.
Credentials: Use AWS Secrets Manager or Parameter Store for database credentials — never environment variables for secrets.
Encryption: Enable SQS SSE, CloudWatch Logs encryption (KMS), and S3 default encryption for any data at rest.
Logging: Set CloudWatch Log group retention policies. Avoid logging PII or credentials. Enable CloudTrail data events for Lambda.
Instance rotation: The 14-day automatic rotation ensures security patches are applied without manual intervention.
References: Lambda Security Best Practices, IAM Best Practices
Files
| File | Content |
|---|---|
| cost-comparison.md | Pricing analysis, break-even calculations, Savings Plans/RI impact |
| configuration-guide.md | Instance selection, memory ratios, scaling tuning, capacity provider config, SOCI lazy loading |
| thread-safety.md | Concurrency model per runtime, code review checklist, Powertools compatibility |
| migration-patterns.md | Before/after code by runtime, connection pooling, gradual cutover |
| infrastructure-setup.md | IAM roles, VPC setup, SAM templates, CLI commands |
| troubleshooting.md | Common errors, throttling, debugging, stuck deployments |
Files
- ATTRIBUTION.mdAdded by AutoGineer946 B
- LICENSELicence file added by AutoGineer9.9 KiB
- NOTICELicence file added by AutoGineer67 B
- SKILL.md16.1 KiB
- assets/sqs-processor/template.yaml3.3 KiB
- references/configuration-guide.md6.3 KiB
- references/cost-comparison.md924 B
- references/infrastructure-setup.md6.3 KiB
- references/migration-patterns.md4.2 KiB
- references/thread-safety.md5.4 KiB
- references/troubleshooting.md3.4 KiB
LICENSE
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs an MCP server, Needs an API key
Security
No issues found by our static scan· No issues found
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Published by
- AWS
- Publisher
- AWS (Official)
- Source
- aws/agent-toolkit-for-aws · skills/specialized-skills/serverless-skills/aws-lambda-managed-instances · commit 0a218f8
- Licence
- Apache License 2.0 (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- NOTICE (added by AutoGineer from NOTICE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by AWS or AWS.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download aws-lambda-managed-instances.zip