Speed Up Firebase Cold Starts with Firestore REST Calls

If you use serverless cloud capabilities on AWS or Google Cloud, you know the pain of a cold start. Firebase functions are notorious for cold start problems and I’ve written about Firebase cold start solutions before. Most of these solutions require code rewriting, such as dynamic import modules or the new Google Cloud Functions v2 where a Node.js instance can handle multiple requests.

Suddenly, Firebase secret announcement New features to help cold start, preferRest.

The Cloud Firestore API is now preferRest Force the REST transport to be enabled until an operation requires gRPC.

What does this mean? hidden in Firebase Github Ticket Here is the explanation:

I have a long standing issue with very slow cold start times when using the official Nodejs Firestore library in a serverless environment. https://issuetracker.google.com/issues/158014637. The underlying problem is very difficult to fix (hence the unresolved, years old P1/S1 issue) and a suitable temporary fix seems long overdue.

One solution is to use the Firestore REST API directly. This greatly improves cold start time, but severely degrades the developer experience. Firestore users unofficial wrapper library (https://github.com/bountyrush/nodejs-firestore). This library works, but is maintained by a single developer and for obvious reasons does not replace the official library.

By default there is no overhead of gRPC and using direct REST Firestore calls can potentially reduce Firebase cold start times.

How to implement Firestore REST call with preferRest

We mentioned before the “covert” release, and we mean it. There is a new way to initialize Firestore in a function which is not mentioned in the formula. Firebase documentation.

In general, you initialize Firestore in Node.js by doing the following (see the documentation for examples in other programming languages):

const { initializeApp, applicationDefault, cert } = require('firebase-admin/app');
const { getFirestore, Timestamp, FieldValue } = require('firebase-admin/firestore');

initializeApp({
  credential: applicationDefault()
});

const db = getFirestore();

use getFirestore() Ability to create database instances.

If you want to set preferRestFirestore needs to be initialized slightly differently: initializeFirestore:

const { initializeApp, applicationDefault, cert } = require('firebase-admin/app');
const { initializeFirestore, Timestamp, FieldValue } = require('firebase-admin/firestore');

const app = initializeApp({
  credential: applicationDefault()
});

const db = const db = initializeFirestore(app, { preferRest: true });

passed to initialization app and object { preferRest: true }. It’s that simple!

This is a new feature, so you should test it thoroughly before rolling it out to production. “I haven’t tried it myself yet,” said Puf, a Firebase fan favorite.

Source

Explore additional categories

Explore Other Classes