Why does performance degrade when a serverless function exits without completing Promise.all() successfully in Firebase Cloud Function?
In the past, I used to run Promise.all() without await in Cloud Function.
Then, this would cause the Cloud Function to exit without waiting for Promise.all() to complete.
As a result, my Cloud Function sometimes worked correctly and sometimes did not.
This is problem, so we fixed it to await Promise.all() to wait for all the processing to finish.
Then, the Cloud Function, which used to take several minutes to complete, now completes in a few seconds.
I am curious about this issue and would like to understand it. Why is it that when I fix all async process to wait, the function completes immediately?
Thanks.
It's simply the serverless model of Google Cloud. You pay when you process traffic, I mean, when your request is handled.
When you have sent a response, you stop to pay, and so, Google limit the CPU available to your Cloud Functions (about 5% of the CPU available). Indeed, if you don't pay, Google threshold the CPU and propose the processing power to other Cloud Function that handle traffic, and which pays for it.
To free the memory reserved by your cloud functions, after a while (about 15 minutes) Google stop the instance.
So, in your case, if you send the response before the end of the processing, the processing will continue in background with a low percentage of CPU. Either it finishes or it doesn't have the time to finish before the instance stop;
Now, because you await all the promises before sending the response, you have 100% of the CPU power for you (because you pay for it) and you finish quickly the processing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With