I am trying to update documents using Firebase Cloud Functions. My document updates do not need to consider existing values, and since they primarily involve single document updates with minimal risk of conflicts, I am proceeding without transaction handling.
The issue is that even a single test case takes approximately 3 minutes to complete. As a junior developer, I have never experienced such delays with Cloud Functions before, and I am struggling to identify the root cause of the problem.
Below is my full code and the logs generated from it:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
exports.authenticator = functions.region('asia-northeast1').https.onRequest(async (req, res) => {
const startTime = new Date().getTime();
console.log("Function execution started at: ", new Date().toISOString());
if (req.method !== "POST") {
console.log("Method Not Allowed");
return res.status(405).send("Method Not Allowed");
}
const data = req.body;
if (!data || !data.data || !Array.isArray(data.data)) {
console.log("Bad Request");
return res.status(400).send("Bad Request");
}
res.status(200).send("Processing...");
console.log("Process started at: ", new Date().toISOString());
for (const item of data.data) {
if (!item || !item.phoneNum || !item.authCode) {
console.log("Invalid data: ", item);
continue;
}
try {
const updateStart = new Date().getTime();
console.log("Update started for authCode: ", item.authCode, " at: ", new Date().toISOString());
await admin.firestore().collection("auth").doc(item.authCode).update({
phoneNum: item.phoneNum,
verified: true,
timestamp: admin.firestore.FieldValue.serverTimestamp()
});
const updateEnd = new Date().getTime();
console.log("Success: ", item.authCode, " at: ", new Date().toISOString(), " Update took: ", (updateEnd - updateStart) / 1000, " seconds");
} catch (err) {
console.error(`Error processing ${item.authCode}:`, err);
}
}
const endTime = new Date().getTime();
console.log("Process ended at: ", new Date().toISOString());
console.log("Total execution time: ", (endTime - startTime) / 1000, " seconds");
});
Function execution started Function execution started at:
2024-07-09T21:28:39.167Z Process started at: 2024-07-09T21:28:39.188Z
Update started for authCode: 519504f79458497cb8c4709739fbc877 at:
2024-07-09T21:28:39.188Z Function execution took 80 ms, finished with
status code: 200 Success: 519504f79458497cb8c4709739fbc877 at:
2024-07-09T21:31:36.657Z Update took: 177.469 seconds Process ended
at: 2024-07-09T21:31:36.957Z Total execution time: 177.79 seconds
The region for my Cloud Functions is asia-northeast1, and Firestore is in asia-northeast3. I changed the regions due to concerns about potential region-related issues, but I have previously handled updates quickly even in the us-central1 region.
For your reference, my code receives data processed by Gmail through a POST request from Google Apps Scripts.