超时时重试 AWS lambda 函数的最佳解决方案

Best solution to retry AWS lambda function when it got timeout

我有一个严肃的问题,我需要你的帮助。在网上找了好久也没找到解决办法

我制作了一个机器人来获取数据,这是一项非常繁重的任务,因为我需要设置一个抓取工具,然后它通过许多步骤(登录、注销、点击、提交按钮等)从网页中提取数据,并且得到这个结果后,它会post到API做报告。

我在每天的特定时间使用 Cloudwatch 事件来创建我的 lambda 函数运行。

问题是虽然我将我的 lambda 函数设置为最大设置(3GB RAM,超时 15 分钟,指标是 2019 年 1 月的指标),但有时我的 lambda 函数在执行时失败(可能是抓取任务太耗时很多步骤或者我尝试抓取的网页不稳定)而且很少失败,我认为大约只有 5%。

但我想知道是否有任何方法可以处理这种情况,我希望我的 lambda 函数可以在失败时自动重试而无需手动操作。

您的 lambda 已重试,因为来自 cloudwatch 事件的触发器是异步的。 (请参阅下面的文档) 我会为您的 lambda 设置一个 DLQ,然后从那里重新处理。

来自文档 (aws lambda event sources)

Error handling for a given event source depends on how Lambda is invoked. Amazon CloudWatch Events invokes your Lambda function asynchronously. For more information on how errors are retried, see AWS Lambda Retry Behavior.

And: (aws lambda retry behaviour)

Asynchronous invocation – Asynchronous events are queued before being used to invoke the Lambda function. If AWS Lambda is unable to fully process the event, it will automatically retry the invocation twice, with delays between retries. If you have specified a Dead Letter Queue for your function, then the failed event is sent to the specified Amazon SQS queue or Amazon SNS topic. If you don't specify a Dead Letter Queue (DLQ), which is not required and is the default setting, then the event will be discarded. For more information, see AWS Lambda Function Dead Letter Queues.

这是一个完美的示例 StepFunction 您可以通过 CloudWatch Event 而不是 lambda 安排它。

StepFunction 可以调用您的 lambda 并在需要时使用可配置的指数退避处理失败时的重试逻辑。

这是一个 StepFunction 的例子

{
  "Comment": "Call lambda with retry",
  "StartAt": "Scraper",
  "States": {
    "Scraper": {
      "Type": "Task",
      "Resource": "<LAMBDA_ARN>",
      "Retry": [
        {
          "ErrorEquals": [
            "States.ALL"
          ],
          "IntervalSeconds": 20,
          "MaxAttempts": 5,
          "BackoffRate": 2
        }
      ],
      "End": true
    }
  }
}

虽然已经给出了答案,但在本文中我解释了问题并分享了一个处理 lambda 的步函数示例。

Lambdas with step function