【问题标题】:Is there a penalty for having multiple small Firebase functions for same subscription?为同一订阅拥有多个小型 Firebase 功能是否会受到处罚?
【发布时间】:2020-07-22 13:21:54
【问题描述】:

我有一个 React Web 应用程序,它使用 Firestore 作为其数据库,每个 Firestore 集合有多个 (10+) Firebase 函数,用于发布到社交媒体等副作用:

exports.onUserSignUp = functions.auth.user().onCreate(user => {
  // Insert into users collection
  // Insert into profiles collection
  // Notify via Discord webhook
  // insert into history collection to keep track of actions performed by users
})

exports.onCityCreate = functions.firestore.document('cities/{cityId}').onCreate(doc => {
  // Notify via Discord webhook
  // Send tweet
  // Update cache in a collection
  // Insert into history collection to keep track of actions performed by users
})

等等

在 Firebase 函数教程中,他们经常建议您声明一个 Firebase 函数以获得这样的副作用:

exports.onCityCreate = functions.firestore.document('/cities/{documentId}')
  .onCreate((snap, context) => {
    ...
  })

如果您有一个小的副作用,这是有道理的 - 例如。通过 Twitter REST API 发送推文 - 但随着时间的推移,我添加了越来越多的副作用,例如通过 webhook 发送到 Discord、将新记录插入其他数据库、缓存数据等等。

当我在 AWS 中了解 lambda 时,我被教导要使我的函数变得很小,并且仅限于一项工作,而不是 1 个大型函数。这意味着如果一种副作用失败,它不会降低其他副作用。它使代码更容易理解和阅读。它使调试更容易。

所以上面的函数可以拆分到每个作业:

exports.sendTweetOnCityCreate =  functions.firestore.document('cities/{cityId}').onCreate(doc => {
  // send tweet via REST API
})

exports.sendDiscordOnCityCreate =  functions.firestore.document('cities/{cityId}').onCreate(doc => {
  // send Discord message via webhook
})

exports.updateCitiesCache =  functions.firestore.document('cities/{cityId}').onCreate(doc => {
  // update a record in a cache collection with some kind of tally etc.
})

exports.recordCityInHistory =  functions.firestore.document('cities/{cityId}').onCreate(doc => {
  // insert into history collection to keep track of actions performed by users
})

为每个副作用声明一个小的、独立的函数而不是像我目前拥有的那样“完成所有”的 1 个大型函数,是否会受到惩罚(性能 - 速度较慢或财务 - 来自 Google 的更多成本)?强>

【问题讨论】:

    标签: firebase google-cloud-functions


    【解决方案1】:

    性能不会有明显变化。无论您有多少函数,事件从 Firestore 传递到函数所需的时间基本相同。

    使用多合一方法最糟糕的情况是您的函数无法大规模扩展,因为每个函数的上限为 1000 个并发服务器实例来处理其事件。但这样的例子很多。如果你拆分你的函数,它们每个都可以扩展到 1000 个服务器实例。不过,这只会在非常大的范围内有用。

    【讨论】:

    • 您可以为您的想法添加一些参考吗?
    猜你喜欢
    • 1970-01-01
    • 2018-09-02
    • 1970-01-01
    • 2011-05-31
    • 1970-01-01
    • 2017-11-23
    • 2021-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多