我们真的应该在 AWS lambda 运行时重用全局变量吗?

Should we really reuse global variables in AWS lambda runtime?

我引用了 here 中关于 AWS-lambda 服务性能提示的一段非常阴暗的段落。

根据 AWS 团队的说法:

Take advantage of Execution Context reuse to improve the performance of your function. Make sure any externalized configuration or dependencies that your code retrieves are stored and referenced locally after initial execution. Limit the re-initialization of variables/objects on every invocation. Instead use static initialization/constructor, global/static variables and singletons. Keep alive and reuse connections (HTTP, database, etc.) that were established during a previous invocation

让我们暂时忽略故意将变量声明为全局、静态并选择单调的邪恶想法*(就个人而言,这是最不负责任的建议之一)我主要担心的是 open connections.

的使用

我的问题是:

  1. 如果,例如,一个 lambda 调用与另一个调用之间的连接超时,会发生什么情况? AWS 运行时如何 "knows" 否重新使用该连接?

  2. 如果连接被缓冲会怎样?意思是之前的调用有残留?

  3. 这个建议(在调用之间重用连接)在现实生活中是否真的适用?这对我来说似乎很糟糕。

  1. what happens if , eg, the connection times out between one lambda invocations to another? how does the AWS runtime "knows" no to re-use that connection?

  2. what happens if the connection is buffered? meaning there are residues from a previous invocations?

A​​WS 运行时 "know" 根本不知道如何处理它。您的 Lambda 函数需要通过检查连接是否仍然有效来了解这一点,并在连接不再有效时进行处理。

  1. is this advice (re-using connections across invocations) really holds in real life? it's seems very buggish to me.

考虑到 AWS Lambda 运行时环境的现实情况,如果您关心的是减少 Lambda 函数调用的冷启动时间,则此建议绝对有效。然而,它肯定会导致与关系数据库的连接等问题,这就是亚马逊发布 AWS Aurora Data API 的原因。

我通常会尝试遵循此建议在 Lambda 函数中缓存数据,例如通过读取数据库 table 或将 S3 对象加载到内存中来初始化数据结构,但我发现Lambda 函数中的全局范围数据库连接问题带来的麻烦多于其价值,但如果您的 Lambda 函数调用非常频繁,那么这对您来说可能是值得的。