我有一个非常简单的像素服务器,它可以检索客户端请求标头/参数/正文以将消息发布到pub / sub主题,并且它是用云函数编写的。在理想情况下,该函数的执行时间不会超过5-10毫秒,最好情况下少于5毫秒。
但是然后,在日志中,我看到一些函数调用耗时超过500毫秒
我试图了解云功能冷启动和自动缩放的行为以与成本相关,因为如果由于冷启动/自动缩放而导致10%的调用运行速度慢100倍,我们最终将多支付50%
Could someone from the community point out the best practices to overcome this scenario to save cost & improve performance due to cold-start as we need to deal more than 100M request? Also, due to our amount of invocations (100M+) does cloud function / pub-sub comes with any invocation/scale-up limitations we need to start considering or think of a non-serverless solution (wink)?
There are several tips from the best practices that may help you reduce the performance issues:
Remove unused dependencies
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.
Use global variables to reuse objects in future invocations
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.
Do lazy initialization of global variables
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.
Also regarding the access to Google APIs, as you are fetching messages from PUB/SUB, it's better to create the Pub/Sub client object in global scope. There's more information and a sample code regarding that in the public documentation.
云功能还需要一些时间来扩展,因此,如果请求数量过多,这也可能会导致您遇到的高延迟。一种解决方法是,创建两个订阅您的发布/订阅主题的Cloud Functions,或者为这两个功能创建2个单独的主题,然后将工作量分配到这两个中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句