-
Notifications
You must be signed in to change notification settings - Fork 1k
add a simplistic lambda-managed-instances-cdk pattern
#2885
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
julianwood
merged 9 commits into
aws-samples:main
from
DmitryGulin:pattern/lambda-managed-instances-cdk
Feb 16, 2026
Merged
Changes from 2 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
eeef170
add a simplistic `lambda-managed-instances-cdk` pattern
DmitryGulin 9a60876
NPM packages updates and a few renames so that this stack doesn't con…
DmitryGulin d62484a
address code review comment
DmitryGulin 0268e87
address code review comment
DmitryGulin 9cc9f59
Apply suggestions from code review
DmitryGulin 4cd51a5
Merge branch 'aws-samples:main' into pattern/lambda-managed-instances…
DmitryGulin 1d290b1
docs(core): update README.md and example-pattern.json as requested
DmitryGulin a2b934d
update NPM packages
DmitryGulin 73bffc3
Add final pattern file
bfreiberg File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,91 @@ | ||
| *.js | ||
| !jest.config.js | ||
| *.d.ts | ||
| node_modules | ||
|
|
||
| # CDK asset staging directory | ||
| .cdk.staging | ||
| cdk.out | ||
|
|
||
| # Parcel default cache directory | ||
| .parcel-cache | ||
|
|
||
| # npm | ||
| .npm | ||
|
|
||
| # yarn | ||
| .yarn | ||
|
|
||
| # IDE | ||
| .vscode/ | ||
| .idea/ | ||
|
|
||
| # OS | ||
| .DS_Store | ||
| Thumbs.db | ||
|
|
||
| # Logs | ||
| *.log | ||
|
|
||
| # Runtime data | ||
| pids | ||
| *.pid | ||
| *.seed | ||
| *.pid.lock | ||
|
|
||
| # Coverage directory used by tools like istanbul | ||
| coverage | ||
| *.lcov | ||
|
|
||
| # nyc test coverage | ||
| .nyc_output | ||
|
|
||
| # Dependency directories | ||
| node_modules/ | ||
| jspm_packages/ | ||
|
|
||
| # Optional npm cache directory | ||
| .npm | ||
|
|
||
| # Optional eslint cache | ||
| .eslintcache | ||
|
|
||
| # Output of 'npm pack' | ||
| *.tgz | ||
|
|
||
| # Yarn Integrity file | ||
| .yarn-integrity | ||
|
|
||
| # dotenv environment variables file | ||
| .env | ||
| .env.test | ||
|
|
||
| # parcel-bundler cache (https://parceljs.org/) | ||
| .cache | ||
| .parcel-cache | ||
|
|
||
| # next.js build output | ||
| .next | ||
|
|
||
| # nuxt.js build output | ||
| .nuxt | ||
|
|
||
| # vuepress build output | ||
| .vuepress/dist | ||
|
|
||
| # Serverless directories | ||
| .serverless/ | ||
|
|
||
| # FuseBox cache | ||
| .fusebox/ | ||
|
|
||
| # DynamoDB Local files | ||
| .dynamodb/ | ||
|
|
||
| # TernJS port file | ||
| .tern-port | ||
|
|
||
| # CDK Context & Staging files | ||
| .cdk.staging/ | ||
| cdk.out/ | ||
| cdk.context.json |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| *.ts | ||
| !*.d.ts | ||
|
|
||
| # CDK asset staging directory | ||
| .cdk.staging | ||
| cdk.out |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,202 @@ | ||
| # Lambda Hello World on Lambda Managed Instances | ||
|
|
||
| This pattern demonstrates how to deploy a simple Hello World Lambda function running on Lambda Managed Instances using AWS CDK. Lambda Managed Instances provide predictable performance and reduced cold starts for your Lambda functions. | ||
|
DmitryGulin marked this conversation as resolved.
Outdated
|
||
|
|
||
| Learn more about this pattern at Serverless Land Patterns: https://serverlessland.com/patterns/lambda-managed-instances-cdk | ||
|
|
||
| Important: this application uses various AWS services and there are costs associated with these services after the Free Tier usage - please see the [AWS Pricing page](https://aws.amazon.com/pricing/) for details. You are responsible for any AWS costs incurred. No warranty is implied in this example. | ||
|
|
||
| **Note**: Lambda Managed Instances provision EC2 instances that are **NOT eligible for the AWS Free Tier**. These instances will incur charges immediately upon deployment, regardless of your Free Tier status. | ||
|
|
||
| ## Requirements | ||
|
|
||
| * [Create an AWS account](https://portal.aws.amazon.com/gp/aws/developer/registration/index.html) if you do not already have one and log in. The IAM user that you use must have sufficient permissions to make necessary AWS service calls and manage AWS resources. | ||
| * [AWS CLI v2](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) (latest available version) installed and configured | ||
| * [Git Installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) | ||
| * [AWS CDK](https://docs.aws.amazon.com/cdk/latest/guide/getting_started.html) (version 2.232.0 or later) installed and configured | ||
| * [Node.js](https://nodejs.org/) (version 24.x or later) | ||
|
|
||
| ## Deployment Instructions | ||
|
|
||
| 1. Create a new directory, navigate to that directory in a terminal and clone the GitHub repository: | ||
| ``` | ||
| git clone https://github.com/aws-samples/serverless-patterns | ||
| ``` | ||
| 1. Change directory to the pattern directory: | ||
| ``` | ||
| cd lambda-managed-instances-cdk | ||
| ``` | ||
| 1. Install the project dependencies: | ||
| ``` | ||
| npm install | ||
| ``` | ||
| 1. Deploy the CDK stack: | ||
| ``` | ||
| cdk deploy | ||
| ``` | ||
| Note: This stack will deploy to your default AWS region. Please refer to the [AWS capabilities explorer](https://builder.aws.com/build/capabilities/explore) for feature availability in your desired region. | ||
|
|
||
| 1. Note the outputs from the CDK deployment process. These contain the resource names and/or ARNs which are used for testing. | ||
|
|
||
| ## How it works | ||
|
|
||
| This pattern demonstrates the deployment of a simple Lambda function on Lambda Managed Instances: | ||
|
|
||
| ### Lambda Managed Instances | ||
| [Lambda Managed Instances](https://docs.aws.amazon.com/lambda/latest/dg/lambda-managed-instances.html) provide: | ||
| - Predictable performance with pre-warmed execution environments | ||
| - Reduced cold start latency | ||
| - Consistent execution characteristics | ||
| - Better resource utilization for frequently invoked functions | ||
|
|
||
| The underlying EC2 infrastructure can be inspected using AWS CLI commands to understand how managed instances work (see "Inspecting Lambda Managed Instances Infrastructure" section below). | ||
|
|
||
| ### Hello World Function | ||
| The Lambda function is a simple Hello World implementation that: | ||
| - Accepts an event with a name parameter | ||
| - Returns a JSON response with a greeting message | ||
| - Uses AWS Lambda PowerTools for efficient event logging | ||
| - Demonstrates minimal Lambda function structure using the Handler type | ||
|
DmitryGulin marked this conversation as resolved.
Outdated
|
||
|
|
||
| ### CloudWatch Log Group | ||
|
DmitryGulin marked this conversation as resolved.
Outdated
|
||
| The pattern includes a dedicated CloudWatch log group with: | ||
| - **Custom log group name**: `/demo/lambda/hello-world-managed-instances-cdk` | ||
| - **Retention period**: 2 weeks (14 days) to manage storage costs | ||
| - **Automatic cleanup**: Configured with `RemovalPolicy.DESTROY` to be deleted when the stack is destroyed | ||
| - **Direct integration**: The Lambda function is configured to use this specific log group | ||
|
DmitryGulin marked this conversation as resolved.
Outdated
|
||
|
|
||
| ## Testing | ||
|
|
||
| After deployment, you can test the Lambda function using AWS CLI or AWS Console. | ||
|
|
||
| ### AWS CLI Testing | ||
|
|
||
| 1. **Basic function invocation**: | ||
| ```bash | ||
| aws lambda invoke \ | ||
| --function-name hello-world-managed-instances-cdk \ | ||
| --payload file://events/hello-world.json \ | ||
| --cli-binary-format raw-in-base64-out \ | ||
| response.json | ||
| ``` | ||
|
|
||
| 2. **View the response**: | ||
| ```bash | ||
| cat response.json | ||
| ``` | ||
|
|
||
| 3. **Custom name invocation**: | ||
| ```bash | ||
| echo '{"name":"Lambda Managed Instances"}' | aws lambda invoke \ | ||
| --function-name hello-world-managed-instances-cdk \ | ||
| --payload file:///dev/stdin \ | ||
| --cli-binary-format raw-in-base64-out \ | ||
| custom-response.json | ||
| ``` | ||
|
|
||
| 4. **View CloudWatch logs**: | ||
| ```bash | ||
| aws logs filter-log-events \ | ||
| --log-group-name /demo/lambda/hello-world-managed-instances-cdk \ | ||
| --start-time $(date -d '5 minutes ago' +%s)000 | ||
| ``` | ||
|
|
||
| ### AWS Console Testing | ||
|
|
||
| 1. Navigate to the Lambda service in the AWS Console | ||
| 2. Find the function named `hello-world-managed-instances-cdk` | ||
| 3. Create a test event using the payload from `events/hello-world.json` or create a custom payload: | ||
| ```json | ||
| { | ||
| "name": "Your Custom Name" | ||
| } | ||
| ``` | ||
| 4. Execute the test and observe the results in the execution logs | ||
|
|
||
| ### Expected Response | ||
|
|
||
| The function returns a JSON response with the following structure: | ||
|
|
||
| ```json | ||
| { | ||
| "response": "Hello AWS Lambda on Managed Instances" | ||
| } | ||
| ``` | ||
|
|
||
| ### Monitoring and Observability | ||
|
|
||
| Monitor the function execution through: | ||
| - **CloudWatch Logs**: Detailed execution logs with event and response data in the dedicated log group | ||
| - **Lambda Metrics**: Function performance and invocation statistics | ||
| - **CloudWatch Metrics**: Custom metrics and alarms for monitoring | ||
|
|
||
| The stack outputs include the log group name for easy reference when setting up monitoring dashboards or log analysis tools. | ||
|
|
||
| ## Inspecting Lambda Managed Instances Infrastructure | ||
|
|
||
| Lambda Managed Instances provision EC2 instances behind the scenes to provide predictable performance. You can inspect this infrastructure using AWS CLI commands: | ||
|
|
||
| ### View Capacity Provider Details | ||
|
|
||
| ```bash | ||
| aws lambda get-capacity-provider --capacity-provider-name lambda-capacity-provider-cdk | ||
| ``` | ||
|
|
||
| This shows: | ||
| - Capacity provider ARN and state | ||
| - VPC configuration (subnets and security groups) | ||
| - Instance requirements (architecture, scaling mode) | ||
| - IAM roles and permissions | ||
|
|
||
| ### List Associated EC2 Instances | ||
|
|
||
| ```bash | ||
| aws ec2 describe-instances \ | ||
| --filters "Name=tag:aws:lambda:capacity-provider,Values=arn:aws:lambda:*:capacity-provider:lambda-capacity-provider-cdk" \ | ||
| --query 'Reservations[*].Instances[*].[InstanceId,InstanceType,State.Name,LaunchTime,SubnetId,PrivateIpAddress]' \ | ||
| --output table | ||
| ``` | ||
|
|
||
| This displays: | ||
| - Instance IDs and types | ||
| - Current state (running, pending, terminated) | ||
| - Launch times and subnet distribution | ||
| - Private IP addresses within the VPC | ||
|
|
||
| **Note**: For a complete list of supported EC2 instance types for Lambda Managed Instances and their pricing, see the [AWS Lambda Pricing page](https://aws.amazon.com/lambda/pricing/). | ||
|
|
||
| ### Understanding Instance Behavior | ||
|
|
||
| **Auto-scaling**: Instances are automatically created and terminated based on function demand | ||
| - **Scale-up**: New instances launch when function invocation increases | ||
| - **Scale-down**: Unused instances terminate after periods of low activity | ||
| - **Multi-AZ**: Instances are distributed across availability zones for high availability | ||
|
|
||
| **Instance Lifecycle**: | ||
| - Instances typically launch within 1-2 minutes of stack deployment | ||
| - They remain running to provide immediate function execution | ||
| - AWS manages all instance lifecycle operations automatically | ||
|
|
||
| ### Automated Testing | ||
|
|
||
| The included test script (`./test-lambda.sh`) automatically inspects both the capacity provider and EC2 instances, providing a comprehensive view of the managed instances infrastructure. | ||
|
|
||
| ## Regional Availability | ||
|
|
||
| This stack will deploy to your default AWS region. Before deploying, please verify that Lambda Managed Instances feature is available in your target region by using the [AWS capabilities explorer](https://builder.aws.com/build/capabilities/explore) or consulting the official [Lambda Managed Instances documentation](https://docs.aws.amazon.com/lambda/latest/dg/lambda-managed-instances.html). | ||
|
|
||
| ## Cleanup | ||
|
|
||
| 1. Delete the stack | ||
| ```bash | ||
| cdk destroy | ||
| ``` | ||
| 1. Confirm the stack has been deleted by checking the AWS CloudFormation console or running: | ||
| ```bash | ||
| aws cloudformation describe-stacks --stack-name lambda-managed-instances-cdk | ||
| ``` | ||
|
|
||
| ---- | ||
| Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
|
DmitryGulin marked this conversation as resolved.
Outdated
|
||
|
|
||
| SPDX-License-Identifier: MIT-0 | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| #!/usr/bin/env node | ||
| import { App } from 'aws-cdk-lib/core'; | ||
| import { DemoStack } from '../lib/demo-stack'; | ||
|
|
||
| const app = new App(); | ||
| new DemoStack(app, 'LambdaManagedInstancesDemo', { | ||
| stackName: 'lambda-managed-instances-cdk', | ||
| env: { | ||
| account: process.env.CDK_DEFAULT_ACCOUNT, | ||
| region: process.env.CDK_DEFAULT_REGION | ||
| }, | ||
| description: 'Simple Hello World Lambda function running on Lambda Managed Instances', | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,70 @@ | ||
| { | ||
| "app": "npx ts-node --prefer-ts-exts bin/app.ts", | ||
| "watch": { | ||
| "include": [ | ||
| "**" | ||
| ], | ||
| "exclude": [ | ||
| "README.md", | ||
| "cdk*.json", | ||
| "**/*.d.ts", | ||
| "**/*.js", | ||
| "tsconfig.json", | ||
| "package*.json", | ||
| "yarn.lock", | ||
| "node_modules", | ||
| "test" | ||
| ] | ||
| }, | ||
| "context": { | ||
| "@aws-cdk/aws-lambda:recognizeLayerVersion": true, | ||
| "@aws-cdk/core:checkSecretUsage": true, | ||
| "@aws-cdk/core:target-partitions": [ | ||
| "aws", | ||
| "aws-cn" | ||
| ], | ||
| "@aws-cdk-containers/ecs-service-extensions:enableDefaultLogDriver": true, | ||
| "@aws-cdk/aws-ec2:uniqueImdsv2TemplateName": true, | ||
| "@aws-cdk/aws-ecs:arnFormatIncludesClusterName": true, | ||
| "@aws-cdk/aws-iam:minimizePolicies": true, | ||
| "@aws-cdk/core:validateSnapshotRemovalPolicy": true, | ||
| "@aws-cdk/aws-codepipeline:crossAccountKeyAliasStackSafeResourceName": true, | ||
| "@aws-cdk/aws-s3:createDefaultLoggingPolicy": true, | ||
| "@aws-cdk/aws-sns-subscriptions:restrictSqsDescryption": true, | ||
| "@aws-cdk/aws-apigateway:disableCloudWatchRole": true, | ||
| "@aws-cdk/core:enablePartitionLiterals": true, | ||
| "@aws-cdk/aws-events:eventsTargetQueueSameAccount": true, | ||
| "@aws-cdk/aws-iam:standardizedServicePrincipals": true, | ||
| "@aws-cdk/aws-ecs:disableExplicitDeploymentControllerForCircuitBreaker": true, | ||
| "@aws-cdk/aws-iam:importedRoleStackSafeDefaultPolicyName": true, | ||
| "@aws-cdk/aws-s3:serverAccessLogsUseBucketPolicy": true, | ||
| "@aws-cdk/aws-route53-patters:useCertificate": true, | ||
| "@aws-cdk/customresources:installLatestAwsSdkDefault": false, | ||
| "@aws-cdk/aws-rds:databaseProxyUniqueResourceName": true, | ||
| "@aws-cdk/aws-codedeploy:removeAlarmsFromDeploymentGroup": true, | ||
| "@aws-cdk/aws-apigateway:authorizerChangeDeploymentLogicalId": true, | ||
| "@aws-cdk/aws-ec2:launchTemplateDefaultUserData": true, | ||
| "@aws-cdk/aws-secretsmanager:useAttachedSecretResourcePolicyForSecretTargetAttachments": true, | ||
| "@aws-cdk/aws-redshift:columnId": true, | ||
| "@aws-cdk/aws-stepfunctions-tasks:enableLogging": true, | ||
| "@aws-cdk/aws-ec2:restrictDefaultSecurityGroup": true, | ||
| "@aws-cdk/aws-apigateway:requestValidatorUniqueId": true, | ||
| "@aws-cdk/aws-kms:aliasNameRef": true, | ||
| "@aws-cdk/aws-autoscaling:generateLaunchTemplateInsteadOfLaunchConfig": true, | ||
| "@aws-cdk/core:includePrefixInUniqueNameGeneration": true, | ||
| "@aws-cdk/aws-efs:denyAnonymousAccess": true, | ||
| "@aws-cdk/aws-opensearchservice:enableLogging": true, | ||
| "@aws-cdk/aws-normlizer:disable": true, | ||
| "@aws-cdk/aws-lambda:recognizeVersionProps": true, | ||
| "@aws-cdk/aws-cloudfront:defaultSecurityPolicyTLSv1.2_2021": true, | ||
| "@aws-cdk/core:stackRelativeExports": true, | ||
| "@aws-cdk/aws-rds:lowercaseDbIdentifier": true, | ||
| "@aws-cdk/aws-efs:mountTargetOrderInsensitiveLogicalId": true, | ||
| "@aws-cdk/aws-rds:generateSecretManagerSecretName": true, | ||
| "@aws-cdk/aws-ecs-patterns:removeDefaultDesiredCount": true, | ||
| "@aws-cdk/aws-rds:auroraClusterChangeScopeOfInstanceParameterGroupWithEachParameters": true, | ||
| "@aws-cdk/aws-appsync:useArnForSourceApiAssociationIdentifier": true, | ||
| "@aws-cdk/aws-rds:preventRenderingDeprecatedCredentials": true, | ||
| "@aws-cdk/aws-codepipeline-actions:useNewDefaultBranchForSourceAction": true | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| { | ||
| "name": "AWS Lambda on Managed Instances" | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.