2

I have a website that stores data in Cloud Firestore. Every minute, the database gets updated when I go out to various APIs and store new data in it.

I need to provide the user this updated data every minute. Currently, I have it so that every minute, the user's browser will make a new Cloud Function call, which then goes out to the Cloud Firestore and gets the new data. However, imagine if a user were to leave their browser open all day - that would result in 1,440 requests.

Cloud Functions only provides me 2,000,000 requests for free, and if I had many users, those requests would get eaten up quite quickly. Is there a better way for me to give the user this data every minute and not eat up my Cloud Functions quota? Perhaps I could make my own Socket and have the user connect to that? Though I'd have to see how I could update that socket every minute without adding too much to the quota.

Mike K.
  • 543
  • 3
  • 14
  • 46

1 Answers1

2

Firebase allows your clients to directly connection to Cloud Firestore, where they can then listen for realtime updates. This saves them from having to poll for that data, and removes the need for the Cloud Function.

Attaching a real time listener can be as simple as (from the documentation):

 db.collection("cities").doc("SF")
    .onSnapshot(function(doc) {
        console.log("Current data: ", doc.data());
    });

The onSnapshot callback above will trigger whenever the /cities/SF document is updated. Similarly you can attach a listener to the entire collection.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thanks - And what is generally the best way for me to know when to call the 'Detach a listener' code? I would probably want to detach it if their computer is idle for an hour or something . . . or if their computer goes to sleep . . . or if the user turns their cell phone off. And then I'd have to figure out how to reattach the listener once they come back on. Not quite sure how to do these things though. – Mike K. May 31 '18 at 12:49
  • It depends a bit on the phone, but in general you'll tie into the lifecycle events of the OS to attach/detach the listeners. I.e. https://stackoverflow.com/questions/8515936/android-activity-life-cycle-what-are-all-these-methods-for – Frank van Puffelen May 31 '18 at 13:15