You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firebase事务执行缓慢如何优化?附相关代码求助

问题:Firestore事务函数运行缓慢,如何优化?

我有一个函数,每当用户创建新的活动参与文档时触发执行。由于部分场景下新参与文档会快速连续创建,为避免竞态条件我使用了事务,但该函数通常需要40-120秒才能完成运行。以下是相关代码:

export const esLatDailyAggr = async (
  uid: admin.firestore.DocumentReference,
  eventTypeId: admin.firestore.DocumentReference,
  timestamp: Date,
  clientId: admin.firestore.DocumentReference,
  year: number,
  month: number,
  day: number) => {
  const startTime = Date.now();
  console.log("Starting to update daily aggr data.");
  const docId = `${uid.id}-${year}-${month}-${day}`; // create composite key

  const statsRefAggr = admin.firestore().collection("dailyAggregateData");
  const queryAggr = statsRefAggr.doc(docId);
  await admin.firestore().runTransaction(async (transaction) => {
    const queryAggrSnapshot = await transaction.get(queryAggr);

    if (!queryAggrSnapshot.exists) { // check if document exists
      console.log(
        docId, " Daily doc not found. Creating new one by new Participation");
      // create new document with composite key
      transaction.set(queryAggr, {
        uid: uid,
        year: year,
        month: month,
        day: day,
        NoOfParticipations: 1,
        ActiveClientsId: [clientId],
        ActiveEventTypeId: [eventTypeId],
        timestamp: timestamp,
      });
    } else {
      // update existing document
      transaction.update(queryAggr, {
        NoOfParticipations: admin.firestore.FieldValue.increment(1),
        ActiveClientsId: admin.firestore.FieldValue.arrayUnion(clientId),
        ActiveEventTypeId: admin.firestore.FieldValue.arrayUnion(eventTypeId),
      });
      console.log(docId, " Daily aggr data updated by new Participation.");
    }
  });
  const endTime = Date.now();
  console.log("Daily Aggr Data function finished. Running Time: ",
  endTime - startTime, "ms");
};

优化方案

  • 用原子操作+合并写入替代事务
    你代码里用到的increment和arrayUnion本身就是Firestore的原子操作,完全不需要事务来保障竞态安全。事务的锁机制和重试逻辑反而会在高并发场景下拖慢执行速度。直接使用set方法的merge: true参数,就能实现“不存在则创建,存在则更新”的逻辑,性能提升非常明显。

    修改后的代码:

    export const esLatDailyAggr = async (
      uid: admin.firestore.DocumentReference,
      eventTypeId: admin.firestore.DocumentReference,
      timestamp: Date,
      clientId: admin.firestore.DocumentReference,
      year: number,
      month: number,
      day: number) => {
      const startTime = Date.now();
      console.log("Starting to update daily aggr data.");
      const docId = `${uid.id}-${year}-${month}-${day}`;
    
      const queryAggr = admin.firestore().collection("dailyAggregateData").doc(docId);
    
      // 合并写入:文档不存在则创建,存在则仅更新指定字段
      await queryAggr.set({
        uid: uid,
        year: year,
        month: month,
        day: day,
        NoOfParticipations: admin.firestore.FieldValue.increment(1),
        ActiveClientsId: admin.firestore.FieldValue.arrayUnion(clientId),
        ActiveEventTypeId: admin.firestore.FieldValue.arrayUnion(eventTypeId),
        timestamp: timestamp,
      }, { merge: true });
    
      const endTime = Date.now();
      console.log("Daily Aggr Data function finished. Running Time: ", endTime - startTime, "ms");
    };
    
  • 精简日志输出
    高并发场景下频繁打印日志会占用额外资源,建议只保留函数启动、结束的关键日志,或者仅在异常时打印,减少I/O开销。

  • 优化函数运行环境(针对Cloud Function)
    如果这是Google Cloud Function,慢启动可能是原因之一:

    • 升级函数实例配置(比如增加内存配额),提升CPU和网络性能
    • 启用函数预热机制,避免冷启动延迟
    • 清理不必要的依赖包,缩小部署包体积,加快初始化速度

内容的提问来源于stack exchange,提问作者Attila

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 23:08:11