How to keep google functions warm?
One of our projects uses google functions a lot. Both HTTP and onCall functions.
It was a surprise for us that functions sometimes took more than 2–4 seconds to start execution. This issue is also known as a cold start.
Let’s imagine the situation: you have 3 google functions. First check user email address domain, second search your database for already existing email, and third check user phone number. When all these functions are not warm user can get a significant delay before the front-end will react.
To mitigate cold start we created scheduled jobs that call our functions every 5 minutes in the needed time range.
This task is trivial for HTTP functions but still has some nuances:
- When the function is called by Scheduler we need to exit as soon as possible. To achieve this you might add conditions at the very beginning of the function;
- onCall functions accept only Content-Type=application/json and it is not possible to set this header in Google Scheduler web interface (that’s why we had to use gcloud cli).
Examples of functions:
myHttpFunction: functions.https.onRequest((request, response) => {
// Check if available warmup parameter.
// Use request.query.warmup parameter if warmup request is GET.
// Use request.body.warmup parameter if warmup request is POST.
if (request.query.warmup || request.body.warmup) {
return response.status(200).type('application/json').send({status: "success", message: "OK"});
}
});myOnCallFunction: functions.https.onCall((data, context) => {
// Check if available warmup parameter.
if (data.warmup) {
return {"success": true};
}
});
Gcloud cli examples of warmup scheduled jobs creation:
gcloud --project="my-awesome-project" scheduler jobs create http warmupMyOnCallFuntion --time-zone "America/Los_Angeles" --schedule="*/5 5-23 * * *" --uri="https://us-central1-my-awesome-project.cloudfunctions.net/myOnCallFuntion" --description="my warmup job" --headers="Content-Type=application/json" --http-method="POST" --message-body="{\"data\":{\"warmup\":\"true\"}}"gcloud --project="my-awesome-project" scheduler jobs create http warmupMyHttpFuntion --time-zone "America/Los_Angeles" --schedule="*/5 5-23 * * *" --uri="https://us-central1-my-awesome-project.cloudfunctions.net/myHttpFuntion?warmup=true" --description="my warmup job" --headers="Content-Type=application/json" --http-method="GET"
I hope this article will help you save time :)