Firebase: Cloud Functions, How to Cache a Firestore Document Snapshot

Viewed 2028

I have a Firebase Cloud Function that I call directly from my app. This cloud function fetches a collection of Firestore documents, iterating over each, then returns a result.

My question is, would it be best to keep the result of that fetch/get in memory (on the node server), refreshed with .onSnapshot? It seems this would improve performance as my cloud function would not have to wait for the Firestore response (it would already have the collection in memory). How would I do this? Simple as populating a global variable? How to do .onSnaphot realtime listener with cloud functions?

1 Answers

it might depend how large these snapshots are and how many of them may be cached ...

because, it is a RAM disk and without house-keeping it might only work for a limited time.

Always delete temporary files

Local disk storage in the temporary directory is an in-memory file-system. Files that you write consume memory available to your function, and sometimes persist between invocations. Failing to explicitly delete these files may eventually lead to an out-of-memory error and a subsequent cold start.

Source: Cloud Functions - Tips & Tricks.

It does not tell there, what exactly the hard-limit would be - and caching elsewhere might not improve access time that much. it says 2048mb per function, per default - while one can raise the quotas with IAM & admin. it all depends, if the quota per function can be raised far enough to handle the cache.

here's an example for the .onShapshot() event:

// for a single document:
var doc = db.collection('cities').doc('SF');

// this also works for multiple documents:
// var docs = db.collection('cities').where('state', '==', 'CA');

var observer = doc.onSnapshot(docSnapshot => {
 console.log(`Received doc snapshot: ${docSnapshot}`);
}, err => {
  console.log(`Encountered error: ${err}`);
});

// unsubscribe, to stop listening for changes:
var unsub = db.collection('cities').onSnapshot(() => {});
unsub();

Source: Get realtime updates with Cloud Firestore.

Cloud Firestore Triggers might be another option.

Related