Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloud Functions (Firebase) - decrease cold start times through partial loading firebase modules?

Firebase docs recommend managing dependencies wisely as one of the first things you can do to decrease cold start times: https://firebase.google.com/docs/functions/tips#use_dependencies_wisely

For most Firebase functions, you'd likely be using the firebase-functions and firebase-admin modules.

Here is a practical example function:

const functions = require('firebase-functions');
const admin = require('firebase-admin');

// Initialize the app in admin sdk
admin.initializeApp();

// Firestore timestamp support
admin.firestore().settings({timestampsInSnapshots: true});

exports.simpleFunction = functions.https.onCall((data, context) => {
    return admin.auth().getUserByEmail(data.email)
        .catch(() => {
            return Promise.reject(new https.HttpsError('not-found', 'User not found.'));
        })
        .then(userRecord => {
            return admin.firestore().collection('user').doc(userRecord.uid).get();
        })
});

Cold start execution time: Function execution took 7517 ms, finished with status code: 200 Warm execution time: Function execution took 8 ms, finished with status code: 200

A test of this function, as shown, has a ~7.5 second cold start boot time (although remarkable warm response times). Although there are many factors as to why this may be the case, one reason could be loading all of the dependencies required by firebase-functions and firebase-admin.

Given that the example function only uses a few methods within either package, is it possible to somehow only load these methods and its dependencies to decrease the load times?

I've also tried using typescript and importing methods directly in the form of import {https} from 'firebase-functions' and import {initializeApp, firestore, auth} from 'firebase-admin' hoping some type of magical behind the scenes tree-shaking but it turns out that the typescript is transpiled to javascript in the end.

like image 784
yoonjesung Avatar asked Sep 01 '18 19:09

yoonjesung


1 Answers

There are a few strategies to decrease cold starts for firebase functions. Your strategy is on spot to try to reduce the dependencies.

1 contributor to GCF cold-boot performance is dependencies.

It doesn't seem possible the kind of granularity you want.

My suggestions are:

  • Try to use the version of the libraries that is more widely used. The dependency cache is shared across all GCF dependencies. There is a very good post about this subject from a guy from google. Check it out. Also, there is the video version

  • Use lazy loading for dependencies. There is a nice video explaining this strategy by @DougStevenson, a Firebase member. He also gives an example for using typescript.

  • Avoid crashes. If you function crashes it can increase cold starts.

like image 77
ajorquera Avatar answered Oct 10 '22 01:10

ajorquera