-1

I need to fix a common problem with a lambda that is a cold start issue. while I am using CDK with typescript. I have seen many solutions but did not get the right approach. if any plugin resolves my issue then where I mentioned the logic to invoke the lambda function after a certain period. also need for concurrency feature and cost is also matter while in CDK similar code I defined for a lambda-

const lambda = new aws.lambda.Function("mylambda", {
    code: lambda.Code.fromAsset("/src"),
    handler: "handler",
    timeout: 30
});

How to fix the cold start issue.

  • You can't remove cold starts totally but you can minimize them. It depends on whether your code is doing a lot outside of the handler, deployment package size, size of dependencies, code that runs on import time, etc. Also, the higher traffic you get, the less frequent cold starts happen. – Noel Llevares Nov 28 '21 at 23:02

1 Answers1

3

You can prevent cold starts using Provisioned Concurrency, which will keep a number of lambda instances warm all the time.

To do this in CDK, you need to create an Alias for your function:

const lambdaCode = lambda.Code.fromCfnParameters();
const func = new lambda.Function(this, 'Lambda', {
  code: lambdaCode,
  handler: 'index.handler',
  runtime: lambda.Runtime.NODEJS_12_X,
});
const version = func.addVersion('NewVersion');
const alias = new lambda.Alias(this, 'LambdaAlias', {
  aliasName: 'Prod',
  version,
  // Keeps one instance warm all the time
  provisionedConcurrentExecutions: 1
});

The above example is a slightly modified one from the Alias docs.

gshpychka
  • 8,523
  • 1
  • 11
  • 31
  • const func = new lambda.Function(this, 'Lambda', { code: lambdaCode, handler: 'index.handler', runtime: lambda.Runtime.NODEJS_12_X, currentVersionOptions: { provisionedConcurrentExecutions: 5 } }); this.func.currentVersion; – prabhakar srivastava Dec 02 '21 at 07:08
  • this one is working but provision concurrency is too much costly with the normal approach. we can trigger the lambda with cloud watch event but we need concurrency as well with a different approach. cost is also matter – prabhakar srivastava Dec 02 '21 at 07:10
  • 2
    My answer describes the solution to eliminate cold starts. Yes, it costs money. – gshpychka Dec 02 '21 at 07:23
  • 2
    What is the difference between `currentVersionOptions: { provisionedCocurrencyExecutions: N }` and @gshpychka answer? The answer in the comment is much more simple and elegant – Anh Tú Mai Oct 20 '22 at 08:14