英文:
How to know when an synchronously-invoked Lambda function has timed out
问题
我从我的主要Lambda函数(A)中调用另一个Lambda函数(B)。 B的超时设置为两分钟。 实际上,我会多次调用B,并希望尽可能多地在两分钟内完成它们。 如果它们中的任何一个在两分钟内未完成(它们的执行时间高度变化且难以预测),那我就只能放弃这些未完成的结果。
我如何检测B何时超时,以便我可以继续执行我的其余代码? 我原以为Lambda会在超时时返回带有某种状态的响应,但似乎由于函数超时,它完全中断了,没有什么可以返回状态的。
实际上,我只会得到一个异常抛出,说签名已在五分钟后过期。 但这没有用,因为这意味着在函数超时和抛出此异常之间已经过去了三分钟(这不仅会使A也超时,而且在我为A的运行付费却得不到任何结果)。
我可以发布代码,但只是用于调用Lambda函数的标准C#代码。
编辑:请注意,B在第三方库中运行阻塞代码,因此我不能有任何可以预期超时并返回带有响应的函数中断的东西。
英文:
I invoke another Lambda function (B) from my main Lambda function (A). B has its timeout set to two minutes. I actually invoke B several times, and I want as many of them to complete as possible within two minutes. If any of them don't complete within two minutes (they're highly variable and unpredictable), I just live without the result from those ones.
How can I detect when B has timed out, so I can carry on with the rest of my code? I was expecting Lambda to return a response with some kind of status when it times out, but it seems that since the function times out, it just craps out altogether and there's nothing to return a status.
All I actually get is an exception thrown saying that the signature has expired after five minutes. This is useless though because it means three minutes have elapsed between the function timing out and this exception being thrown (whilst not only risking A timing out as well, but also whilst I'm paying AWS for running A for nothing).
I can post the code but it's just the standard C# code for invoking a Lambda function.
Edit: Note that B runs blocking code in a third party library, so I can't have anything that anticipates the timeout and returns out of the function with a response.
答案1
得分: 1
- Lambda函数A将超时时间与其余请求负载一起发送给Lambda函数B。
- Lambda函数B然后设置两个任务 - 一个(B1)执行工作,另一个(B2)等待超时时间。
- 然后通过Task.WhenAny()调用B1和B2。
- 如果B1首先完成,则返回计算结果。
- 如果B2首先完成,则返回一个超时的结果。
- 无论哪种情况,B都会干净地完成,并且实例变得可用于另一个调用(或者如果不再使用则关闭)。
这意味着我可以在A中计算超时时间,如果B能在足够的时间内给我一个结果,那就太好了。如果不能,那也没关系,B永远不会运行得比我需要的时间长,因此不会浪费资源。
英文:
I came up with a relatively simple workaround.
- Lambda function A sends Lambda function B the timeout time along with the rest of the request payload.
- Lambda function B then sets up two tasks - one (B1) to do the work and another (B2) that waits for the timeout time.
- B1 and B2 are then invoked via Task.WhenAny().
- If B1 completes first then I return the calculation result.
- If B2 completes first then I return a result saying that it timed out.
- In either case, B completes cleanly and the instance becomes available for another invocation (or closes if it isn't used again of course).
This means that I can calcuate the timeout in A, and if that's enough time for B to give me a result then great. If it doesn't then that's okay too, and B never runs for longer than I need it to, and therefore doesn't waste resources.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论