firebasefirebase-realtime-databasegoogle-cloud-firestoredatabase-designdenormalization

Increment counter across multiple subcollections


I am structuring the app where users can increment an attendee counter when they click "go" on an event. To simplify reads events are duplicated in "events" subcollections across users that follow a particular organizer. Every time a user clicks "go" on an event this counter has to be incremented across all subcollections. Is making a join a better alternative than denormalizing data in this case?


Solution

  • There is no "right" or "wrong" when it comes to modeling. If your app has its needs satisfied by what you've implemented, combined with knowledge of Firestore's limitations, do whatever you want.

    But if your goal is to avoid 10000 writes by performing an extra lookup, then by all means, save yourself that trouble and cost. You might want to do a cost or performance estimate of both approaches, and choose the one that's cheaper or faster, or whatever you need out of this solution.

    Bear in mind that there is a limitation of 500 documents in a single transaction, so if you need to update 10000 documents, you won't be able to do so atomically. It's possible that some documents simply might not get the update if your code isn't resilient to errors or incomplete work. That could be enough reason not to fan out a write to so many documents.