djalmafreestyler
djalmafreestyler

Reputation: 1909

Is it possible to add only new documents to Cloud Firestore cache?

I have an app that has 50k - 60k document reads a day and I can't afford another plan now, so I'm looking for a way to optimize reads, getting less reads possible I can.

The database has 4 collections with some subcollections, I think I might have around 1000 documents in the whole server.

It is there anyway: I can read documents from cloud Firestore (first time the user opens the app) and store on the Firestore cache, after that, make the app only load data from Firestore cache, and if there is a new document(s), it reads these documents only, store to the cache, and keep reading from the cache?

The app could only load data from cache (using the parameter "source") and never directly from Firestore, if possible.

Firestore.instance.collection("images").getDocuments(source: Source.cache);

Upvotes: 0

Views: 372

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138824

Is is there anyway: I can read documents from cloud Firestore (first time the user opens the app) and store on the Firestore cache

That's the default behavior. According to the official documentation regarding Firestore offline persistence:

  • For Android and iOS, offline persistence is enabled by default. To disable persistence, set the PersistenceEnabled option to false.

  • For the web, offline persistence is disabled by default. To enable persistence, call the enablePersistence method. Cloud Firestore's cache isn't automatically cleared between sessions. Consequently, if your web app handles sensitive information, make sure to ask the user if they're on a trusted device before enabling persistence.

So there is nothing special that you need to do. Once you open a stream on one of your collections, the data is added to the cache.

after that, make the app only load data from Firestore cache, and if there is a new document(s), it reads these documents only, stores to the cache, and keeps reading from the cache?

That's again the default behavior, but this work as long as the documents in your database are not changed. If a document in the database is changed, you'll be charged with a document read for each document. The mechanism is the same.

Besides that, you can tell Firestore to read data only from the cache if needed, as explained in the answer from the following post:

Upvotes: 1

Related Questions