0

I have written a Firebase Cloud Function that triggers when a document is created. After that, I am updating documents using batch update. I have only 5 documents in the "test" collection and it is taking 7-10 seconds to update these documents. My target is maximum of 2 seconds. Is this normal or it can be optimized more?

Code:


import * as functions from "firebase-functions";
import * as admin from 'firebase-admin';
admin.initializeApp();
const db = admin.firestore();


exports.onCreateOrder = functions.firestore.document('PPB/{id}/Orders/{order_id}').onCreate((snapshot, context) => {
  var userRef = db.collection('test');
  if (userRef != null) {
    let batch = db.batch();
    return userRef.get()
      .then(snapshot => {
        snapshot.forEach(doc => {
          batch.update(doc.ref, "name", "Paul");
        });
        return batch.commit();
      });
  } else {
    return null;
  }
}

);
Gourav B
  • 864
  • 5
  • 17
ali262883
  • 349
  • 3
  • 16

2 Answers2

1

As mentioned by Tarik Huber, Firebase Functions tend to have a greater execution time and it is because of the cold-start. I want to focus on how you can attempt to reduce the time further or optimise it.

As per this stackoverflow thread, the community member has mentioned several ways in which execution time of Firebase Functions can be improved from about 7-8s down to 2-3s

  1. “Requiring files and general initialisation happening in the global scope is a huge cause for slow-down during cold-boot”. As a project gets more functions the global scope is polluted more. It can be solved if you scope your functions into separate files. Also moving all the requires into an init method and then calling it as the first line inside any function definition for that file.
  2. You can have an index.js file that will import and list all the other Cloud Functions functions. One trick is to use the process.env.FUNCTION_TARGET env variable as here that will have the name of the function currently being triggered. During deployment that env variable is null.
  3. Also pinging the functions periodically doesn’t eliminate the cold starts entirely, it warms them up and makes them less frequent.
  4. Look for the tips, tricks and the common hacks mentioned here in the documentation to try and execute functions faster.
Priyashree Bhadra
  • 3,182
  • 6
  • 23
0

The code looks fine. I can't see anything you could do better. How did you measure the time the function needs to execute?

Make sure not to measure when the function is having a "cold start". The time you explain is quite the time a function would have for a "cold start".

Tarik Huber
  • 7,061
  • 2
  • 12
  • 18