[英]Performance of Cloud Functions for Firebase with outbound networking
當我在 Cloud Functions 中運行以下代碼時,它需要超過 2 秒。
當我在本地運行它時,大約需要 600 毫秒。
可能的原因是什么?
import * as functions from 'firebase-functions'
import axios from 'axios'
const headers = { 'accept': 'application/json', 'x-access-key': '...', 'x-access-secret': '...' }
exports.functionName = functions.https.onRequest(async (req, res) => {
try {
console.log('request 1 start')
const response1 = await axios.get(`https://api.sample.com/users/${req.body.userId}`, { headers })
console.log('request 1 completed')
const response2 = await axios.post(`https://api.sample.com/contents1/${response1.data.id}`, {}, { headers })
console.log('request 2 completed')
const response3 = await axios.post(`https://api.sample.com/contents2/${response2.data.id}`, {}, { headers })
console.log('request 3 completed')
res.send(response3)
} catch (error) {
res.send(error)
}
})
在 Cloud 中,每個異步請求 ( axios.get/post
) 占用近 1 秒。
我想我嘗試了 Firebase 官方文檔中描述的所有方法。
header
對象就是一個const httpAgent = new http.Agent({ keepAlive: true })
await axios.get(`https://api.sample.com/users/${req.body.userId}`, { headers, httpAgent })
需要考慮的重要事項:
它們可以部署在地球的另一端,而不是您和您的 API。 您可以通過指定數據中心來控制您希望將函數部署到何處。 https://firebase.google.com/docs/functions/locations
我們所有的函數代碼如下所示:
const DEFAULT_FUNCTIONS_LOCATION = "us-east4";
const runtimeOpts: Record<string, "512MB" | any> = {
timeoutSeconds: 120,
memory: "512MB",
};
const getCustomAnalysis = functions
.region(DEFAULT_FUNCTIONS_LOCATION)
.runWith(runtimeOpts)
您可以在不同的數據中心/在一個項目中部署功能。 順便說一句,您需要在調用它們時指定它。
我們在我們的一個項目中確實有這個。 整個項目部署在歐盟(因為合法)。 一個功能在美國 - 調用美國 API。 一旦數據進入 GCP 功能並傳送到另一個 GCP 數據中心,它們就會使用Google 高級網絡。 但是,如果您不受限制,只需將您的整個項目部署到您的用戶/您的 API 附近即可。
你的 GCP 項目還干凈嗎? 您不使用任何 VPC 網絡? 網絡可能很混亂,它們也可能是 GCP 數據中心和您的 API 數據中心之間的“問題”。
作為更多測試的提示:嘗試不同的網址並測量速度。 但我不認為這是一般的 CF 問題。
順便說一句,我在從 Firestore 檢索大量數據時遇到了類似的問題。 然而,當我們加速函數時,我們注意到了不同(使用更多的內存會給你更多的 MHz)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.