gpt4 book ai didi

Firebase Cloud Functions - 查询 Firestore 时响应缓慢

转载 作者:行者123 更新时间:2023-12-03 10:05:28 24 4
gpt4 key购买 nike

我在 Firebase 中有一个简单的 Cloud Function,它在 http POST 中获取 JSON 并将其保存到 Firestore 集合中。它分配了 512MB 内存。

这个云功能的性能很差。如果连续执行,往返时间为 200-600 毫秒,如果不经常执行(每 5-10 分钟),则可能需要 4-10 秒。我了解冷启动问题,但在 AWS 上,我从未见过如此缓慢或如此频繁的冷启动。

我的代码如下 - 我很感激任何关于如何提高性能的见解。

'use strict';

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const db = admin.firestore();

const express = require('express');
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// CORS Express middleware to enable CORS Requests.
const cors = require('cors');
app.use(cors({ origin: true }))

app.post('/submitResponse', (req, res) => {
console.log('/submitResponse');

if (!req.body.info)
res.status(422).send()

const payload = req.body.info;
console.log(payload);

const responses = db.collection("responses")

responses.add({
payload: payload,
timestamp: admin.firestore.FieldValue.serverTimestamp()
}).then(function(docRef) {
console.log("Response written with ID: ", docRef.id);
res.status(200).send(JSON.stringify(docRef.id))
})
.catch(function(error) {
console.error("Error adding document: ", error);
});
});

exports.app = functions.https.onRequest(app);

最佳答案

some of the comments : 在撰写本文时 Cloud Firestore for Firebase实际上是仍处于测试阶段 .

Firestore is in Beta

但在这种情况下,Firestore 可能不是罪魁祸首。云功能的冷启动时间很可能会掩盖您正在进行的任何数据库操作。

无论何时,云功能都需要时间来启动新实例

  • 部署新功能/首次调用
  • 实例已回收
  • 扩展以处理负载(请求命中新实例)

  • 有一个 section about Cloud Function performance这提到了通过最小化模块依赖关系可以获得的潜在 yield 。

    Because functions are stateless, the execution environment is often initialized from scratch (during what is known as a cold start). When a cold start occurs, the global context of the function is evaluated.

    If your functions import modules, the load time for those modules can add to the invocation latency during a cold start. You can reduce this latency, as well as the time needed to deploy your function, by loading dependencies correctly and not loading dependencies your function doesn't use.



    另请查看真棒 Cloud Performance Atlas video on the topic其中提到了以下提示:
  • 减少库依赖
  • 使用更多(大多数)流行版本的包,因为它更有可能已经被缓存
  • 启动时不重要的延迟加载模块

  • 在库依赖的情况下,最容易实现的目标是摆脱可能实现自己和/或仅使用一个或几个函数但需要整个库的依赖项(我在看着你,lodash)。

    关于Firebase Cloud Functions - 查询 Firestore 时响应缓慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49198208/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com