Google Cloud Functions 执行时间和限制

Google Cloud Functions Execution Time & Limitations

我有一个非常简单的像素服务器,它检索客户端请求 header/params/body 以将消息发布到 pub/sub 主题,它是用云函数编写的。在理想情况下,该函数的执行时间不会超过 5-10 毫秒,最佳情况下少于 5 毫秒。

但是,在日志中,我看到一些函数调用花费了 >500 毫秒

我正在尝试了解云函数冷启动和自动缩放的行为以与成本相关联,因为如果 10% 的调用由于寒冷而运行速度慢 100 倍,我们最终将多支付 50% start/autoscaling

社区中的某个人能否指出克服这种情况的最佳实践,以节省成本并提高由于冷启动而导致的性能,因为我们需要处理超过 100M 的请求?此外,由于我们的调用量 (100M+) 云函数/pub-sub 有任何 invocation/scale-up 限制,我们需要开始考虑或考虑非无服务器解决方案 (wink)?

best practices 中的一些提示可以帮助您减少性能问题:

  • 删除不用的依赖项

    If your functions import modules, the load time for those modules can add to the invocation latency during a cold start. You can reduce this latency, as well as the time needed to deploy your function, by loading dependencies correctly and not loading dependencies your function doesn't use.

  • 使用全局变量在以后的调用中重用对象

    There is no guarantee that the state of a Cloud Function will be preserved for future invocations. However, Cloud Functions often recycles the execution environment of a previous invocation. If you declare a variable in global scope, its value can be reused in subsequent invocations without having to be recomputed.

  • 对全局变量进行惰性初始化

    If you initialize variables in global scope, the initialization code will always be executed via a cold start invocation, increasing your function's latency. If some objects are not used in all code paths, consider initializing them lazily on demand.

关于访问 Google API,当您从 PUB/SUB 获取消息时,最好在全局范围内创建 Pub/Sub 客户端对象。在 public documentation.

中有更多信息和示例代码。

Cloud Functions 还需要一些时间来扩展,因此如果请求量过高,这也可能会导致您一直遇到的高延迟。一种解决方法是创建两个 Cloud Functions 订阅您的 Pub/Sub 主题,或者甚至为这 2 个功能设置 2 个单独的主题,然后您将在这两个中分配工作量。