PluginWorks in Claude CodeCurrent
Aws serverless
Design, build, deploy, test, and debug serverless applications with AWS Serverless services.
0
Try it
See what this would do for you. No sign-up needed.
Runs shell commands (hooks)
This plugin runs commands on your computer when Claude Code reaches certain events. Read its hooks before you install it.
Install in Claude Code
Run these in Claude Code, in order. The first adds the marketplace, the second installs the plugin.
Step 1
/plugin marketplace add anthropics/claude-plugins-official
Step 2
/plugin install aws-serverless@claude-plugins-official
Review commands before running them. Promptu never runs code on your machine or pushes changes to your repo.
What's inside
7 skills
- api-gateway
- aws-lambda-durable-functions
- aws-lambda-managed-instances
- aws-lambda-microvms
- aws-lambda
- aws-serverless-deployment
- aws-step-functions
1 hook
1 MCP server
Security scan
Passed
Promptu's text scan of the files it could read didn't match any known risky patterns. It doesn't run the plugin, and a clean scan doesn't mean the plugin is safe.
Automated pattern check of 12 file(s) found nothing risky. Not a full audit.
Details
## skills/api-gateway/SKILL.md
---
name: api-gateway
description: >
Build, manage, and operate APIs with Amazon API Gateway (REST, HTTP, and WebSocket).
Triggers on phrases like: API Gateway, REST API, HTTP API, WebSocket API, custom domain, Lambda authorizer, usage plan, throttling, CORS, VPC link, private API.
Also covers troubleshooting API Gateway errors (4xx, 5xx, timeout, CORS failures) and IaC templates containing API Gateway resources.
For general REST API design unrelated to AWS, do not trigger.
metadata:
tags: [api-gateway, serverless, aws, rest-api, http-api, websocket]
---
# Amazon API Gateway Development
Expert guidance for building, managing, governing, and operating APIs with Amazon API Gateway. Covers REST APIs (v1), HTTP APIs (v2), and WebSocket APIs.
## How to Use This Skill
When answering API Gateway questions:
1. Read the relevant reference file(s) before responding, do not rely solely on this summary
2. For tasks spanning multiple concerns (e.g., "private API with mTLS and custom domain"), read all relevant references
3. When the user needs IaC templates, consult `references/sam-cloudformation.md` or `references/sam-service-integrations.md` and provide complete, working SAM/CloudFormation YAML
4. Always mention relevant pitfalls and limits that affect the user's design
## Quick Decision: Which API Type?
Choose the right API type first. This decision affects every downstream choice.
**REST API** is the full-featured API management platform for enterprises. It provides the governance, security, monetization, and operational controls that organizations need to build, publish, and manage APIs at scale, including usage plans with per-consumer throttling and quotas, API keys, request validation, WAF integration, resource policies, caching, canary deployments, and private endpoints.
**HTTP API** is the lightweight, low-cost proxy optimized for simpler API workloads. It offers ~70% lower cost and lower latency but trades away the API management features. Choose HTTP API when you need a fast, lightweight proxy to Lambda or HTTP backends and don't require the enterprise controls above.
| Factor | REST API (v1) | HTTP API (v2) | WebSocket API |
| ------------------------- | -------------------------------------- | ---------------------------------------------- | ------------------------------ |
| **Positioning** | **Full API management** | **Low-cost proxy** | **Real-time bidirectional** |
| Cost | Higher | ~70% cheaper | Per-message pricing |
| Latency | Higher | Lower | Persistent connection |
| Max timeout | 50ms-29s (up to 300s Regional/Private) | 30s hard limit | 29s |
| Payload | 10 MB | 10 MB | 128 KB message / 32 KB frame |
| **API Management** | | | |
| Usage plans/API keys | Yes | No | No |
| Request validation | Yes (JSON Schema draft 4) | No | No |
| Caching | Yes (0.5-237 GB) | No | No |
| Custom gateway responses | Yes | No | No |
| VTL mapping templates | Yes | No (parameter mapping only) | Yes |
| **Security & Governance** | | | |
| WAF | Yes | No (use CloudFront + WAF) | No |
| Resource policies | Yes | No | No |
| Private endpoints | Yes | No | No |
| mTLS | Yes (Regional custom domain only) | Yes (Regional custom domain only) | Via CloudFront viewer mTLS |
| **Auth** | | | |
| Lambda authorizer | Yes (TOKEN + REQUEST) | Yes (REQUEST only, simple + IAM policy format) | Yes (REQUEST on $connect only) |
| JWT authorizer | No (use Cognito authorizer) | Yes (native) | No |
| Cognito authorizer | Yes (native) | Use JWT authorizer | No |
| **Operations** | | | |
| Canary deployments | Yes | No | No |
| Response streaming | Yes | No | No |
| X-Ray tracing | Yes | No | No |
| Execution logging | Yes | No | Yes |
| Custom domain sharing | Not with WebSocket | Not with WebSocket | Not with REST/HTTP |
**Use REST API when**: you are building APIs for external consumers, partners, or multi-tenant platforms; need to enforce per-consumer rate limits and quotas; require request validation, caching, or WAF at the API layer; need private endpoints, resource policies, or canary deployments; or are building an API product with monetization and governance requirements.
**Use HTTP API when**: you are building lightweight APIs or simple backend proxies; cost and latency are the primary concerns; you don't need per-consumer throttling, request validation, caching, or WAF at the API layer; and native JWT authorization with OIDC/OAuth 2.0 meets your auth needs. Accept the hard 30s timeout and lack of API management features. For WAF, edge caching, or edge compute, place a CloudFront distribution in front of the HTTP API.
**Use WebSocket API when you need**: persistent bidirectional connections for real-time use cases (chat, notifications, live dashboards).
## Instructions
### Step 1: Design the API
Before implementation, gather requirements systematically. Consult `references/requirements-gathering.md` for the full requirements workflow covering endpoints, auth, data models, performance, security, and deployment needs.
Key design decisions:
1. **API type**: Use the decision table above
2. **Endpoint type**: Edge-optimized (default for global clients; optimizes TCP connections via CloudFront POPs but does not cache at the edge), Regional (same-region clients, or global clients needing their own CloudFront distribution for edge caching, edge compute, granular WAF control, or geo-based routing), Private (VPC-only access, REST API only)
3. **Topology**: Centralized (single domain, path-based routing) vs Distributed (subdomains per service)
4. **Authentication**: See `references/authentication.md` for the decision tree
### Step 2: Implement the API
Consult these references based on what you're building:
- **Architecture patterns**: `references/architecture-patterns.md`: topology, multi-tenant SaaS, hybrid workloads, private APIs, multi-region, streaming
- **WebSocket API**: `references/websocket.md`: route selection, @connections management, session management, client resilience, SAM templates, limits, multi-region
- **Service integrations**: `references/service-integrations.md`: direct AWS service integrations (EventBridge, SQS, SNS, DynamoDB, Kinesis, Step Functions, S3), HTTP proxy, mock, VTL mapping templates, binary media types, Lambda sync/async invocation
- **Custom domains and routing**: `references/custom-domains-routing.md`: base path mappings, routing rules, header-based versioning
- **Security**: `references/security.md`: mTLS (API Gateway native + CloudFront viewer mTLS), TLS policies, resource policies, WAF, HttpOnly cookies, CRL checks
- **SAM/CloudFormation**: `references/sam-cloudformation.md`: IaC patterns, OpenAPI extensions, VTL reference, binary data
- **SAM service integration templates**: `references/sam-service-integrations.md`: EventBridge, SQS, DynamoDB CRUD, Kinesis, Step Functions (REST + WebSocket) templates
### Step 3: Configure Performance and Scaling
- **Throttling**: Account-level default is 10,000 rps / 5,000 burst (adjustable; request increases via AWS Support). Configure stage-level and method-level throttling via usage plans. See `references/performance-scaling.md`
- **Caching** (REST only): Default TTL 300s, max 3600s. Only GET methods cached by default. Max cached response 1 MB
- **Edge caching** (all API types): For edge caching, place a self-managed CloudFront distribution in front of a Regional API. CloudFront reduces latency, backend load, AND cost (cached responses never reach API Gateway). Also enables edge compute (CloudFront Functions, Lambda@Edge) and granular cache behaviors per path. Use a Regional endpoint, not edge-optimized, when pairing with your own CloudFront distribution
- **Scaling**: API Gateway scales automatically but plan the entire stack (Lambda concurrency, DynamoDB capacity)
### Step 4: Set Up Observability
Always configure access logging. For REST and WebSocket APIs, also enable execution logging (ERROR level for production, INFO only for debugging). **HTTP API does not support execution logging**; use access logs with enhanced observability variables instead.
Consult the observability references based on what you need:
- **Logging setup, log formats, retention**: `references/observability-logging.md`
- **Metrics, alarms, metric filters, X-Ray tracing**: `references/observability-metrics-alarms.md`
- **Log analysis and insights, analytics pipeline, cross-account, control plane logs**: `references/observability-analytics.md`
### Step 5: Deploy
- Use Infrastructure as Code (SAM, CDK, CloudFormation, Terraform) for production
- **Canary deployments** (REST only): Route a percentage of traffic to test new versions
- **Blue/green deployments**: Use custom domain API mappings to switch between environments with zero downtime
- **Routing rules** (preferred for new domains): Declarative header/path-based routing on custom domains for versioning, A/B testing, gradual rollouts, and cell-based routing
- See `references/deployment.md` for detailed patterns
### Step 6: Apply Governance
For organization-wide API standards, see `references/governance.md` covering:
- Preventative controls (SCPs, IAM policies)
- Proactive controls (CloudFormation Hooks, Guard rules)
- Detective controls (AWS Config rules, EventBridge)
- Specific enforcement examples for security, observability, and management
## Response Format
When responding to API Gateway questions, structure your answer as:
1. **Recommendation**: Lead with the recommended approach and why
2. **Code**: Include SAM/CloudFormation YAML or code when the user needs implementation (always read the relevant reference file first)
3. **Pitfalls**: Warn about relevant gotchas from the pitfalls below or from `references/pitfalls.md`
4. **Limits**: Mention any service limits that constrain the design
## Troubleshooting Quick Reference
When diagnosing API Gateway errors, consult `references/troubleshooting.md` for detailed resolution steps. Here are the most common issues:
| Error | Most Common Cause | Quick Fix |
| ---------------------- | ----------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
| 400 Bad Request | Protocol mismatch (HTTP/HTTPS) with ALB | Match protocol to listener type |
| 401 Unauthorized | Wrong token type (ID vs access) or missing identity sources | Check token type matches scope config; verify all identity sources sent |
| 403 Missing Auth Token | Stage name in URL when using custom domain | Remove stage name from URL path |
| 403 from VPC | Private DNS on VPC endpoint intercepts ALL API calls | Use custom domain names for public APIs |
| 403 Access Denied | Resource policy + auth type mismatch or missing redeployment | Review policy, check auth type, redeploy API |
| 403 mTLS | Certificate issuer not in truststore or weak signature algorithm | Verify CA in truststore, use SHA-256+ |
| 429 Too Many Requests | Account/stage/method throttle limits exceeded | Implement jittered exponential backoff; request limit increase |
| 500 Internal Error | Missing Lambda invoke permission (especially with stage variables) | Add resource-based policy to Lambda function |
| 502 Bad Gateway | Lambda response not in required proxy format | Return `{statusCode, headers, body}` from Lambda |
| 504 Timeout | Backend exceeds 29s (REST, increasable) or 30s (HTTP, hard). HTTP API body says "Service Unavailable" but status is 504 | Optimize backend, request timeout increase (REST Regional/Private), or switch to async invocation |
| CORS errors | Missing CORS headers on Gateway Responses (4XX/5XX) | Add CORS headers to DEFAULT_4XX and DEFAULT_5XX gateway responses |
| SSL/PKIX errors | Incomplete certificate chain on backend | Provide full cert chain; use `insecureSkipVerification` only for testing |
## Critical Pitfalls
1. **REST API default timeout is 29 seconds** (increasable up to 300s for Regional/Private endpoints via quota request). Lambda continues running but client gets 504. Request a timeout increase, or consider async patterns (SQS, EventBridge) for better user experience on long operations
2. **HTTP API hard timeout is 30 seconds**. Returns `{"message":"Service Unavailable"}` while Lambda continues
3. **`/ping` and `/sping` are reserved paths**. Do not use for API resources
4. **Execution log events truncated at 1,024 bytes**. Use access logs for complete data
5. **413 `REQUEST_TOO_LARGE` is the only gateway response that cannot be customized**. Use DEFAULT_4XX as a catch-all to add CORS headers for all 4xx errors including 413
6. **`maxItems`/`minItems` not validated** in REST API request validation
7. **Root-level `security` in OpenAPI is ignored**. Must set per-operation
8. **JWT authorizer public keys cached 2 hours**. Account for this in key rotation
9. **Management API rate limit: 10 rps / 40 burst**. Heavy automation can hit this
10. **Always redeploy REST API after configuration changes**. Changes don't take effect until deployed
11. **Edge-optimized endpoints do NOT cache at the edge** — they only optimize TCP connections via CloudFront POPs. If you need edge caching, edge compute (CloudFront Functions, Lambda@Edge), or granular CloudFront control, use a Regional API with your own CloudFront distribution instead
For additional pitfalls (header handling, URL encoding, caching charges, canary deployments, usage plans), see `references/pitfalls.md`.
## IaC Framework Selection
Default: CDK TypeScript
Override syntax:
- "use SAM" → Generate SAM/CloudFormation YAML templates
- "use CloudFormation" → Generate CloudFormation YAML templates
- "use Terraform" → Generate Terraform HCL
When not specified, ALWAYS use CDK TypeScript.
## Error Scenarios
### MCP Server Unavailable
- Inform user: "AWS Serverless MCP not responding"
- Ask: "Proceed without MCP support?"
- DO NOT continue without user confirmation
## Service Limits Quick Reference
See `references/service-limits.md` for the complete table. **Most numeric quotas below are default values and adjustable**; check with your AWS account team and the [latest quotas page](https://docs.aws.amazon.com/apigateway/latest/developerguide/limits.html) before using them for architectural decisions. Key limits:
| Resource | REST API | HTTP API | WebSocket |
| ------------------------ | ---------------------------------------- | -------- | ------------------- |
| Payload size | 10 MB | 10 MB | 128 KB |
| Integration timeout | 50ms-29s (up to 300s Regional/Private) | 30s hard | 29s |
| APIs per region | 600 Regional/Private; 120 Edge-optimized | 600 | 600 |
| Stages per API | 10 | 10 | 10 |
| Routes/resources per API | 300 | 300 | 300 |
| Custom domains (public) | 120 | 120 | 120 |
| Account throttle | 10,000 rps / 5,000 burst | Same | Same (shared quota) |
| API keys per region | 10,000 | N/A | N/A |
| Usage plans per region | 300 | N/A | N/A |
| Cache sizes | 0.5 GB - 237 GB | N/A | N/A |
## skills/aws-lambda-durable-functions/SKILL.md
---
name: aws-lambda-durable-functions
description: >
Build resilient, long-running, multi-step applications with AWS Lambda durable functions with automatic state persistence, retry logic, and orchestration for long-running executions. Covers the critical replay model, step operations, wait/callback patterns, error handling with saga pattern, testing with LocalDurableTestRunner. Triggers on phrases like: lambda durable functions, workflow orchestration, state machines, retry/checkpoint patterns, long-running stateful Lambda functions, saga pattern, human-in-the-loop callbacks, and reliable serverless applications.
---
# AWS Lambda durable functions
Build resilient multi-step applications and AI workflows that can execute for up to 1 year while maintaining reliable progress despite interruptions.
## Onboarding
### Step 1: Validate Prerequisites
Before using AWS Lambda durable functions, verify:
1. **AWS CLI** is installed (2.33.22 or higher) and configured:
```bash
aws --version
aws sts get-caller-identity
```
2. **Runtime environment** is ready:
- For TypeScript/JavaScript: Node.js 22+ (`node --version`)
- For Python: Python 3.11+ (`python --version`. Note that currently only Lambda runtime environments 3.13+ come with the Durable Execution SDK pre-installed. 3.11 is the min supported Python version by the Durable SDK itself, however, you could use OCI to bring your own container image with your own Python runtime + Durable SDK.)
3. **Deployment capability** exists (one of):
- AWS SAM CLI (`sam --version`) 1.153.1 or higher
- AWS CDK (`cdk --version`) v2.237.1 or higher
- Direct Lambda deployment access
### Step 2: Select language and IaC framework
### Language Selection
Default: TypeScript
Override syntax:
- "use Python" → Generate Python code
- "use JavaScript" → Generate JavaScript code
When not specified, ALWAYS use TypeScript
### IaC framework selection
Default: CDK
Override syntax:
- "use CloudFormation" → Generate YAML templates
- "use SAM" → Generate YAML templates
When not specified, ALWAYS use CDK
### Error Scenarios
#### Unsupported Language
- List detected language
- State: "Durable Execution SDK is not yet available for [framework]"
- Suggest supported languages as alternatives
#### Unsupported IaC Framework
- List detected framework
- State: "[framework] might not support Lambda durable functions yet"
- Suggest supported frameworks as alternatives
### Serverless MCP Server Unavailable
- Inform user: "AWS Serverless MCP not responding"
- Ask: "Proceed without MCP support?"
- DO NOT continue without user confirmation
### Step 3: Install SDK
**For TypeScript/JavaScript:**
```bash
npm install @aws/durable-execution-sdk-js
npm install --save-dev @aws/durable-execution-sdk-js-testing
```
**For Python:**
```bash
pip install aws-durable-execution-sdk-python
pip install aws-durable-execution-sdk-python-testing
```
## When to Load Reference Files
Load the appropriate reference file based on what the user is working on:
- **Getting started**, **basic setup**, **example**, **ESLint**, or **Jest setup** -> see [getting-started.md](references/getting-started.md)
- **Understanding replay model**, **determinism**, or **non-deterministic errors** -> see [replay-model-rules.md](references/replay-model-rules.md)
- **Creating steps**, **atomic operations**, or **retry logic** -> see [step-operations.md](references/step-operations.md)
- **Waiting**, **delays**, **callbacks**, **external systems**, or **polling** -> see [wait-operations.md](references/wait-operations.md)
- **Parallel execution**, **map operations**, **batch processing**, or **concurrency** -> see [concurrent-operations.md](references/concurrent-operations.md)
- **Error handling**, **retry strategies**, **saga pattern**, or **compensating transactions** -> see [error-handling.md](references/error-handling.md)
- **Advanced error handling**, **timeout handling**, **circuit breakers**, or **conditional retries** -> see [advanced-error-handling.md](references/advanced-error-handling.md)
- **Testing**, **local testing**, **cloud testing**, **test runner**, or **flaky tests** -> see [testing-patterns.md](references/testing-patterns.md)
- **Deployment**, **CloudFormation**, **CDK**, **SAM**, **log groups**, **deploy**, or **infrastructure** -> see [deployment-iac.md](references/deployment-iac.md)
- **Advanced patterns**, **GenAI agents**, **completion policies**, **step semantics**, or **custom serialization** -> see [advanced-patterns.md](references/advanced-patterns.md)
- **troubleshooting**, **stuck execution**, **failed execution**, **debug execution ID**, **execution history**, **execution error**, **why did my execution fail**, **execution timed out**, **callback not received**, **diagnose execution**, or **root cause execution** -> see [troubleshooting-executions.md](references/troubleshooting-executions.md)
## Quick Reference
### Basic Handler Pattern
**TypeScript:**
```typescript
import { withDurableExecution, DurableContext } from '@aws/durable-execution-sdk-js';
export const handler = withDurableExecution(async (event, context: DurableContext) => {
const result = await context.step('process', async () => processData(event));
return result;
});
```
**Python:**
```python
from aws_durable_execution_sdk_python import durable_execution, DurableContext
@durable_execution
def handler(event: dict, context: DurableContext) -> dict:
result = context.step(lambda _: process_data(event), name='process')
return result
```
### Critical Rules
1. **All non-deterministic code MUST be in steps** (Date.now, Math.random, API calls)
2. **Cannot nest durable operations** - use `runInChildContext` to group operations
3. **Closure mutations are lost on replay** - return values from steps
4. **Side effects outside steps repeat** - use `context.logger` (replay-aware)
### Python API Differences
The Python SDK differs from TypeScript in several key areas:
- **Steps**: Use `@durable_step` decorator + `context.step(my_step(args))`, or inline `context.step(lambda _: ..., name='...')`. Prefer the decorator for automatic step naming.
- **Wait**: `context.wait(duration=Duration.from_seconds(n), name='...')`
- **Exceptions**: `ExecutionError` (permanent), `InvocationError` (transient), `CallbackError` (callback failures)
- **Testing**: Use `DurableFunctionTestRunner` class directly - instantiate with handler, use context manager, call `run(input=...)`
### Invocation Requirements
Durable functions **require qualified ARNs** (version, alias, or `$LATEST`):
```bash
# Valid
aws lambda invoke --function-name my-function:1 output.json
aws lambda invoke --function-name my-function:prod output.json
# Invalid - will fail
aws lambda invoke --function-name my-function output.json
```
## IAM Permissions
Your Lambda execution role MUST have the `AWSLambdaBasicDurableExecutionRolePolicy` managed policy attached. This includes:
- `lambda:CheckpointDurableExecution` - Persist execution state
- `lambda:GetDurableExecutionState` - Retrieve execution state
- CloudWatch Logs permissions
**Additional permissions needed for:**
- **Durable invokes**: `lambda:InvokeFunction` on target function ARNs
- **External callbacks**: Systems need `lambda:SendDurableExecutionCallbackSuccess` and `lambda:SendDurableExecutionCallbackFailure`
## Validation Guidelines
When writing or reviewing durable function code, ALWAYS check for these replay model violations:
1. **Non-deterministic code outside steps**: `Date.now()`, `Math.random()`, UUID generation, API calls, database queries must all be inside steps
2. **Nested durable operations in step functions**: Cannot call `context.step()`, `context.wait()`, or `context.invoke()` inside a step function — use `context.runInChildContext()` instead
3. **Closure mutations that won't persist**: Variables mutated inside steps are NOT preserved across replays — return values from steps instead
4. **Side effects outside steps that repeat on replay**: Use `context.logger` for logging (it is replay-aware and deduplicates automatically)
When implementing or modifying tests for durable functions, ALWAYS verify:
1. All operations have descriptive names
2. Tests get operations by NAME, never by index
3. Replay behavior is tested with multiple invocations
4. Use `LocalDurableTestRunner` for local testing
### MCP Server Configuration
**Write access is enabled by default.** The plugin ships with `--allow-write` in `.mcp.json`, so the MCP server can create projects, generate IaC, and deploy on behalf of the user.
Access to sensitive data (like Lambda and API Gateway logs) is **not** enabled by default. To grant it, add `--allow-sensitive-data-access` to `.mcp.json`.
## Resources
- [AWS Lambda durable functions Documentation](https://docs.aws.amazon.com/lambda/latest/dg/durable-functions.html)
- [JavaScript SDK Repository](https://github.com/aws/aws-durable-execution-sdk-js)
- [Python SDK Repository](https://github.com/aws/aws-durable-execution-sdk-python)
- [IAM Policy Reference](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AWSLambdaBasicDurableExecutionRolePolicy.html)
## skills/aws-lambda-managed-instances/SKILL.md
---
name: aws-lambda-managed-instances
description: >
Evaluate, configure, and migrate workloads to AWS Lambda Managed Instances (LMI).
Triggers on: Lambda Managed Instances, LMI, capacity provider, multi-concurrency Lambda,
dedicated instance Lambda, EC2-backed Lambda, cold start elimination, Graviton Lambda,
instance type for Lambda, scheduled scaling for LMI, Lambda cost optimization with
Reserved Instances or Savings Plans. Also trigger when users describe high-volume
predictable workloads seeking cost savings, want to scale LMI capacity on a schedule,
or compare Lambda vs EC2 for steady-state traffic. For standard Lambda without LMI,
use the aws-lambda skill instead.
argument-hint: "[describe your workload or what you need help with]"
metadata:
tags: lambda, lmi, managed-instances, ec2, capacity-provider, multi-concurrency, cost-optimization, scheduled-scaling
---
# AWS Lambda Managed Instances (LMI)
Run Lambda functions on current-generation EC2 instances in your account while AWS manages provisioning, patching, scaling, routing, and load balancing. Combines Lambda's developer experience with EC2's pricing and hardware options.
For standard Lambda development, see [aws-lambda skill](../aws-lambda/). For SAM/CDK deployment, see [aws-serverless-deployment skill](../aws-serverless-deployment/).
## When to Load Reference Files
- **Cost comparison**, **pricing analysis**, **Lambda vs LMI cost**, **Savings Plans**, or **Reserved Instances** -> see [references/cost-comparison.md](references/cost-comparison.md)
- **Instance types**, **memory sizing**, **vCPU ratios**, **scaling tuning**, **scheduled scaling**, or **capacity provider config** -> see [references/configuration-guide.md](references/configuration-guide.md)
- **Thread safety**, **concurrency model**, **code review checklist**, **Powertools compatibility**, or **multi-concurrency readiness** -> see [references/thread-safety.md](references/thread-safety.md)
- **Before/after code examples**, **runtime-specific migration** (Node.js, Python, Java, .NET), or **connection pooling** -> see [references/migration-patterns.md](references/migration-patterns.md)
- **IAM roles**, **VPC setup**, **CLI commands**, **SAM template**, **CDK example**, or **scheduled scaling setup (EventBridge Scheduler)** -> see [references/infrastructure-setup.md](references/infrastructure-setup.md) and [scripts/setup-lmi.sh](scripts/setup-lmi.sh)
- **Errors**, **throttling**, **debugging**, **stuck deployments**, **tuning configuration**, or **adjusting after deployment** -> see [references/troubleshooting.md](references/troubleshooting.md)
## Quick Decision: Is LMI Right for This Workload?
| Signal | LMI is a strong fit | Standard Lambda is better |
| -------------- | --------------------------------------------------------------------------------------- | ------------------------------------------------------ |
| Traffic | Steady, predictable, 50M+ req/mo | Bursty, unpredictable, long idle |
| Cost | Duration-heavy spend at scale | Low or sporadic invocations |
| Cold starts | Unacceptable (LMI eliminates for provisioned capacity; scale-out may have brief delays) | Tolerable or mitigated by SnapStart |
| Compute | Latest CPUs, specific families, high network bandwidth | Standard Lambda memory/CPU sufficient |
| Isolation | Dedicated EC2 instances in your account, full VPC control | Shared Firecracker micro-VMs acceptable |
| Scale-to-zero | Not needed (execution environments always running) | Required (pay nothing when idle) |
| Code readiness | Thread-safe (Node.js/Java/.NET) or any Python code | Non-thread-safe Node.js/Java/.NET, expensive to change |
## Instructions
### Step 1: Assess the Workload
Gather these signals before recommending:
1. **Traffic pattern**: Steady vs bursty? Requests per second?
2. **Current costs**: Monthly Lambda spend? Existing Savings Plans?
3. **Runtime**: Node.js, Java, .NET, or Python?
4. **Memory/CPU**: How much memory? CPU-bound or I/O-bound?
5. **Execution duration**: Average and P99?
6. **Concurrency readiness**: Thread safety (Node.js/Java/.NET)? Shared `/tmp` paths? Per-invocation DB connections?
7. **VPC**: Already in a VPC? Private resource access needed?
#### Deriving LMI Configuration from Metrics
If Lambda Insights is enabled on the function, use these metrics to calculate your starting configuration. If Lambda Insights is not enabled, suggest adding it to gather accurate workload data — but only proceed with the user's explicit confirmation, as adding the Insights layer may affect function performance or cold start times.
To check if Lambda Insights is enabled, look for a LambdaInsightsExtension layer on the function. To add it, find the latest layer ARN for your region from the [Lambda Insights documentation](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Lambda-Insights-extension-versions.html) and attach the `CloudWatchLambdaInsightsExecutionRolePolicy` managed policy to the function's execution role.
**Target max concurrency** (from `cpu_total_time` and `Duration`):
```
PerExecutionEnvironmentMaxConcurrency = floor((0.5 × Duration) / cpu_total_time)
```
This targets 50% CPU utilization at full concurrency, leaving headroom for scaling.
**Memory allocation** (from `memory_utilization` and current memory):
```
MemorySize = min(32768, max(2048, MaxConcurrency × (memory_utilization / 100) × current_allocated_memory))
```
This overestimates (assumes no shared base memory) but provides a safe starting point. The outer `min` caps the result at the 32 GB (32768 MB) LMI maximum.
**Minimum execution environments** (from baseline `ConcurrentExecutions`):
```
MinExecutionEnvironments = max(3, ceil(baseline_concurrent_executions × 2 / MaxConcurrency))
```
Targets 50% concurrency utilization to leave headroom for traffic bursts.
**Without Lambda Insights:** Start with the runtime's default max concurrency, 2 GB memory, and MinExecutionEnvironments = 3. Adjust during testing.
### Step 2: Build the Cost Comparison
REQUIRED: Present a cost comparison before recommending LMI. Compare at minimum:
| Scenario | When it wins |
| ---------------- | --------------------------- |
| Lambda on-demand | Low volume, bursty traffic |
| LMI on-demand | High volume, steady traffic |
Rule of thumb: LMI becomes cost-competitive when your Lambda spend exceeds ~$1,000/month with steady traffic.
For discount analysis (Savings Plans, Reserved Instances), refer users to the [AWS Pricing Calculator](https://calculator.aws/) and [references/cost-comparison.md](references/cost-comparison.md) for formulas and worked examples. Discount recommendations require workload-specific forecasting beyond this skill's scope.
### Step 3: Configure the Deployment
**Instance families** (~450 types): C-series (compute, .xlarge+), M-series (general, .large+), R-series (memory, .large+). ARM (Graviton) for best price-performance.
**Memory-to-vCPU ratios**: 2:1 (default, CPU-bound work), 4:1 (general/mixed workloads), 8:1 (memory-heavy or Python apps). Min 2 GB, max 32 GB.
**Multi-concurrency defaults/vCPU**: Node.js 64, Java 32, .NET 32, Python 16.
**Scaling**: MinExecutionEnvironments (default 3), MaxVCpuCount (default 400), TargetResourceUtilization.
**Scheduled scaling**: For predictable traffic (business hours, marketing events), use EventBridge Scheduler to adjust Min/Max execution environments on a one-time or recurring schedule — scale up before peak, scale down or to zero when idle.
See [references/configuration-guide.md](references/configuration-guide.md) for decision trees and detailed tuning.
### Step 4: Migrate the Code
Review code for concurrency safety. LMI runs multiple invocations concurrently per execution environment, but the model differs by runtime:
- **Python**: Process-based isolation — globals are NOT shared. No thread-safety changes needed. Focus on `/tmp` conflicts and memory sizing (per-process × concurrency).
- **Node.js**: Worker threads — globals shared within a worker. Requires async safety. Callback handlers not supported on Node.js 22.
- **Java/.NET**: OS threads/Tasks — handler shared across threads. Requires full thread safety.
**Common issues (all runtimes)**: shared `/tmp` paths, per-invocation DB connections.
**Thread-safety issues (Node.js/Java/.NET only)**: mutable globals, non-thread-safe libs.
See [references/thread-safety.md](references/thread-safety.md) for the review checklist and [references/migration-patterns.md](references/migration-patterns.md) for runtime-specific before/after code.
### Step 5: Set Up Infrastructure
1. Create two IAM roles: execution role (for the function) and operator role (for capacity provider EC2 management)
2. Configure VPC with subnets across multiple AZs (recommended 3+ for resiliency)
3. Create capacity provider with VPC config and scaling limits
4. Create or update function with capacity provider attachment
5. Publish a version (triggers instance provisioning)
See [references/infrastructure-setup.md](references/infrastructure-setup.md) for CLI commands and SAM templates.
### Step 6: Validate and Cut Over
1. Deploy to a non-production environment first
2. Monitor CloudWatch: CPU utilization, memory, concurrency, throttle rate. If you observe low CPU utilization or ongoing throttles, see [references/troubleshooting.md](references/troubleshooting.md) for metric-specific adjustment guidance.
3. Shift traffic to the LMI function (note: weighted alias shifting between LMI and non-LMI functions is not currently supported)
4. Compare costs after 1-2 weeks of production data
5. Decommission standard Lambda once stable
## Best Practices
### Configuration
- Do: Start with 2:1 ratio and runtime default concurrency
- Do: Use ARM (Graviton) unless x86 dependencies exist
- Do: Let Lambda choose instance types unless specific hardware needed
- Do: Set MaxVCpuCount to control cost ceiling
- Don't: Set MinExecutionEnvironments below 3 in production (reduces multi-AZ coverage). Non-prod environments can use 1 as the minimum.
- Don't: Over-restrict instance types (lowers availability)
### Migration
- Do: Start with I/O-heavy functions (benefit most from multi-concurrency; CPU-bound functions compete for same CPU)
- Do: Review code for concurrency safety before attaching to capacity provider (thread safety for Node.js/Java/.

