Search code examples
firebasegoogle-cloud-firestore

Firebase: Understanding reads and caching


I am trying to understand whether I need to implement additional logic for caching to reduce the number of reads for my future app. I have read about Firebase and it seems as if I am only charged reads if a document is not already in the cache. That is, if I query an entire collection, but only one document is new, I am only charged one read as long as I have enabled persistence and caching. Is that correct?

If it is, it seems that Firebase comes with all the caching logic one needs to prevent unnecessary reads with every app start. Say I have about 500 documents overall in my DB and 10000 daily users, then, given I do not create new documents, I will have only

new users * 500 + existing users * app starts * queries per session

reads, as one read is charged whenever something is queried.

If what I am saying is incorrect, I would be very grateful for insights into how reads are actually charged.


Solution

  • That is, if I query an entire collection, but only one document is new, I am only charged one read as long as I have enabled persistence and caching. Is that correct?

    No, that is not correct.

    By default, all query results come from the backend, and you pay for each document read for each of those queries. The local cache is only used if the backend isn't available (your app is offline), or your query specifically requests documents from the cache (using the source option) instead of the backend.

    From the linked documentation:

    By default, a get call will attempt to fetch the latest document snapshot from your database. On platforms with offline support, the client library will use the offline cache if the network is unavailable or if the request times out.

    You can specify the source option in a get() call to change the default behavior. You can fetch from only the database and ignore the offline cache, or you can fetch from only the offline cache.

    See also: