(cli): Hotswapping support for Lambda Versions and Aliases
General Issue
How should Lambda Versions and Aliases be hotswapped?
The Question
The expected behavior when hotswapping Lambda Functions that make use of Versions or Aliases is not clear. Please :+1: this issue and add comments explaining your desired behavior and use cases if you would like to see hotswapping be able to modify Lambda Versions and Aliases.
Versions:
- What should happen when the
currentVersionproperty of a particular Function is being used, and that Function is updated? - What should happen when a Version construct is present, and the Function it references is updated?
Aliases:
- Provided that the Function in the
currentVersionconstruct use case above is updated, should any Aliases that reference it be updated? - Provided that the Function in the
Versionconstruct use case above is updated, should any Aliases that reference it be updated?
Implementation Challenges:
- Because
currentVersiondeletes a resource and creates a new one with a different ID each deployment, hotswapping that change requires matching a deleted resource to a created resource with different IDs. This would require some detector functions to know the results of other detector functions before they finish executing, which is not ideal in the current framework.
CDK CLI Version
N/A
Framework Version
No response
Node.js Version
No response
OS
No response
Language
Typescript
Language Version
No response
Other information
No response
What is hotswapping in this context?
What is hotswapping in this context?
@iph it's a CDK feature: https://www.npmjs.com/package/aws-cdk#user-content-hotswap-deployments-for-faster-development
Thanks!
So, I personally haven't touched the Version resource in like 3 years, but it's a mine-field. Luckily the actual backing "what we are attempting to do" is actually super simple!
Summarized thoughts
I think if currentVersion is specified, always try a PublishVersion api call, and wherever the Version resource is referenced, update with the new version arn (or the same one idempotently). You will find this to be as close to the desired experience as cfn is today. Even aliases would work surprisingly well with this implementation.
Read more to find out why :)
Long-winded Details of Version/Alias
Adding some contextual flavor: Surprisingly, PublishVersion always succeeds, if you have permission to publish. "Hold up, what?! There is a crap-ton of wiring in the CDK specifically arounds the Version resource!". That's right! See, Cloudformation treats versions as an immutable resource, and because of that, they expect the resource to change, otherwise cloudformation updates fail. But really...behind the scenes, Version resource is just doing a publish-version and validating that the number changed. The problem that Lambda messed up on, is if nothing has changed in your function, then we don't publish a new number. This does not mesh well in CFN, since their definition of change is based on the version arn changing. If you are on version:5, and publish-version returns "version:5", cfn is like "nothing has changed, but I'm creating a new resource, hence I must fail" -- and explodes on Version replacement. This is what the CDK mechanisms are attempting to prevent from happening and why it's so hamfisted at the moment.
BUT -- if you are just hotswapping and implementing this out of band...well...if a Version resource exists...just publish a version -- whatever that value is...use it everywhere else the version arn is specifically requested. It's either idempotently the same value on update, or it's new and needs updates everywhere it's referenced anyways
What I mean by "everywhere else" is that anywhere a lambda function arn is used, some integrations are configured to be a bit too restrictive. Take EventBus as an example:
const deployer = new lambda.Function(this, 'DeployerLambda', {
functionName: `${props.tag}-deployer`,
code: lambda.Code.fromAsset(path.join(__dirname, '..', 'lambdas/deployer.zip')),
handler: 'deployer',
runtime: lambda.Runtime.GO_1_X,
});
const deployTarget = new targets.LambdaFunction(deployer, {version: true});
new eventbridge.Rule(this, 'DailyRule', {
ruleName: `${props.tag}-daily-trigger`,
schedule: eventbridge.Schedule.cron({minute: '11', hour: '4'}),
targets: [deployTarget]
});
I made up the "version: true" bit, as you can't specify the version arn in eventbus targets today, a true tragedy (well you can, but the interface is too verbose for an example). The above is slightly broken, as you can't specify a lambda version arn, nor a lambda alias arn -- just the default arn of the function. That's fine, as the first step to publishing a version is updating the code (just slightly sad there is no way to specify without creating a new manual target).
If it was ever supported to plop out the version arn automagically (maybe a prop) to eventbridge rule targets, you would need to also update all targets to point to the new version. For aliases, you don't have to do this (the beauty of the alias in the first place :D) -- but aliases would point to the version anyways, so that update would still be required.
Thanks @iph! This is super valuable. A few questions: when you say
if a Version resource exists...just publish a version -- whatever that value is...use it everywhere else the version arn is specifically requested
do you mean that if any Version exists in the synthesized template (not just in the diff), we should always publish a new Version when hotswapping?
Lastly, what should happen if a user creates an Alias that is meant to be stable (eg is not affected by updates to the function until the user changes the referenced version)? Should we update all aliases that reference any version of the updated function to the version we just published, or should we only modify aliases that reference the currentVersion of the function?
do you mean that if any Version exists in the synthesized template (not just in the diff), we should always publish a new Version when hotswapping?
So, two scenarios:
-
Publish version doesn't do anything (you are on version 5, it returns version 5), update calls on all integrations with this arn are idempotent, so you can just "do them" (or store the value beforehand if you want to short circuit)
-
Publish Version produces a new version. Well, gotta update all places this version is referenced (e.g. alias, or possibly some integration attachment).
Both scenarios can technically follow the same code path (update all references to version with whatever the output is), which simplifies the implementation.
we just published, or should we only modify aliases that reference the currentVersion of the function?
I think this is the desired behavior, yes. You only update the alias if it references the version and the version is being modified (but again, read scenario 1 above). Technically, if it's pointing to a function that just had updated code, all paths lead to the alias being updated anyways, IIRC.
Thanks! This has cleared up the confusion I had around this.
Thanks for the awesome summary @iph. There's so much in your answer that it will take me a long time to digest all of it 🙂.
For now, I want to focus on the following statement you made:
Adding some contextual flavor: Surprisingly, PublishVersion always succeeds, if you have permission to publish. "Hold up, what?! There is a crap-ton of wiring in the CDK specifically arounds the Version resource!". That's right! See, Cloudformation treats versions as an immutable resource, and because of that, they expect the resource to change, otherwise cloudformation updates fail. But really...behind the scenes, Version resource is just doing a publish-version and validating that the number changed. The problem that Lambda messed up on, is if nothing has changed in your function, then we don't publish a new number. This does not mesh well in CFN, since their definition of change is based on the version arn changing. If you are on version:5, and publish-version returns "version:5", cfn is like "nothing has changed, but I'm creating a new resource, hence I must fail" -- and explodes on Version replacement. This is what the CDK mechanisms are attempting to prevent from happening and why it's so hamfisted at the moment.
So, I just did some experiments, and I'm wondering whether what I've seen is consistent with your expectations.
Here's my CDK code:
const func = new lambda.Function(this, 'Function', {
code: lambda.Code.fromAsset(`${__dirname}/lambda-code`),
runtime: lambda.Runtime.NODEJS_14_X,
handler: 'index.handler',
});
new lambda.Version(this, 'Version', {
lambda: func,
});
Here's what I did:
-
cdk deploythe above code. Everything works as expected. -
Make a change only to the code of the Lambda,
cdk deployagain (no--hotswap). Everything happened as expected: the Lambda has the new code, but a new Version was not published, and the existing latest Version still has the old code. -
Now I make a change only to the Version in the CDK code (I added a
description, but it probably doesn't matter):new lambda.Version(this, 'Version', { lambda: func, description: 'this is my Alias', });And incredibly, this causes a 500 when running
cdk deploy!3:34:17 PM | UPDATE_FAILED | AWS::Lambda::Version | Version6A868472 Internal Failure(It's consistent - I can reproduce this 500 many times)
Is this part of what you said above?
This does not mesh well in CFN, since their definition of change is based on the version arn changing. If you are on version:5, and publish-version returns "version:5", cfn is like "nothing has changed, but I'm creating a new resource, hence I must fail" -- and explodes on Version replacement.
I would understand CloudFormation failing here, but I was not expecting a 500, I think coming from the Lambda API 🙂.
Would love to get your take on whether this is expected, or not!
Just want to drop a note about my repro / workaround for this issue.
I followed the example for setting up a serverless application using CDK. With this simple API Gateway + Lambda App, hotswap feature works as expected.
I additionally created an alias that was associated with this lambda function:
export class WidgetService extends core.Construct {
constructor(scope: core.Construct, id: string) {
super(scope, id);
const bucket = new s3.Bucket(this, "WidgetStore");
const handler = new lambda.Function(this, "WidgetHandler", {
runtime: lambda.Runtime.NODEJS_14_X, // So we can use async in widget.js
code: lambda.Code.fromAsset("resources"),
description: "generated at " + new Date().toISOString(),
handler: "widgets.main",
environment: {
BUCKET: bucket.bucketName
}
});
bucket.grantReadWrite(handler); // was: handler.role);
const api = new apigateway.RestApi(this, "widgets-api", {
restApiName: "Widget Service",
description: "This service serves widgets."
});
const getWidgetsIntegration = new apigateway.LambdaIntegration(handler, {
requestTemplates: { "application/json": '{ "statusCode": "200" }' }
});
new lambda.Alias(this, "LambdaAlias", {
aliasName: "widget-alias",
version: new lambda.Version(this, "LambdaVersion-" + new Date().toISOString(), { lambda: handler })
});
api.root.addMethod("GET", getWidgetsIntegration); // GET /
}
}
Now hotswapping does not work. It assumes that the function version resource has changed and does a stack update everytime.
Workaround:
- Upload assets to S3 directly using S3 API.
- Call
updateFunctionCodeto update the code for the lambda function. - Call
publishVersionto publish a new version using the latest code. - Call
updateAliasAPI on lambda alias with the following params:
alias name = widget-alias
function_name = ...
function_version = version returned by publishVersion API call above.
RoutingConfig: {
AdditionalVersionWeights: { }
}
This helps in hot swapping the function code without updating the stack. This causes drift as expected but this is acceptable for dev / test stacks.
Please note that the speed gains are only available when provisioned concurrency on the lambda function is disabled. With provisioned concurrency enabled, it still takes some time for the getAlias API to reflect that all traffic is being routed to the new version.
It would be very helpful to have this workaround as part of CDK hotswap feature.
Hey @iamrohitbanga, I've submitted a PR (https://github.com/aws/aws-cdk/pull/18145) that covers the example you posted. This is the code that I used to test whether everything works:
import * as cdk from '@aws-cdk/core';
import * as apigateway from '@aws-cdk/aws-apigateway';
import * as lambda from '@aws-cdk/aws-lambda';
export class LambdaVersionsAliasesStack extends cdk.Stack {
constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const handler = new lambda.Function(this, 'Function', {
code: lambda.Code.fromAsset(`${__dirname}/lambda-code`),
runtime: lambda.Runtime.NODEJS_14_X,
handler: 'index.handler',
});
const api = new apigateway.RestApi(this, "widgets-api", {
restApiName: "Widget Service",
description: "This service serves widgets."
});
const getWidgetsIntegration = new apigateway.LambdaIntegration(handler, {
requestTemplates: { "application/json": '{ "statusCode": "200" }' },
});
new lambda.Alias(this, "LambdaAlias", {
aliasName: "widget-alias",
version: new lambda.Version(this, "LambdaVersion-" + new Date().toISOString(), { lambda: handler }),
});
api.root.addMethod("GET", getWidgetsIntegration); // GET /
}
}
The only difference between this code, and what you posted, is that I don't have the dynamic description (description: "generated at " + new Date().toISOString()) in my Function that you had. That's required, as hotswapping will fail if it detects a change to the description property (as that's not a hotswappable property, at least right now).
⚠️COMMENT VISIBILITY WARNING⚠️
Comments on closed issues are hard for our team to see. If you need more assistance, please either tag a team member or open a new issue that references this one. If you wish to keep having a conversation with other community members under this issue feel free to do so.