0

I'm working on a chat app with a friends list feature and I need to know how to reduce the number of read calls to the database. The logged in user has a document with the name of their uid and contains their username (which can be changed), and their friends in a different subcollection with two documents (one for requests and one for accepted friends). The problem is that I want to be able to list all of the user's friends to display, but I don't know how to do that without having to make an absurd amount of reads. The user would have to go through and fetch the username for all of their friends, so if the user has 50 friends, 50 reads. I was also thinking that I could have a document with all of the users in a map (uid: username), but that would be slow since you have to fetch all of the users, and the 1MB per document rule gets in the way, so I would have to split it up into multiple documents, which wouldn't scale well because it could eventually be worse than the first solution depending on how many friends the user has.

Firestore structure

How would I implement a feature such as a friends list with the least amount of document reads?

Would I be better off using Realtime Database for a chat app like this?

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
User-92
  • 374
  • 3
  • 13
  • Reading 50 documents is not "absurd". That's actually pretty common and not as expensive or lengthy as you think. Just keep the documents small and you'll be OK. You can try to cram data into a single document, but that is going to cause you other bigger problems later. – Doug Stevenson Mar 04 '23 at 20:06
  • @DougStevenson 50 was just an example. It can be much more – User-92 Mar 04 '23 at 20:46
  • 3
    I guess it's time to measure or benchmark your worst case scenario to see what the real cost is. It sounds like you might be trying to optimize something that isn't yet known to be problematic. – Doug Stevenson Mar 04 '23 at 22:15
  • Perhaps this [answer](https://stackoverflow.com/questions/53053768/what-is-the-correct-way-to-structure-this-kind-of-data-in-firestore/53057707#53057707) will also help. – Alex Mamo Mar 06 '23 at 09:20

0 Answers0