Firestore云函数执行耗时过长问题排查求助
Firestore Cloud Function 执行耗时过长问题排查及解决
我有一个监听Firestore文档创建的Cloud Function,功能正常但执行任务需要数分钟。以下是初始代码:
export const incrementUserCategoryCounter = functions.firestore .document("imgs/{imgDocId}") .onCreate(async (snapshot, context) => { const imgData = snapshot.data(); const catId = imgData.catId; const uid = imgData.cid; const userCatDocRef = db.collection(`users/${uid}/categories/`).doc(catId); const catDocRef = db.collection("categories").doc(catId); userCatDocRef .get() .then((doc: any) => { if (doc.exists) { userCatDocRef .update({...}) .then(() => { console.log("Transaction success! Increment for id", catId); }) .catch((err: string) => { console.log("Transaction failure:", err); }); } else { userCatDocRef.create({...}); catDocRef.update({...}); console.log( "No doc for this category, doc now created with counter 1." ); } }) .catch((err: string) => { console.log("Transaction failure:", err); }); });
对应的函数日志如下:
2023-11-13T07:28:11 No doc for this category, doc now created with counter 1. 2023-11-13T07:24:56 Function execution took 162 ms, finished with status: 'ok' 2023-11-13T07:24:56 Function execution started
仅完成这些简单的更新/添加操作就需要3分钟,请问哪里出错了?
编辑说明
修改代码后,执行耗时降至1600ms:
export const incrementUserCategoryCounter = functions.firestore .document('imgs/{imgDocId}') .onCreate(async (snapshot, context) => { const imgData = snapshot.data(); const catId = imgData.catId; const uid = imgData.cid; const userCatDocRef = db.collection(`users/${uid}/categories/`).doc(catId); // const catDocRef = db.collection('categories').doc(catId); try { const userCatDoc = await userCatDocRef.get(); if (userCatDoc.exists) { const doc = userCatDoc.data()!; let newLast10 = {...}; ... await incUserCat(uid, catId, newLast10, 1); } else { await userCatDocRef.create({...}); console.log('No doc, adding it.'); } await incCat(catId, 1); return null; } catch (err) { console.log('Transaction failure:', err); return null; } });
问题原因及解决分析
核心问题是初始代码未正确处理异步操作的生命周期:
- 初始代码使用
.then()链式调用,但没有返回这些异步操作的Promise,导致Cloud Function在主函数执行完毕后就标记为执行完成,而实际的数据库操作还在后台异步运行。此时Cloud Function可能会被强制终止或进入闲置状态,导致后续操作延迟,最终出现日志时间顺序混乱(函数完成日志早于操作完成日志)的情况。 - Cloud Function要求必须等待所有异步任务完成后返回Promise或值,否则无法正确感知任务结束时机。
修改后的代码解决了这个问题:
- 使用
async/await替代.then()链式调用,同步化异步流程,确保每一步数据库操作都等待完成后再执行下一步。 - 所有异步操作(
get()、create()、自定义函数incUserCat()/incCat())都通过await等待完成,保证函数在所有任务结束后才返回。 - 用
try/catch统一捕获异常,避免未处理的Promise rejection导致的异常情况。
内容的提问来源于stack exchange,提问作者Bourbon
相关产品推荐
相关产品推荐

