skip to Main Content

I want to understand what would be the better approach to scale the Cloud Functions.

Single or multiple triggers on the same RTDB node?

I have to perform several functions when data on a particular node in RTDB is created, updated, or deleted. For example, one function is to maintain the total count of records. Another is to send the data to third-party services like Algolia, etc. Is it better to add multiple triggers, depending on the number of functions to perform, or a Single trigger performing all the functions?

var ref = firebase.database.ref().child('notes/{id}');

Multiple triggers:

ref.onWrite((change, context) => {
 // maintain count
 // ...
});

ref.onWrite((change, context) => {
 // send the data to third party
 // ...
});

Single trigger:

ref.onWrite((change, context) => {
 // maintain count
 // ...
 //Send the data to a third party
 // ...
});

Separate onCreate, onUpdate, onDelete triggers, or one common onWrite trigger?

If I want to perform the functionality on all triggers, create, update, and delete then which one is better to use? Single onWrite trigger or separate onCreate, onUpdate, onDelete triggers?

2

Answers


  1. By default, Cloud Functions for Firebase scales the number of running instances based on the number of incoming requests…

    You can read more about this here.

    As cloud functions are auto scalabe you can write everything on one single trigger but I don’t think this is a good practice.

    I would write my code using multi triggers (onCreate, onUpdate, onDelete) instead of a single onWrite trigger because you’ll then have smaller (and easer to read/maintain) pieces of code.

    If you write everything on a single trigger maybe you’ll be doing unecessary calculation (eg. trying to send the data to third party while you don’t need this because it’s a delete event) and also increasing instance runtime wich can lead to a higger firebase billing.

    Login or Signup to reply.
  2. Separate onCreate, onUpdate, and onDelete triggers, or one common onWrite trigger?

    Usually, we use onWrite, when we want to do generic things, no matter what is the type of the change parameter. Otherwise, we use onCreate, onUpdate, and onDelete. As you can see, you’ll have to create 3 functions, and not 1, but you’ll pay only when the function runs. In this case, it won’t be more expensive to use 3 partially used functions, than a single always-used function.

    As @DougStevenson mentioned in his comment, it turns out that the initial question was related to the use of a single vs. three functions but you’re looking to get rid of an error. In my opinion, I think that you should consider using the Cloud Functions 2nd gen where you can have up to 1,000 concurrent requests served at the same time in a single instance. So I think you should take advantage of this feature.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search