在Serverless框架Step Functions中配置预置并发以保持Lambda函数预热

本文详细介绍了在AWS Step Functions中使用Serverless框架时,如何正确配置Lambda函数的预置并发以避免冷启动问题。文章通过具体示例演示了配置步骤和注意事项。

在Serverless框架Step Functions中配置预置并发

这将是一篇简短但希望有用的文章,适用于任何在使用AWS Step Functions时试图保持Lambda函数预热的人。这并不像我最初想象的那么简单——仅仅调整函数配置中的provisionedConcurrency值是不够的。简而言之,必须在Step Function配置中指定预置并发别名,状态机才能使用它。

让我们从一个最小的Step Function示例开始:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
service: step-function-test
frameworkVersion: '3'

provider:
  name: aws
  runtime: python3.10
  timeout: 60
  memorySize: 512
  versionFunctions: false
  stage: ${opt:stage, "sbx"}
  region: us-east-1

functions:
  hello:
    handler: handler.hello
  hi:
    handler: handler.hi

stepFunctions:
  stateMachines:
    helloStepFunc:
      name: 'hello'
      definition:
        Comment: "A Hello World example"
        StartAt: HelloWorld
        States:
          HelloWorld:
            Type: Task
            Resource: !GetAtt hello.Arn
            Next: HiWorld
          HiWorld:
            Type: Task
            Resource: !GetAtt hi.Arn
            End: true

plugins:
  - serverless-step-functions

当然,这些Lambda函数没有配置provisionedConcurrency,可能会遭受冷启动。如果我们简单地在serverless.yml中启用它,部署并再次调用Step Function,我们将看不到改进。查看日志,我们可以识别被调用的版本:

Step Function当前配置为调用Lambda的$LATEST版本。配置预置并发的文档描述了这个问题:

预置并发在函数的未发布版本($LATEST)上不受支持。在配置预置并发之前,请确保您的客户端应用程序没有指向$LATEST

在这种情况下,客户端应用程序就是状态机配置。使用Serverless框架对provisionedConcurrency的内置支持,我们可以启用它并推断出别名。Serverless像这样生成预置并发别名:

1
2
3
getLambdaProvisionedConcurrencyAliasLogicalId(functionName) {
    return `${this.getNormalizedFunctionName(functionName)}ProvConcLambdaAlias`;
  }

以下是更新后的serverless.yml

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
service: step-function-test
frameworkVersion: '3'

provider:
  name: aws
  runtime: python3.10
  timeout: 60
  memorySize: 512
  versionFunctions: false
  stage: ${opt:stage, "sbx"}
  region: us-east-1

functions:
  hello:
    handler: handler.hello
    provisionedConcurrency: 3
  hi:
    handler: handler.hi
    provisionedConcurrency: 3

stepFunctions:
  stateMachines:
    helloStepFunc:
      name: 'hello'
      definition:
        Comment: "A Hello World example"
        StartAt: HelloWorld
        States:
          HelloWorld:
            Type: Task
            Resource: !Ref HelloProvConcLambdaAlias
            Next: HiWorld
          HiWorld:
            Type: Task
            Resource: !Ref HiProvConcLambdaAlias
            End: true

plugins:
  - serverless-step-functions

请注意,当与Ref一起使用时,AWS::Lambda::Alias资源直接返回ARN。

现在,我们可以使用sls invoke stepf -n helloStepFunc调用Step Function,并在CloudWatch日志中看到版本已更新:

comments powered by Disqus
使用 Hugo 构建
主题 StackJimmy 设计