调用了一次 lambda 函数,它执行了两次 [英] Called a lambda function once, it's executed twice

查看:35
本文介绍了调用了一次 lambda 函数,它执行了两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这更像是一个问题而不是一个问题,但是,之前有人经历过吗?有谁知道如何预防吗?

This is more of a concern than a question, but still, has anyone experienced this before? Does anyone know how to prevent it?

我有一个 lambda 函数 (L1),它调用第二个 lambda 函数 (L2),全部用 NodeJs 编写(运行时:Node.Js 8.10,aws-sdk 应该是 v2.488.0 - 但是我只是从文档中粘贴它).简而言之,L1 应该调用 L2,而当它调用时,L2 会执行两次!我通过将日志写入 CloudWatch 发现了这一点,我可以看到一个 L1 日志和两个 L2 日志.

I have a lambda function (L1) which calls a second lambda function (L2) all written in NodeJs (runtime: Node.Js 8.10, and aws-sdk should be v2.488.0 - but I'm just pasting that from the documentation). The short story is that L1 is supposed to call L2, and when it does L2 is executed twice! I discovered this by writing logs to CloudWatch and I could see one L1 log and two L2 logs.

这是 L1 和 L2 的简化版本.

Here's a simplified version of L1 and L2.

L1:

const AWS = require('aws-sdk');
const lambda = new AWS.Lambda();

module.exports = {
    handler: async (event, context, callback) => {
        const lambdaParams = {
            FunctionName: 'L2',
            Qualifier: `dev`,
            Payload: JSON.stringify({}),
        };

        console.log(`Calling: ${JSON.stringify(lambdaParams)}`);
        return await lambda.invoke(lambdaParams).promise();
    },
};

L2:

module.exports = {
    handler: async (event, context, callback) => {
        console.log(`L2 called`);
    },
};

在 CloudWatch 中,我可以看到一个 Calling .... 和两个 L2 调用

In CloudWatch I can see one Calling .... and two L2 called!

顺便说一句,这不会一直发生.这是步骤函数过程的一部分,该过程将调用 L1 10k 次.我的代码的编写方式是,如果 L2 执行两次(每次调用),它将使整个过程失败(因为 L2 仅在记录不存在时才向 DB 插入记录,如果存在则失败).到目前为止,我设法记录了这种行为 3 次.他们都处理相同的 10k 项,每次都在不同的迭代中面临问题.

BTW, this does not happen all the time. This is part of a step function process which was going to call L1 10k times. My code is written in a way that if L2 is executed twice (per one call), it will fail the whole process (because L2 inserts a record to DB only if it does not exist and fails if it does). So far, I managed to log this behaviour three times. All of them processing the same 10k items, facing the issue at a different iteration each time.

有人有同样的经历吗?或者更好的是,知道如何确保一次调用只导致一次执行?

Does anyone have the same experience? Or even better, knows how to make sure one call leads to exactly one execution?

推荐答案

你的 lambda 函数必须是幂等的,因为它可以在不同的情况下被调用两次.

Your lambda function must be idempotent, because it can be called twice in different situations.

https://aws.amazon.com/premiumsupport/knowledge-center/lambda-function-idempotent/

https://cloudonaut.io/your-lambda-function-might-execute-twice-deal-with-it/

这篇关于调用了一次 lambda 函数,它执行了两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆