Decrease document reads in Firestore, react app

Viewed 272

I am building a chat app in react using Firebase Firestore as backend database.

I get recent 25 messages in useEffect hook as

useEffect(() => {
    const q = query(
        collection(db, 'messages'),
        orderBy('createdAt', 'desc'),
        limit(25)
    );

    return onSnapshot(q, (snapshot) => {
        setData(
            snapshot.docs.map((doc) => {
                console.log('document read');
                return { ...doc.data(), id: doc.id };
            })
        );
    });
}, []);

But this operation results in 25 document reads on page load and 50 additional on sending a message. If more users are connected, 25 request per user happen on single message send by any user. Is there any way to reduce the reads?

Complete code:- https://github.com/Puneet56/Converse

1 Answers

You don't get 25 reads in a running query with a limit of 25 resulst if you get a new one inside. As the documentation says:

When you listen to the results of a query, you are charged for a read each time a document in the result set is added or updated. You are also charged for a read when a document is removed from the result set because the document has changed. (In contrast, when a document is deleted, you are not charged for a read.)

Also, if the listener is disconnected for more than 30 minutes (for example, if the user goes offline), you will be charged for reads as if you had issued a brand-new query.

As stated in the docs you will be charged only for the one that is added and the one that get's out of the query limit because a new one got in. So you get probably only 2 reads per new message. I think that is a reasonable amount. I can't any way to reduce this amount in a chat App. Even if you would increase the query limit only your inital reads (if it's a fresh read with no old or empty cache) will increas to but the reads while listening would stay the same.

Related